clang  9.0.0
ExprConstant.cpp
Go to the documentation of this file.
1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 // * A success/failure flag indicating whether constant folding was successful.
14 // This is the 'bool' return value used by most of the code in this file. A
15 // 'false' return value indicates that constant folding has failed, and any
16 // appropriate diagnostic has already been produced.
17 //
18 // * An evaluated result, valid only if constant folding has not failed.
19 //
20 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 // where it is possible to determine the evaluated result regardless.
23 //
24 // * A set of notes indicating why the evaluation was not a constant expression
25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 // too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CharUnits.h"
42 #include "clang/AST/Expr.h"
43 #include "clang/AST/OSLog.h"
44 #include "clang/AST/RecordLayout.h"
45 #include "clang/AST/StmtVisitor.h"
46 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/FixedPoint.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SmallBitVector.h"
52 #include "llvm/Support/SaveAndRestore.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <cstring>
55 #include <functional>
56 
57 #define DEBUG_TYPE "exprconstant"
58 
59 using namespace clang;
60 using llvm::APInt;
61 using llvm::APSInt;
62 using llvm::APFloat;
63 using llvm::Optional;
64 
65 static bool IsGlobalLValue(APValue::LValueBase B);
66 
67 namespace {
68  struct LValue;
69  struct CallStackFrame;
70  struct EvalInfo;
71 
72  using SourceLocExprScopeGuard =
74 
75  static QualType getType(APValue::LValueBase B) {
76  if (!B) return QualType();
77  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
78  // FIXME: It's unclear where we're supposed to take the type from, and
79  // this actually matters for arrays of unknown bound. Eg:
80  //
81  // extern int arr[]; void f() { extern int arr[3]; };
82  // constexpr int *p = &arr[1]; // valid?
83  //
84  // For now, we take the array bound from the most recent declaration.
85  for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
86  Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
87  QualType T = Redecl->getType();
88  if (!T->isIncompleteArrayType())
89  return T;
90  }
91  return D->getType();
92  }
93 
94  if (B.is<TypeInfoLValue>())
95  return B.getTypeInfoType();
96 
97  const Expr *Base = B.get<const Expr*>();
98 
99  // For a materialized temporary, the type of the temporary we materialized
100  // may not be the type of the expression.
101  if (const MaterializeTemporaryExpr *MTE =
102  dyn_cast<MaterializeTemporaryExpr>(Base)) {
105  const Expr *Temp = MTE->GetTemporaryExpr();
106  const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
107  Adjustments);
108  // Keep any cv-qualifiers from the reference if we generated a temporary
109  // for it directly. Otherwise use the type after adjustment.
110  if (!Adjustments.empty())
111  return Inner->getType();
112  }
113 
114  return Base->getType();
115  }
116 
117  /// Get an LValue path entry, which is known to not be an array index, as a
118  /// field declaration.
119  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
120  return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
121  }
122  /// Get an LValue path entry, which is known to not be an array index, as a
123  /// base class declaration.
124  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
125  return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
126  }
127  /// Determine whether this LValue path entry for a base class names a virtual
128  /// base class.
129  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
130  return E.getAsBaseOrMember().getInt();
131  }
132 
133  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
134  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
135  const FunctionDecl *Callee = CE->getDirectCallee();
136  return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
137  }
138 
139  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
140  /// This will look through a single cast.
141  ///
142  /// Returns null if we couldn't unwrap a function with alloc_size.
143  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
144  if (!E->getType()->isPointerType())
145  return nullptr;
146 
147  E = E->IgnoreParens();
148  // If we're doing a variable assignment from e.g. malloc(N), there will
149  // probably be a cast of some kind. In exotic cases, we might also see a
150  // top-level ExprWithCleanups. Ignore them either way.
151  if (const auto *FE = dyn_cast<FullExpr>(E))
152  E = FE->getSubExpr()->IgnoreParens();
153 
154  if (const auto *Cast = dyn_cast<CastExpr>(E))
155  E = Cast->getSubExpr()->IgnoreParens();
156 
157  if (const auto *CE = dyn_cast<CallExpr>(E))
158  return getAllocSizeAttr(CE) ? CE : nullptr;
159  return nullptr;
160  }
161 
162  /// Determines whether or not the given Base contains a call to a function
163  /// with the alloc_size attribute.
164  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
165  const auto *E = Base.dyn_cast<const Expr *>();
166  return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
167  }
168 
169  /// The bound to claim that an array of unknown bound has.
170  /// The value in MostDerivedArraySize is undefined in this case. So, set it
171  /// to an arbitrary value that's likely to loudly break things if it's used.
172  static const uint64_t AssumedSizeForUnsizedArray =
174 
175  /// Determines if an LValue with the given LValueBase will have an unsized
176  /// array in its designator.
177  /// Find the path length and type of the most-derived subobject in the given
178  /// path, and find the size of the containing array, if any.
179  static unsigned
180  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
182  uint64_t &ArraySize, QualType &Type, bool &IsArray,
183  bool &FirstEntryIsUnsizedArray) {
184  // This only accepts LValueBases from APValues, and APValues don't support
185  // arrays that lack size info.
186  assert(!isBaseAnAllocSizeCall(Base) &&
187  "Unsized arrays shouldn't appear here");
188  unsigned MostDerivedLength = 0;
189  Type = getType(Base);
190 
191  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
192  if (Type->isArrayType()) {
193  const ArrayType *AT = Ctx.getAsArrayType(Type);
194  Type = AT->getElementType();
195  MostDerivedLength = I + 1;
196  IsArray = true;
197 
198  if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
199  ArraySize = CAT->getSize().getZExtValue();
200  } else {
201  assert(I == 0 && "unexpected unsized array designator");
202  FirstEntryIsUnsizedArray = true;
203  ArraySize = AssumedSizeForUnsizedArray;
204  }
205  } else if (Type->isAnyComplexType()) {
206  const ComplexType *CT = Type->castAs<ComplexType>();
207  Type = CT->getElementType();
208  ArraySize = 2;
209  MostDerivedLength = I + 1;
210  IsArray = true;
211  } else if (const FieldDecl *FD = getAsField(Path[I])) {
212  Type = FD->getType();
213  ArraySize = 0;
214  MostDerivedLength = I + 1;
215  IsArray = false;
216  } else {
217  // Path[I] describes a base class.
218  ArraySize = 0;
219  IsArray = false;
220  }
221  }
222  return MostDerivedLength;
223  }
224 
225  // The order of this enum is important for diagnostics.
227  CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
228  CSK_Real, CSK_Imag
229  };
230 
231  /// A path from a glvalue to a subobject of that glvalue.
232  struct SubobjectDesignator {
233  /// True if the subobject was named in a manner not supported by C++11. Such
234  /// lvalues can still be folded, but they are not core constant expressions
235  /// and we cannot perform lvalue-to-rvalue conversions on them.
236  unsigned Invalid : 1;
237 
238  /// Is this a pointer one past the end of an object?
239  unsigned IsOnePastTheEnd : 1;
240 
241  /// Indicator of whether the first entry is an unsized array.
242  unsigned FirstEntryIsAnUnsizedArray : 1;
243 
244  /// Indicator of whether the most-derived object is an array element.
245  unsigned MostDerivedIsArrayElement : 1;
246 
247  /// The length of the path to the most-derived object of which this is a
248  /// subobject.
249  unsigned MostDerivedPathLength : 28;
250 
251  /// The size of the array of which the most-derived object is an element.
252  /// This will always be 0 if the most-derived object is not an array
253  /// element. 0 is not an indicator of whether or not the most-derived object
254  /// is an array, however, because 0-length arrays are allowed.
255  ///
256  /// If the current array is an unsized array, the value of this is
257  /// undefined.
258  uint64_t MostDerivedArraySize;
259 
260  /// The type of the most derived object referred to by this address.
261  QualType MostDerivedType;
262 
263  typedef APValue::LValuePathEntry PathEntry;
264 
265  /// The entries on the path from the glvalue to the designated subobject.
267 
268  SubobjectDesignator() : Invalid(true) {}
269 
270  explicit SubobjectDesignator(QualType T)
271  : Invalid(false), IsOnePastTheEnd(false),
272  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
273  MostDerivedPathLength(0), MostDerivedArraySize(0),
274  MostDerivedType(T) {}
275 
276  SubobjectDesignator(ASTContext &Ctx, const APValue &V)
277  : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
278  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279  MostDerivedPathLength(0), MostDerivedArraySize(0) {
280  assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
281  if (!Invalid) {
282  IsOnePastTheEnd = V.isLValueOnePastTheEnd();
283  ArrayRef<PathEntry> VEntries = V.getLValuePath();
284  Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
285  if (V.getLValueBase()) {
286  bool IsArray = false;
287  bool FirstIsUnsizedArray = false;
288  MostDerivedPathLength = findMostDerivedSubobject(
289  Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
290  MostDerivedType, IsArray, FirstIsUnsizedArray);
291  MostDerivedIsArrayElement = IsArray;
292  FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
293  }
294  }
295  }
296 
297  void truncate(ASTContext &Ctx, APValue::LValueBase Base,
298  unsigned NewLength) {
299  if (Invalid)
300  return;
301 
302  assert(Base && "cannot truncate path for null pointer");
303  assert(NewLength <= Entries.size() && "not a truncation");
304 
305  if (NewLength == Entries.size())
306  return;
307  Entries.resize(NewLength);
308 
309  bool IsArray = false;
310  bool FirstIsUnsizedArray = false;
311  MostDerivedPathLength = findMostDerivedSubobject(
312  Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
313  FirstIsUnsizedArray);
314  MostDerivedIsArrayElement = IsArray;
315  FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
316  }
317 
318  void setInvalid() {
319  Invalid = true;
320  Entries.clear();
321  }
322 
323  /// Determine whether the most derived subobject is an array without a
324  /// known bound.
325  bool isMostDerivedAnUnsizedArray() const {
326  assert(!Invalid && "Calling this makes no sense on invalid designators");
327  return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
328  }
329 
330  /// Determine what the most derived array's size is. Results in an assertion
331  /// failure if the most derived array lacks a size.
332  uint64_t getMostDerivedArraySize() const {
333  assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
334  return MostDerivedArraySize;
335  }
336 
337  /// Determine whether this is a one-past-the-end pointer.
338  bool isOnePastTheEnd() const {
339  assert(!Invalid);
340  if (IsOnePastTheEnd)
341  return true;
342  if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
343  Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
344  MostDerivedArraySize)
345  return true;
346  return false;
347  }
348 
349  /// Get the range of valid index adjustments in the form
350  /// {maximum value that can be subtracted from this pointer,
351  /// maximum value that can be added to this pointer}
352  std::pair<uint64_t, uint64_t> validIndexAdjustments() {
353  if (Invalid || isMostDerivedAnUnsizedArray())
354  return {0, 0};
355 
356  // [expr.add]p4: For the purposes of these operators, a pointer to a
357  // nonarray object behaves the same as a pointer to the first element of
358  // an array of length one with the type of the object as its element type.
359  bool IsArray = MostDerivedPathLength == Entries.size() &&
360  MostDerivedIsArrayElement;
361  uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
362  : (uint64_t)IsOnePastTheEnd;
363  uint64_t ArraySize =
364  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
365  return {ArrayIndex, ArraySize - ArrayIndex};
366  }
367 
368  /// Check that this refers to a valid subobject.
369  bool isValidSubobject() const {
370  if (Invalid)
371  return false;
372  return !isOnePastTheEnd();
373  }
374  /// Check that this refers to a valid subobject, and if not, produce a
375  /// relevant diagnostic and set the designator as invalid.
376  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
377 
378  /// Get the type of the designated object.
379  QualType getType(ASTContext &Ctx) const {
380  assert(!Invalid && "invalid designator has no subobject type");
381  return MostDerivedPathLength == Entries.size()
382  ? MostDerivedType
383  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
384  }
385 
386  /// Update this designator to refer to the first element within this array.
387  void addArrayUnchecked(const ConstantArrayType *CAT) {
388  Entries.push_back(PathEntry::ArrayIndex(0));
389 
390  // This is a most-derived object.
391  MostDerivedType = CAT->getElementType();
392  MostDerivedIsArrayElement = true;
393  MostDerivedArraySize = CAT->getSize().getZExtValue();
394  MostDerivedPathLength = Entries.size();
395  }
396  /// Update this designator to refer to the first element within the array of
397  /// elements of type T. This is an array of unknown size.
398  void addUnsizedArrayUnchecked(QualType ElemTy) {
399  Entries.push_back(PathEntry::ArrayIndex(0));
400 
401  MostDerivedType = ElemTy;
402  MostDerivedIsArrayElement = true;
403  // The value in MostDerivedArraySize is undefined in this case. So, set it
404  // to an arbitrary value that's likely to loudly break things if it's
405  // used.
406  MostDerivedArraySize = AssumedSizeForUnsizedArray;
407  MostDerivedPathLength = Entries.size();
408  }
409  /// Update this designator to refer to the given base or member of this
410  /// object.
411  void addDeclUnchecked(const Decl *D, bool Virtual = false) {
412  Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
413 
414  // If this isn't a base class, it's a new most-derived object.
415  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
416  MostDerivedType = FD->getType();
417  MostDerivedIsArrayElement = false;
418  MostDerivedArraySize = 0;
419  MostDerivedPathLength = Entries.size();
420  }
421  }
422  /// Update this designator to refer to the given complex component.
423  void addComplexUnchecked(QualType EltTy, bool Imag) {
424  Entries.push_back(PathEntry::ArrayIndex(Imag));
425 
426  // This is technically a most-derived object, though in practice this
427  // is unlikely to matter.
428  MostDerivedType = EltTy;
429  MostDerivedIsArrayElement = true;
430  MostDerivedArraySize = 2;
431  MostDerivedPathLength = Entries.size();
432  }
433  void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
434  void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
435  const APSInt &N);
436  /// Add N to the address of this subobject.
437  void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
438  if (Invalid || !N) return;
439  uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
440  if (isMostDerivedAnUnsizedArray()) {
441  diagnoseUnsizedArrayPointerArithmetic(Info, E);
442  // Can't verify -- trust that the user is doing the right thing (or if
443  // not, trust that the caller will catch the bad behavior).
444  // FIXME: Should we reject if this overflows, at least?
445  Entries.back() = PathEntry::ArrayIndex(
446  Entries.back().getAsArrayIndex() + TruncatedN);
447  return;
448  }
449 
450  // [expr.add]p4: For the purposes of these operators, a pointer to a
451  // nonarray object behaves the same as a pointer to the first element of
452  // an array of length one with the type of the object as its element type.
453  bool IsArray = MostDerivedPathLength == Entries.size() &&
454  MostDerivedIsArrayElement;
455  uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
456  : (uint64_t)IsOnePastTheEnd;
457  uint64_t ArraySize =
458  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
459 
460  if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
461  // Calculate the actual index in a wide enough type, so we can include
462  // it in the note.
463  N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
464  (llvm::APInt&)N += ArrayIndex;
465  assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
466  diagnosePointerArithmetic(Info, E, N);
467  setInvalid();
468  return;
469  }
470 
471  ArrayIndex += TruncatedN;
472  assert(ArrayIndex <= ArraySize &&
473  "bounds check succeeded for out-of-bounds index");
474 
475  if (IsArray)
476  Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
477  else
478  IsOnePastTheEnd = (ArrayIndex != 0);
479  }
480  };
481 
482  /// A stack frame in the constexpr call stack.
483  struct CallStackFrame {
484  EvalInfo &Info;
485 
486  /// Parent - The caller of this stack frame.
487  CallStackFrame *Caller;
488 
489  /// Callee - The function which was called.
490  const FunctionDecl *Callee;
491 
492  /// This - The binding for the this pointer in this call, if any.
493  const LValue *This;
494 
495  /// Arguments - Parameter bindings for this function call, indexed by
496  /// parameters' function scope indices.
497  APValue *Arguments;
498 
499  /// Source location information about the default argument or default
500  /// initializer expression we're evaluating, if any.
501  CurrentSourceLocExprScope CurSourceLocExprScope;
502 
503  // Note that we intentionally use std::map here so that references to
504  // values are stable.
505  typedef std::pair<const void *, unsigned> MapKeyTy;
506  typedef std::map<MapKeyTy, APValue> MapTy;
507  /// Temporaries - Temporary lvalues materialized within this stack frame.
508  MapTy Temporaries;
509 
510  /// CallLoc - The location of the call expression for this call.
511  SourceLocation CallLoc;
512 
513  /// Index - The call index of this call.
514  unsigned Index;
515 
516  /// The stack of integers for tracking version numbers for temporaries.
517  SmallVector<unsigned, 2> TempVersionStack = {1};
518  unsigned CurTempVersion = TempVersionStack.back();
519 
520  unsigned getTempVersion() const { return TempVersionStack.back(); }
521 
522  void pushTempVersion() {
523  TempVersionStack.push_back(++CurTempVersion);
524  }
525 
526  void popTempVersion() {
527  TempVersionStack.pop_back();
528  }
529 
530  // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
531  // on the overall stack usage of deeply-recursing constexpr evaluations.
532  // (We should cache this map rather than recomputing it repeatedly.)
533  // But let's try this and see how it goes; we can look into caching the map
534  // as a later change.
535 
536  /// LambdaCaptureFields - Mapping from captured variables/this to
537  /// corresponding data members in the closure class.
538  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
539  FieldDecl *LambdaThisCaptureField;
540 
541  CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542  const FunctionDecl *Callee, const LValue *This,
543  APValue *Arguments);
544  ~CallStackFrame();
545 
546  // Return the temporary for Key whose version number is Version.
547  APValue *getTemporary(const void *Key, unsigned Version) {
548  MapKeyTy KV(Key, Version);
549  auto LB = Temporaries.lower_bound(KV);
550  if (LB != Temporaries.end() && LB->first == KV)
551  return &LB->second;
552  // Pair (Key,Version) wasn't found in the map. Check that no elements
553  // in the map have 'Key' as their key.
554  assert((LB == Temporaries.end() || LB->first.first != Key) &&
555  (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
556  "Element with key 'Key' found in map");
557  return nullptr;
558  }
559 
560  // Return the current temporary for Key in the map.
561  APValue *getCurrentTemporary(const void *Key) {
562  auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
563  if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
564  return &std::prev(UB)->second;
565  return nullptr;
566  }
567 
568  // Return the version number of the current temporary for Key.
569  unsigned getCurrentTemporaryVersion(const void *Key) const {
570  auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571  if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572  return std::prev(UB)->first.second;
573  return 0;
574  }
575 
576  APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
577  };
578 
579  /// Temporarily override 'this'.
580  class ThisOverrideRAII {
581  public:
582  ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
583  : Frame(Frame), OldThis(Frame.This) {
584  if (Enable)
585  Frame.This = NewThis;
586  }
587  ~ThisOverrideRAII() {
588  Frame.This = OldThis;
589  }
590  private:
591  CallStackFrame &Frame;
592  const LValue *OldThis;
593  };
594 
595  /// A partial diagnostic which we might know in advance that we are not going
596  /// to emit.
597  class OptionalDiagnostic {
599 
600  public:
601  explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
602  : Diag(Diag) {}
603 
604  template<typename T>
605  OptionalDiagnostic &operator<<(const T &v) {
606  if (Diag)
607  *Diag << v;
608  return *this;
609  }
610 
611  OptionalDiagnostic &operator<<(const APSInt &I) {
612  if (Diag) {
613  SmallVector<char, 32> Buffer;
614  I.toString(Buffer);
615  *Diag << StringRef(Buffer.data(), Buffer.size());
616  }
617  return *this;
618  }
619 
620  OptionalDiagnostic &operator<<(const APFloat &F) {
621  if (Diag) {
622  // FIXME: Force the precision of the source value down so we don't
623  // print digits which are usually useless (we don't really care here if
624  // we truncate a digit by accident in edge cases). Ideally,
625  // APFloat::toString would automatically print the shortest
626  // representation which rounds to the correct value, but it's a bit
627  // tricky to implement.
628  unsigned precision =
629  llvm::APFloat::semanticsPrecision(F.getSemantics());
630  precision = (precision * 59 + 195) / 196;
631  SmallVector<char, 32> Buffer;
632  F.toString(Buffer, precision);
633  *Diag << StringRef(Buffer.data(), Buffer.size());
634  }
635  return *this;
636  }
637 
638  OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
639  if (Diag) {
640  SmallVector<char, 32> Buffer;
641  FX.toString(Buffer);
642  *Diag << StringRef(Buffer.data(), Buffer.size());
643  }
644  return *this;
645  }
646  };
647 
648  /// A cleanup, and a flag indicating whether it is lifetime-extended.
649  class Cleanup {
650  llvm::PointerIntPair<APValue*, 1, bool> Value;
651 
652  public:
653  Cleanup(APValue *Val, bool IsLifetimeExtended)
654  : Value(Val, IsLifetimeExtended) {}
655 
656  bool isLifetimeExtended() const { return Value.getInt(); }
657  void endLifetime() {
658  *Value.getPointer() = APValue();
659  }
660  };
661 
662  /// A reference to an object whose construction we are currently evaluating.
663  struct ObjectUnderConstruction {
664  APValue::LValueBase Base;
666  friend bool operator==(const ObjectUnderConstruction &LHS,
667  const ObjectUnderConstruction &RHS) {
668  return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669  }
670  friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671  return llvm::hash_combine(Obj.Base, Obj.Path);
672  }
673  };
674  enum class ConstructionPhase { None, Bases, AfterBases };
675 }
676 
677 namespace llvm {
678 template<> struct DenseMapInfo<ObjectUnderConstruction> {
680  static ObjectUnderConstruction getEmptyKey() {
681  return {Base::getEmptyKey(), {}}; }
682  static ObjectUnderConstruction getTombstoneKey() {
683  return {Base::getTombstoneKey(), {}};
684  }
685  static unsigned getHashValue(const ObjectUnderConstruction &Object) {
686  return hash_value(Object);
687  }
688  static bool isEqual(const ObjectUnderConstruction &LHS,
689  const ObjectUnderConstruction &RHS) {
690  return LHS == RHS;
691  }
692 };
693 }
694 
695 namespace {
696  /// EvalInfo - This is a private struct used by the evaluator to capture
697  /// information about a subexpression as it is folded. It retains information
698  /// about the AST context, but also maintains information about the folded
699  /// expression.
700  ///
701  /// If an expression could be evaluated, it is still possible it is not a C
702  /// "integer constant expression" or constant expression. If not, this struct
703  /// captures information about how and why not.
704  ///
705  /// One bit of information passed *into* the request for constant folding
706  /// indicates whether the subexpression is "evaluated" or not according to C
707  /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
708  /// evaluate the expression regardless of what the RHS is, but C only allows
709  /// certain things in certain situations.
710  struct EvalInfo {
711  ASTContext &Ctx;
712 
713  /// EvalStatus - Contains information about the evaluation.
714  Expr::EvalStatus &EvalStatus;
715 
716  /// CurrentCall - The top of the constexpr call stack.
717  CallStackFrame *CurrentCall;
718 
719  /// CallStackDepth - The number of calls in the call stack right now.
720  unsigned CallStackDepth;
721 
722  /// NextCallIndex - The next call index to assign.
723  unsigned NextCallIndex;
724 
725  /// StepsLeft - The remaining number of evaluation steps we're permitted
726  /// to perform. This is essentially a limit for the number of statements
727  /// we will evaluate.
728  unsigned StepsLeft;
729 
730  /// BottomFrame - The frame in which evaluation started. This must be
731  /// initialized after CurrentCall and CallStackDepth.
732  CallStackFrame BottomFrame;
733 
734  /// A stack of values whose lifetimes end at the end of some surrounding
735  /// evaluation frame.
736  llvm::SmallVector<Cleanup, 16> CleanupStack;
737 
738  /// EvaluatingDecl - This is the declaration whose initializer is being
739  /// evaluated, if any.
740  APValue::LValueBase EvaluatingDecl;
741 
742  /// EvaluatingDeclValue - This is the value being constructed for the
743  /// declaration whose initializer is being evaluated, if any.
744  APValue *EvaluatingDeclValue;
745 
746  /// Set of objects that are currently being constructed.
747  llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
748  ObjectsUnderConstruction;
749 
750  struct EvaluatingConstructorRAII {
751  EvalInfo &EI;
752  ObjectUnderConstruction Object;
753  bool DidInsert;
754  EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
755  bool HasBases)
756  : EI(EI), Object(Object) {
757  DidInsert =
758  EI.ObjectsUnderConstruction
759  .insert({Object, HasBases ? ConstructionPhase::Bases
760  : ConstructionPhase::AfterBases})
761  .second;
762  }
763  void finishedConstructingBases() {
764  EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
765  }
766  ~EvaluatingConstructorRAII() {
767  if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
768  }
769  };
770 
772  isEvaluatingConstructor(APValue::LValueBase Base,
774  return ObjectsUnderConstruction.lookup({Base, Path});
775  }
776 
777  /// If we're currently speculatively evaluating, the outermost call stack
778  /// depth at which we can mutate state, otherwise 0.
779  unsigned SpeculativeEvaluationDepth = 0;
780 
781  /// The current array initialization index, if we're performing array
782  /// initialization.
783  uint64_t ArrayInitIndex = -1;
784 
785  /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
786  /// notes attached to it will also be stored, otherwise they will not be.
787  bool HasActiveDiagnostic;
788 
789  /// Have we emitted a diagnostic explaining why we couldn't constant
790  /// fold (not just why it's not strictly a constant expression)?
791  bool HasFoldFailureDiagnostic;
792 
793  /// Whether or not we're in a context where the front end requires a
794  /// constant value.
795  bool InConstantContext;
796 
797  enum EvaluationMode {
798  /// Evaluate as a constant expression. Stop if we find that the expression
799  /// is not a constant expression.
800  EM_ConstantExpression,
801 
802  /// Evaluate as a potential constant expression. Keep going if we hit a
803  /// construct that we can't evaluate yet (because we don't yet know the
804  /// value of something) but stop if we hit something that could never be
805  /// a constant expression.
806  EM_PotentialConstantExpression,
807 
808  /// Fold the expression to a constant. Stop if we hit a side-effect that
809  /// we can't model.
810  EM_ConstantFold,
811 
812  /// Evaluate the expression looking for integer overflow and similar
813  /// issues. Don't worry about side-effects, and try to visit all
814  /// subexpressions.
815  EM_EvaluateForOverflow,
816 
817  /// Evaluate in any way we know how. Don't worry about side-effects that
818  /// can't be modeled.
819  EM_IgnoreSideEffects,
820 
821  /// Evaluate as a constant expression. Stop if we find that the expression
822  /// is not a constant expression. Some expressions can be retried in the
823  /// optimizer if we don't constant fold them here, but in an unevaluated
824  /// context we try to fold them immediately since the optimizer never
825  /// gets a chance to look at it.
826  EM_ConstantExpressionUnevaluated,
827 
828  /// Evaluate as a potential constant expression. Keep going if we hit a
829  /// construct that we can't evaluate yet (because we don't yet know the
830  /// value of something) but stop if we hit something that could never be
831  /// a constant expression. Some expressions can be retried in the
832  /// optimizer if we don't constant fold them here, but in an unevaluated
833  /// context we try to fold them immediately since the optimizer never
834  /// gets a chance to look at it.
835  EM_PotentialConstantExpressionUnevaluated,
836  } EvalMode;
837 
838  /// Are we checking whether the expression is a potential constant
839  /// expression?
840  bool checkingPotentialConstantExpression() const {
841  return EvalMode == EM_PotentialConstantExpression ||
842  EvalMode == EM_PotentialConstantExpressionUnevaluated;
843  }
844 
845  /// Are we checking an expression for overflow?
846  // FIXME: We should check for any kind of undefined or suspicious behavior
847  // in such constructs, not just overflow.
848  bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
849 
850  EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
851  : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
852  CallStackDepth(0), NextCallIndex(1),
853  StepsLeft(getLangOpts().ConstexprStepLimit),
854  BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
855  EvaluatingDecl((const ValueDecl *)nullptr),
856  EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
857  HasFoldFailureDiagnostic(false),
858  InConstantContext(false), EvalMode(Mode) {}
859 
860  void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
861  EvaluatingDecl = Base;
862  EvaluatingDeclValue = &Value;
863  }
864 
865  const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
866 
867  bool CheckCallLimit(SourceLocation Loc) {
868  // Don't perform any constexpr calls (other than the call we're checking)
869  // when checking a potential constant expression.
870  if (checkingPotentialConstantExpression() && CallStackDepth > 1)
871  return false;
872  if (NextCallIndex == 0) {
873  // NextCallIndex has wrapped around.
874  FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
875  return false;
876  }
877  if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
878  return true;
879  FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
880  << getLangOpts().ConstexprCallDepth;
881  return false;
882  }
883 
884  std::pair<CallStackFrame *, unsigned>
885  getCallFrameAndDepth(unsigned CallIndex) {
886  assert(CallIndex && "no call index in getCallFrameAndDepth");
887  // We will eventually hit BottomFrame, which has Index 1, so Frame can't
888  // be null in this loop.
889  unsigned Depth = CallStackDepth;
890  CallStackFrame *Frame = CurrentCall;
891  while (Frame->Index > CallIndex) {
892  Frame = Frame->Caller;
893  --Depth;
894  }
895  if (Frame->Index == CallIndex)
896  return {Frame, Depth};
897  return {nullptr, 0};
898  }
899 
900  bool nextStep(const Stmt *S) {
901  if (!StepsLeft) {
902  FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
903  return false;
904  }
905  --StepsLeft;
906  return true;
907  }
908 
909  private:
910  /// Add a diagnostic to the diagnostics list.
911  PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
912  PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
913  EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
914  return EvalStatus.Diag->back().second;
915  }
916 
917  /// Add notes containing a call stack to the current point of evaluation.
918  void addCallStack(unsigned Limit);
919 
920  private:
921  OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
922  unsigned ExtraNotes, bool IsCCEDiag) {
923 
924  if (EvalStatus.Diag) {
925  // If we have a prior diagnostic, it will be noting that the expression
926  // isn't a constant expression. This diagnostic is more important,
927  // unless we require this evaluation to produce a constant expression.
928  //
929  // FIXME: We might want to show both diagnostics to the user in
930  // EM_ConstantFold mode.
931  if (!EvalStatus.Diag->empty()) {
932  switch (EvalMode) {
933  case EM_ConstantFold:
934  case EM_IgnoreSideEffects:
935  case EM_EvaluateForOverflow:
936  if (!HasFoldFailureDiagnostic)
937  break;
938  // We've already failed to fold something. Keep that diagnostic.
939  LLVM_FALLTHROUGH;
940  case EM_ConstantExpression:
941  case EM_PotentialConstantExpression:
942  case EM_ConstantExpressionUnevaluated:
943  case EM_PotentialConstantExpressionUnevaluated:
944  HasActiveDiagnostic = false;
945  return OptionalDiagnostic();
946  }
947  }
948 
949  unsigned CallStackNotes = CallStackDepth - 1;
950  unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
951  if (Limit)
952  CallStackNotes = std::min(CallStackNotes, Limit + 1);
953  if (checkingPotentialConstantExpression())
954  CallStackNotes = 0;
955 
956  HasActiveDiagnostic = true;
957  HasFoldFailureDiagnostic = !IsCCEDiag;
958  EvalStatus.Diag->clear();
959  EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
960  addDiag(Loc, DiagId);
961  if (!checkingPotentialConstantExpression())
962  addCallStack(Limit);
963  return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
964  }
965  HasActiveDiagnostic = false;
966  return OptionalDiagnostic();
967  }
968  public:
969  // Diagnose that the evaluation could not be folded (FF => FoldFailure)
970  OptionalDiagnostic
971  FFDiag(SourceLocation Loc,
972  diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
973  unsigned ExtraNotes = 0) {
974  return Diag(Loc, DiagId, ExtraNotes, false);
975  }
976 
977  OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
978  = diag::note_invalid_subexpr_in_const_expr,
979  unsigned ExtraNotes = 0) {
980  if (EvalStatus.Diag)
981  return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
982  HasActiveDiagnostic = false;
983  return OptionalDiagnostic();
984  }
985 
986  /// Diagnose that the evaluation does not produce a C++11 core constant
987  /// expression.
988  ///
989  /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
990  /// EM_PotentialConstantExpression mode and we produce one of these.
991  OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
992  = diag::note_invalid_subexpr_in_const_expr,
993  unsigned ExtraNotes = 0) {
994  // Don't override a previous diagnostic. Don't bother collecting
995  // diagnostics if we're evaluating for overflow.
996  if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
997  HasActiveDiagnostic = false;
998  return OptionalDiagnostic();
999  }
1000  return Diag(Loc, DiagId, ExtraNotes, true);
1001  }
1002  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1003  = diag::note_invalid_subexpr_in_const_expr,
1004  unsigned ExtraNotes = 0) {
1005  return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1006  }
1007  /// Add a note to a prior diagnostic.
1008  OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1009  if (!HasActiveDiagnostic)
1010  return OptionalDiagnostic();
1011  return OptionalDiagnostic(&addDiag(Loc, DiagId));
1012  }
1013 
1014  /// Add a stack of notes to a prior diagnostic.
1015  void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1016  if (HasActiveDiagnostic) {
1017  EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1018  Diags.begin(), Diags.end());
1019  }
1020  }
1021 
1022  /// Should we continue evaluation after encountering a side-effect that we
1023  /// couldn't model?
1024  bool keepEvaluatingAfterSideEffect() {
1025  switch (EvalMode) {
1026  case EM_PotentialConstantExpression:
1027  case EM_PotentialConstantExpressionUnevaluated:
1028  case EM_EvaluateForOverflow:
1029  case EM_IgnoreSideEffects:
1030  return true;
1031 
1032  case EM_ConstantExpression:
1033  case EM_ConstantExpressionUnevaluated:
1034  case EM_ConstantFold:
1035  return false;
1036  }
1037  llvm_unreachable("Missed EvalMode case");
1038  }
1039 
1040  /// Note that we have had a side-effect, and determine whether we should
1041  /// keep evaluating.
1042  bool noteSideEffect() {
1043  EvalStatus.HasSideEffects = true;
1044  return keepEvaluatingAfterSideEffect();
1045  }
1046 
1047  /// Should we continue evaluation after encountering undefined behavior?
1048  bool keepEvaluatingAfterUndefinedBehavior() {
1049  switch (EvalMode) {
1050  case EM_EvaluateForOverflow:
1051  case EM_IgnoreSideEffects:
1052  case EM_ConstantFold:
1053  return true;
1054 
1055  case EM_PotentialConstantExpression:
1056  case EM_PotentialConstantExpressionUnevaluated:
1057  case EM_ConstantExpression:
1058  case EM_ConstantExpressionUnevaluated:
1059  return false;
1060  }
1061  llvm_unreachable("Missed EvalMode case");
1062  }
1063 
1064  /// Note that we hit something that was technically undefined behavior, but
1065  /// that we can evaluate past it (such as signed overflow or floating-point
1066  /// division by zero.)
1067  bool noteUndefinedBehavior() {
1068  EvalStatus.HasUndefinedBehavior = true;
1069  return keepEvaluatingAfterUndefinedBehavior();
1070  }
1071 
1072  /// Should we continue evaluation as much as possible after encountering a
1073  /// construct which can't be reduced to a value?
1074  bool keepEvaluatingAfterFailure() {
1075  if (!StepsLeft)
1076  return false;
1077 
1078  switch (EvalMode) {
1079  case EM_PotentialConstantExpression:
1080  case EM_PotentialConstantExpressionUnevaluated:
1081  case EM_EvaluateForOverflow:
1082  return true;
1083 
1084  case EM_ConstantExpression:
1085  case EM_ConstantExpressionUnevaluated:
1086  case EM_ConstantFold:
1087  case EM_IgnoreSideEffects:
1088  return false;
1089  }
1090  llvm_unreachable("Missed EvalMode case");
1091  }
1092 
1093  /// Notes that we failed to evaluate an expression that other expressions
1094  /// directly depend on, and determine if we should keep evaluating. This
1095  /// should only be called if we actually intend to keep evaluating.
1096  ///
1097  /// Call noteSideEffect() instead if we may be able to ignore the value that
1098  /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1099  ///
1100  /// (Foo(), 1) // use noteSideEffect
1101  /// (Foo() || true) // use noteSideEffect
1102  /// Foo() + 1 // use noteFailure
1103  LLVM_NODISCARD bool noteFailure() {
1104  // Failure when evaluating some expression often means there is some
1105  // subexpression whose evaluation was skipped. Therefore, (because we
1106  // don't track whether we skipped an expression when unwinding after an
1107  // evaluation failure) every evaluation failure that bubbles up from a
1108  // subexpression implies that a side-effect has potentially happened. We
1109  // skip setting the HasSideEffects flag to true until we decide to
1110  // continue evaluating after that point, which happens here.
1111  bool KeepGoing = keepEvaluatingAfterFailure();
1112  EvalStatus.HasSideEffects |= KeepGoing;
1113  return KeepGoing;
1114  }
1115 
1116  class ArrayInitLoopIndex {
1117  EvalInfo &Info;
1118  uint64_t OuterIndex;
1119 
1120  public:
1121  ArrayInitLoopIndex(EvalInfo &Info)
1122  : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1123  Info.ArrayInitIndex = 0;
1124  }
1125  ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1126 
1127  operator uint64_t&() { return Info.ArrayInitIndex; }
1128  };
1129  };
1130 
1131  /// Object used to treat all foldable expressions as constant expressions.
1132  struct FoldConstant {
1133  EvalInfo &Info;
1134  bool Enabled;
1135  bool HadNoPriorDiags;
1136  EvalInfo::EvaluationMode OldMode;
1137 
1138  explicit FoldConstant(EvalInfo &Info, bool Enabled)
1139  : Info(Info),
1140  Enabled(Enabled),
1141  HadNoPriorDiags(Info.EvalStatus.Diag &&
1142  Info.EvalStatus.Diag->empty() &&
1143  !Info.EvalStatus.HasSideEffects),
1144  OldMode(Info.EvalMode) {
1145  if (Enabled &&
1146  (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1147  Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1148  Info.EvalMode = EvalInfo::EM_ConstantFold;
1149  }
1150  void keepDiagnostics() { Enabled = false; }
1151  ~FoldConstant() {
1152  if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1153  !Info.EvalStatus.HasSideEffects)
1154  Info.EvalStatus.Diag->clear();
1155  Info.EvalMode = OldMode;
1156  }
1157  };
1158 
1159  /// RAII object used to set the current evaluation mode to ignore
1160  /// side-effects.
1161  struct IgnoreSideEffectsRAII {
1162  EvalInfo &Info;
1163  EvalInfo::EvaluationMode OldMode;
1164  explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1165  : Info(Info), OldMode(Info.EvalMode) {
1166  if (!Info.checkingPotentialConstantExpression())
1167  Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1168  }
1169 
1170  ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1171  };
1172 
1173  /// RAII object used to optionally suppress diagnostics and side-effects from
1174  /// a speculative evaluation.
1175  class SpeculativeEvaluationRAII {
1176  EvalInfo *Info = nullptr;
1177  Expr::EvalStatus OldStatus;
1178  unsigned OldSpeculativeEvaluationDepth;
1179 
1180  void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1181  Info = Other.Info;
1182  OldStatus = Other.OldStatus;
1183  OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1184  Other.Info = nullptr;
1185  }
1186 
1187  void maybeRestoreState() {
1188  if (!Info)
1189  return;
1190 
1191  Info->EvalStatus = OldStatus;
1192  Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1193  }
1194 
1195  public:
1196  SpeculativeEvaluationRAII() = default;
1197 
1198  SpeculativeEvaluationRAII(
1199  EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1200  : Info(&Info), OldStatus(Info.EvalStatus),
1201  OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1202  Info.EvalStatus.Diag = NewDiag;
1203  Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1204  }
1205 
1206  SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1207  SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1208  moveFromAndCancel(std::move(Other));
1209  }
1210 
1211  SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1212  maybeRestoreState();
1213  moveFromAndCancel(std::move(Other));
1214  return *this;
1215  }
1216 
1217  ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1218  };
1219 
1220  /// RAII object wrapping a full-expression or block scope, and handling
1221  /// the ending of the lifetime of temporaries created within it.
1222  template<bool IsFullExpression>
1223  class ScopeRAII {
1224  EvalInfo &Info;
1225  unsigned OldStackSize;
1226  public:
1227  ScopeRAII(EvalInfo &Info)
1228  : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1229  // Push a new temporary version. This is needed to distinguish between
1230  // temporaries created in different iterations of a loop.
1231  Info.CurrentCall->pushTempVersion();
1232  }
1233  ~ScopeRAII() {
1234  // Body moved to a static method to encourage the compiler to inline away
1235  // instances of this class.
1236  cleanup(Info, OldStackSize);
1237  Info.CurrentCall->popTempVersion();
1238  }
1239  private:
1240  static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1241  unsigned NewEnd = OldStackSize;
1242  for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1243  I != N; ++I) {
1244  if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1245  // Full-expression cleanup of a lifetime-extended temporary: nothing
1246  // to do, just move this cleanup to the right place in the stack.
1247  std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1248  ++NewEnd;
1249  } else {
1250  // End the lifetime of the object.
1251  Info.CleanupStack[I].endLifetime();
1252  }
1253  }
1254  Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1255  Info.CleanupStack.end());
1256  }
1257  };
1258  typedef ScopeRAII<false> BlockScopeRAII;
1259  typedef ScopeRAII<true> FullExpressionRAII;
1260 }
1261 
1262 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1263  CheckSubobjectKind CSK) {
1264  if (Invalid)
1265  return false;
1266  if (isOnePastTheEnd()) {
1267  Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1268  << CSK;
1269  setInvalid();
1270  return false;
1271  }
1272  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1273  // must actually be at least one array element; even a VLA cannot have a
1274  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1275  return true;
1276 }
1277 
1278 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1279  const Expr *E) {
1280  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1281  // Do not set the designator as invalid: we can represent this situation,
1282  // and correct handling of __builtin_object_size requires us to do so.
1283 }
1284 
1285 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1286  const Expr *E,
1287  const APSInt &N) {
1288  // If we're complaining, we must be able to statically determine the size of
1289  // the most derived array.
1290  if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1291  Info.CCEDiag(E, diag::note_constexpr_array_index)
1292  << N << /*array*/ 0
1293  << static_cast<unsigned>(getMostDerivedArraySize());
1294  else
1295  Info.CCEDiag(E, diag::note_constexpr_array_index)
1296  << N << /*non-array*/ 1;
1297  setInvalid();
1298 }
1299 
1300 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1301  const FunctionDecl *Callee, const LValue *This,
1302  APValue *Arguments)
1303  : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1304  Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1305  Info.CurrentCall = this;
1306  ++Info.CallStackDepth;
1307 }
1308 
1309 CallStackFrame::~CallStackFrame() {
1310  assert(Info.CurrentCall == this && "calls retired out of order");
1311  --Info.CallStackDepth;
1312  Info.CurrentCall = Caller;
1313 }
1314 
1315 APValue &CallStackFrame::createTemporary(const void *Key,
1316  bool IsLifetimeExtended) {
1317  unsigned Version = Info.CurrentCall->getTempVersion();
1318  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1319  assert(Result.isAbsent() && "temporary created multiple times");
1320  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1321  return Result;
1322 }
1323 
1324 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1325 
1326 void EvalInfo::addCallStack(unsigned Limit) {
1327  // Determine which calls to skip, if any.
1328  unsigned ActiveCalls = CallStackDepth - 1;
1329  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1330  if (Limit && Limit < ActiveCalls) {
1331  SkipStart = Limit / 2 + Limit % 2;
1332  SkipEnd = ActiveCalls - Limit / 2;
1333  }
1334 
1335  // Walk the call stack and add the diagnostics.
1336  unsigned CallIdx = 0;
1337  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1338  Frame = Frame->Caller, ++CallIdx) {
1339  // Skip this call?
1340  if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1341  if (CallIdx == SkipStart) {
1342  // Note that we're skipping calls.
1343  addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1344  << unsigned(ActiveCalls - Limit);
1345  }
1346  continue;
1347  }
1348 
1349  // Use a different note for an inheriting constructor, because from the
1350  // user's perspective it's not really a function at all.
1351  if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1352  if (CD->isInheritingConstructor()) {
1353  addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1354  << CD->getParent();
1355  continue;
1356  }
1357  }
1358 
1359  SmallVector<char, 128> Buffer;
1360  llvm::raw_svector_ostream Out(Buffer);
1361  describeCall(Frame, Out);
1362  addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1363  }
1364 }
1365 
1366 /// Kinds of access we can perform on an object, for diagnostics. Note that
1367 /// we consider a member function call to be a kind of access, even though
1368 /// it is not formally an access of the object, because it has (largely) the
1369 /// same set of semantic restrictions.
1378 };
1379 
1380 static bool isModification(AccessKinds AK) {
1381  switch (AK) {
1382  case AK_Read:
1383  case AK_MemberCall:
1384  case AK_DynamicCast:
1385  case AK_TypeId:
1386  return false;
1387  case AK_Assign:
1388  case AK_Increment:
1389  case AK_Decrement:
1390  return true;
1391  }
1392  llvm_unreachable("unknown access kind");
1393 }
1394 
1395 /// Is this an access per the C++ definition?
1396 static bool isFormalAccess(AccessKinds AK) {
1397  return AK == AK_Read || isModification(AK);
1398 }
1399 
1400 namespace {
1401  struct ComplexValue {
1402  private:
1403  bool IsInt;
1404 
1405  public:
1406  APSInt IntReal, IntImag;
1407  APFloat FloatReal, FloatImag;
1408 
1409  ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1410 
1411  void makeComplexFloat() { IsInt = false; }
1412  bool isComplexFloat() const { return !IsInt; }
1413  APFloat &getComplexFloatReal() { return FloatReal; }
1414  APFloat &getComplexFloatImag() { return FloatImag; }
1415 
1416  void makeComplexInt() { IsInt = true; }
1417  bool isComplexInt() const { return IsInt; }
1418  APSInt &getComplexIntReal() { return IntReal; }
1419  APSInt &getComplexIntImag() { return IntImag; }
1420 
1421  void moveInto(APValue &v) const {
1422  if (isComplexFloat())
1423  v = APValue(FloatReal, FloatImag);
1424  else
1425  v = APValue(IntReal, IntImag);
1426  }
1427  void setFrom(const APValue &v) {
1428  assert(v.isComplexFloat() || v.isComplexInt());
1429  if (v.isComplexFloat()) {
1430  makeComplexFloat();
1431  FloatReal = v.getComplexFloatReal();
1432  FloatImag = v.getComplexFloatImag();
1433  } else {
1434  makeComplexInt();
1435  IntReal = v.getComplexIntReal();
1436  IntImag = v.getComplexIntImag();
1437  }
1438  }
1439  };
1440 
1441  struct LValue {
1442  APValue::LValueBase Base;
1443  CharUnits Offset;
1444  SubobjectDesignator Designator;
1445  bool IsNullPtr : 1;
1446  bool InvalidBase : 1;
1447 
1448  const APValue::LValueBase getLValueBase() const { return Base; }
1449  CharUnits &getLValueOffset() { return Offset; }
1450  const CharUnits &getLValueOffset() const { return Offset; }
1451  SubobjectDesignator &getLValueDesignator() { return Designator; }
1452  const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1453  bool isNullPointer() const { return IsNullPtr;}
1454 
1455  unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456  unsigned getLValueVersion() const { return Base.getVersion(); }
1457 
1458  void moveInto(APValue &V) const {
1459  if (Designator.Invalid)
1460  V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1461  else {
1462  assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1463  V = APValue(Base, Offset, Designator.Entries,
1464  Designator.IsOnePastTheEnd, IsNullPtr);
1465  }
1466  }
1467  void setFrom(ASTContext &Ctx, const APValue &V) {
1468  assert(V.isLValue() && "Setting LValue from a non-LValue?");
1469  Base = V.getLValueBase();
1470  Offset = V.getLValueOffset();
1471  InvalidBase = false;
1472  Designator = SubobjectDesignator(Ctx, V);
1473  IsNullPtr = V.isNullPointer();
1474  }
1475 
1476  void set(APValue::LValueBase B, bool BInvalid = false) {
1477 #ifndef NDEBUG
1478  // We only allow a few types of invalid bases. Enforce that here.
1479  if (BInvalid) {
1480  const auto *E = B.get<const Expr *>();
1481  assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1482  "Unexpected type of invalid base");
1483  }
1484 #endif
1485 
1486  Base = B;
1487  Offset = CharUnits::fromQuantity(0);
1488  InvalidBase = BInvalid;
1489  Designator = SubobjectDesignator(getType(B));
1490  IsNullPtr = false;
1491  }
1492 
1493  void setNull(QualType PointerTy, uint64_t TargetVal) {
1494  Base = (Expr *)nullptr;
1495  Offset = CharUnits::fromQuantity(TargetVal);
1496  InvalidBase = false;
1497  Designator = SubobjectDesignator(PointerTy->getPointeeType());
1498  IsNullPtr = true;
1499  }
1500 
1501  void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1502  set(B, true);
1503  }
1504 
1505  private:
1506  // Check that this LValue is not based on a null pointer. If it is, produce
1507  // a diagnostic and mark the designator as invalid.
1508  template <typename GenDiagType>
1509  bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1510  if (Designator.Invalid)
1511  return false;
1512  if (IsNullPtr) {
1513  GenDiag();
1514  Designator.setInvalid();
1515  return false;
1516  }
1517  return true;
1518  }
1519 
1520  public:
1521  bool checkNullPointer(EvalInfo &Info, const Expr *E,
1522  CheckSubobjectKind CSK) {
1523  return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1524  Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1525  });
1526  }
1527 
1528  bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1529  AccessKinds AK) {
1530  return checkNullPointerDiagnosingWith([&Info, E, AK] {
1531  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1532  });
1533  }
1534 
1535  // Check this LValue refers to an object. If not, set the designator to be
1536  // invalid and emit a diagnostic.
1537  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1538  return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1539  Designator.checkSubobject(Info, E, CSK);
1540  }
1541 
1542  void addDecl(EvalInfo &Info, const Expr *E,
1543  const Decl *D, bool Virtual = false) {
1544  if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1545  Designator.addDeclUnchecked(D, Virtual);
1546  }
1547  void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1548  if (!Designator.Entries.empty()) {
1549  Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1550  Designator.setInvalid();
1551  return;
1552  }
1553  if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1554  assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1555  Designator.FirstEntryIsAnUnsizedArray = true;
1556  Designator.addUnsizedArrayUnchecked(ElemTy);
1557  }
1558  }
1559  void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1560  if (checkSubobject(Info, E, CSK_ArrayToPointer))
1561  Designator.addArrayUnchecked(CAT);
1562  }
1563  void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1564  if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1565  Designator.addComplexUnchecked(EltTy, Imag);
1566  }
1567  void clearIsNullPointer() {
1568  IsNullPtr = false;
1569  }
1570  void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1571  const APSInt &Index, CharUnits ElementSize) {
1572  // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1573  // but we're not required to diagnose it and it's valid in C++.)
1574  if (!Index)
1575  return;
1576 
1577  // Compute the new offset in the appropriate width, wrapping at 64 bits.
1578  // FIXME: When compiling for a 32-bit target, we should use 32-bit
1579  // offsets.
1580  uint64_t Offset64 = Offset.getQuantity();
1581  uint64_t ElemSize64 = ElementSize.getQuantity();
1582  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1583  Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1584 
1585  if (checkNullPointer(Info, E, CSK_ArrayIndex))
1586  Designator.adjustIndex(Info, E, Index);
1587  clearIsNullPointer();
1588  }
1589  void adjustOffset(CharUnits N) {
1590  Offset += N;
1591  if (N.getQuantity())
1592  clearIsNullPointer();
1593  }
1594  };
1595 
1596  struct MemberPtr {
1597  MemberPtr() {}
1598  explicit MemberPtr(const ValueDecl *Decl) :
1599  DeclAndIsDerivedMember(Decl, false), Path() {}
1600 
1601  /// The member or (direct or indirect) field referred to by this member
1602  /// pointer, or 0 if this is a null member pointer.
1603  const ValueDecl *getDecl() const {
1604  return DeclAndIsDerivedMember.getPointer();
1605  }
1606  /// Is this actually a member of some type derived from the relevant class?
1607  bool isDerivedMember() const {
1608  return DeclAndIsDerivedMember.getInt();
1609  }
1610  /// Get the class which the declaration actually lives in.
1611  const CXXRecordDecl *getContainingRecord() const {
1612  return cast<CXXRecordDecl>(
1613  DeclAndIsDerivedMember.getPointer()->getDeclContext());
1614  }
1615 
1616  void moveInto(APValue &V) const {
1617  V = APValue(getDecl(), isDerivedMember(), Path);
1618  }
1619  void setFrom(const APValue &V) {
1620  assert(V.isMemberPointer());
1621  DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1622  DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1623  Path.clear();
1625  Path.insert(Path.end(), P.begin(), P.end());
1626  }
1627 
1628  /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1629  /// whether the member is a member of some class derived from the class type
1630  /// of the member pointer.
1631  llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1632  /// Path - The path of base/derived classes from the member declaration's
1633  /// class (exclusive) to the class type of the member pointer (inclusive).
1635 
1636  /// Perform a cast towards the class of the Decl (either up or down the
1637  /// hierarchy).
1638  bool castBack(const CXXRecordDecl *Class) {
1639  assert(!Path.empty());
1640  const CXXRecordDecl *Expected;
1641  if (Path.size() >= 2)
1642  Expected = Path[Path.size() - 2];
1643  else
1644  Expected = getContainingRecord();
1645  if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1646  // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1647  // if B does not contain the original member and is not a base or
1648  // derived class of the class containing the original member, the result
1649  // of the cast is undefined.
1650  // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1651  // (D::*). We consider that to be a language defect.
1652  return false;
1653  }
1654  Path.pop_back();
1655  return true;
1656  }
1657  /// Perform a base-to-derived member pointer cast.
1658  bool castToDerived(const CXXRecordDecl *Derived) {
1659  if (!getDecl())
1660  return true;
1661  if (!isDerivedMember()) {
1662  Path.push_back(Derived);
1663  return true;
1664  }
1665  if (!castBack(Derived))
1666  return false;
1667  if (Path.empty())
1668  DeclAndIsDerivedMember.setInt(false);
1669  return true;
1670  }
1671  /// Perform a derived-to-base member pointer cast.
1672  bool castToBase(const CXXRecordDecl *Base) {
1673  if (!getDecl())
1674  return true;
1675  if (Path.empty())
1676  DeclAndIsDerivedMember.setInt(true);
1677  if (isDerivedMember()) {
1678  Path.push_back(Base);
1679  return true;
1680  }
1681  return castBack(Base);
1682  }
1683  };
1684 
1685  /// Compare two member pointers, which are assumed to be of the same type.
1686  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1687  if (!LHS.getDecl() || !RHS.getDecl())
1688  return !LHS.getDecl() && !RHS.getDecl();
1689  if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1690  return false;
1691  return LHS.Path == RHS.Path;
1692  }
1693 }
1694 
1695 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1696 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1697  const LValue &This, const Expr *E,
1698  bool AllowNonLiteralTypes = false);
1699 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1700  bool InvalidBaseOK = false);
1701 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1702  bool InvalidBaseOK = false);
1703 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1704  EvalInfo &Info);
1705 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1706 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1707 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1708  EvalInfo &Info);
1709 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1710 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1711 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1712  EvalInfo &Info);
1713 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1714 
1715 /// Evaluate an integer or fixed point expression into an APResult.
1716 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1717  EvalInfo &Info);
1718 
1719 /// Evaluate only a fixed point expression into an APResult.
1720 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1721  EvalInfo &Info);
1722 
1723 //===----------------------------------------------------------------------===//
1724 // Misc utilities
1725 //===----------------------------------------------------------------------===//
1726 
1727 /// A helper function to create a temporary and set an LValue.
1728 template <class KeyTy>
1729 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1730  LValue &LV, CallStackFrame &Frame) {
1731  LV.set({Key, Frame.Info.CurrentCall->Index,
1732  Frame.Info.CurrentCall->getTempVersion()});
1733  return Frame.createTemporary(Key, IsLifetimeExtended);
1734 }
1735 
1736 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1737 /// preserving its value (by extending by up to one bit as needed).
1738 static void negateAsSigned(APSInt &Int) {
1739  if (Int.isUnsigned() || Int.isMinSignedValue()) {
1740  Int = Int.extend(Int.getBitWidth() + 1);
1741  Int.setIsSigned(true);
1742  }
1743  Int = -Int;
1744 }
1745 
1746 /// Produce a string describing the given constexpr call.
1747 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1748  unsigned ArgIndex = 0;
1749  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1750  !isa<CXXConstructorDecl>(Frame->Callee) &&
1751  cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1752 
1753  if (!IsMemberCall)
1754  Out << *Frame->Callee << '(';
1755 
1756  if (Frame->This && IsMemberCall) {
1757  APValue Val;
1758  Frame->This->moveInto(Val);
1759  Val.printPretty(Out, Frame->Info.Ctx,
1760  Frame->This->Designator.MostDerivedType);
1761  // FIXME: Add parens around Val if needed.
1762  Out << "->" << *Frame->Callee << '(';
1763  IsMemberCall = false;
1764  }
1765 
1766  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1767  E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1768  if (ArgIndex > (unsigned)IsMemberCall)
1769  Out << ", ";
1770 
1771  const ParmVarDecl *Param = *I;
1772  const APValue &Arg = Frame->Arguments[ArgIndex];
1773  Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1774 
1775  if (ArgIndex == 0 && IsMemberCall)
1776  Out << "->" << *Frame->Callee << '(';
1777  }
1778 
1779  Out << ')';
1780 }
1781 
1782 /// Evaluate an expression to see if it had side-effects, and discard its
1783 /// result.
1784 /// \return \c true if the caller should keep evaluating.
1785 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1786  APValue Scratch;
1787  if (!Evaluate(Scratch, Info, E))
1788  // We don't need the value, but we might have skipped a side effect here.
1789  return Info.noteSideEffect();
1790  return true;
1791 }
1792 
1793 /// Should this call expression be treated as a string literal?
1794 static bool IsStringLiteralCall(const CallExpr *E) {
1795  unsigned Builtin = E->getBuiltinCallee();
1796  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1797  Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1798 }
1799 
1801  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1802  // constant expression of pointer type that evaluates to...
1803 
1804  // ... a null pointer value, or a prvalue core constant expression of type
1805  // std::nullptr_t.
1806  if (!B) return true;
1807 
1808  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1809  // ... the address of an object with static storage duration,
1810  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1811  return VD->hasGlobalStorage();
1812  // ... the address of a function,
1813  return isa<FunctionDecl>(D);
1814  }
1815 
1816  if (B.is<TypeInfoLValue>())
1817  return true;
1818 
1819  const Expr *E = B.get<const Expr*>();
1820  switch (E->getStmtClass()) {
1821  default:
1822  return false;
1823  case Expr::CompoundLiteralExprClass: {
1824  const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1825  return CLE->isFileScope() && CLE->isLValue();
1826  }
1827  case Expr::MaterializeTemporaryExprClass:
1828  // A materialized temporary might have been lifetime-extended to static
1829  // storage duration.
1830  return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1831  // A string literal has static storage duration.
1832  case Expr::StringLiteralClass:
1833  case Expr::PredefinedExprClass:
1834  case Expr::ObjCStringLiteralClass:
1835  case Expr::ObjCEncodeExprClass:
1836  case Expr::CXXUuidofExprClass:
1837  return true;
1838  case Expr::ObjCBoxedExprClass:
1839  return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1840  case Expr::CallExprClass:
1841  return IsStringLiteralCall(cast<CallExpr>(E));
1842  // For GCC compatibility, &&label has static storage duration.
1843  case Expr::AddrLabelExprClass:
1844  return true;
1845  // A Block literal expression may be used as the initialization value for
1846  // Block variables at global or local static scope.
1847  case Expr::BlockExprClass:
1848  return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1849  case Expr::ImplicitValueInitExprClass:
1850  // FIXME:
1851  // We can never form an lvalue with an implicit value initialization as its
1852  // base through expression evaluation, so these only appear in one case: the
1853  // implicit variable declaration we invent when checking whether a constexpr
1854  // constructor can produce a constant expression. We must assume that such
1855  // an expression might be a global lvalue.
1856  return true;
1857  }
1858 }
1859 
1860 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1861  return LVal.Base.dyn_cast<const ValueDecl*>();
1862 }
1863 
1864 static bool IsLiteralLValue(const LValue &Value) {
1865  if (Value.getLValueCallIndex())
1866  return false;
1867  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1868  return E && !isa<MaterializeTemporaryExpr>(E);
1869 }
1870 
1871 static bool IsWeakLValue(const LValue &Value) {
1872  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1873  return Decl && Decl->isWeak();
1874 }
1875 
1876 static bool isZeroSized(const LValue &Value) {
1877  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1878  if (Decl && isa<VarDecl>(Decl)) {
1879  QualType Ty = Decl->getType();
1880  if (Ty->isArrayType())
1881  return Ty->isIncompleteType() ||
1882  Decl->getASTContext().getTypeSize(Ty) == 0;
1883  }
1884  return false;
1885 }
1886 
1887 static bool HasSameBase(const LValue &A, const LValue &B) {
1888  if (!A.getLValueBase())
1889  return !B.getLValueBase();
1890  if (!B.getLValueBase())
1891  return false;
1892 
1893  if (A.getLValueBase().getOpaqueValue() !=
1894  B.getLValueBase().getOpaqueValue()) {
1895  const Decl *ADecl = GetLValueBaseDecl(A);
1896  if (!ADecl)
1897  return false;
1898  const Decl *BDecl = GetLValueBaseDecl(B);
1899  if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1900  return false;
1901  }
1902 
1903  return IsGlobalLValue(A.getLValueBase()) ||
1904  (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1905  A.getLValueVersion() == B.getLValueVersion());
1906 }
1907 
1908 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1909  assert(Base && "no location for a null lvalue");
1910  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1911  if (VD)
1912  Info.Note(VD->getLocation(), diag::note_declared_at);
1913  else if (const Expr *E = Base.dyn_cast<const Expr*>())
1914  Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1915  // We have no information to show for a typeid(T) object.
1916 }
1917 
1918 /// Check that this reference or pointer core constant expression is a valid
1919 /// value for an address or reference constant expression. Return true if we
1920 /// can fold this expression, whether or not it's a constant expression.
1921 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1922  QualType Type, const LValue &LVal,
1923  Expr::ConstExprUsage Usage) {
1924  bool IsReferenceType = Type->isReferenceType();
1925 
1926  APValue::LValueBase Base = LVal.getLValueBase();
1927  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1928 
1929  // Check that the object is a global. Note that the fake 'this' object we
1930  // manufacture when checking potential constant expressions is conservatively
1931  // assumed to be global here.
1932  if (!IsGlobalLValue(Base)) {
1933  if (Info.getLangOpts().CPlusPlus11) {
1934  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1935  Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1936  << IsReferenceType << !Designator.Entries.empty()
1937  << !!VD << VD;
1938  NoteLValueLocation(Info, Base);
1939  } else {
1940  Info.FFDiag(Loc);
1941  }
1942  // Don't allow references to temporaries to escape.
1943  return false;
1944  }
1945  assert((Info.checkingPotentialConstantExpression() ||
1946  LVal.getLValueCallIndex() == 0) &&
1947  "have call index for global lvalue");
1948 
1949  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1950  if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1951  // Check if this is a thread-local variable.
1952  if (Var->getTLSKind())
1953  return false;
1954 
1955  // A dllimport variable never acts like a constant.
1956  if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1957  return false;
1958  }
1959  if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1960  // __declspec(dllimport) must be handled very carefully:
1961  // We must never initialize an expression with the thunk in C++.
1962  // Doing otherwise would allow the same id-expression to yield
1963  // different addresses for the same function in different translation
1964  // units. However, this means that we must dynamically initialize the
1965  // expression with the contents of the import address table at runtime.
1966  //
1967  // The C language has no notion of ODR; furthermore, it has no notion of
1968  // dynamic initialization. This means that we are permitted to
1969  // perform initialization with the address of the thunk.
1970  if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1971  FD->hasAttr<DLLImportAttr>())
1972  return false;
1973  }
1974  }
1975 
1976  // Allow address constant expressions to be past-the-end pointers. This is
1977  // an extension: the standard requires them to point to an object.
1978  if (!IsReferenceType)
1979  return true;
1980 
1981  // A reference constant expression must refer to an object.
1982  if (!Base) {
1983  // FIXME: diagnostic
1984  Info.CCEDiag(Loc);
1985  return true;
1986  }
1987 
1988  // Does this refer one past the end of some object?
1989  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1990  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1991  Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1992  << !Designator.Entries.empty() << !!VD << VD;
1993  NoteLValueLocation(Info, Base);
1994  }
1995 
1996  return true;
1997 }
1998 
1999 /// Member pointers are constant expressions unless they point to a
2000 /// non-virtual dllimport member function.
2001 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2002  SourceLocation Loc,
2003  QualType Type,
2004  const APValue &Value,
2005  Expr::ConstExprUsage Usage) {
2006  const ValueDecl *Member = Value.getMemberPointerDecl();
2007  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2008  if (!FD)
2009  return true;
2010  return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2011  !FD->hasAttr<DLLImportAttr>();
2012 }
2013 
2014 /// Check that this core constant expression is of literal type, and if not,
2015 /// produce an appropriate diagnostic.
2016 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2017  const LValue *This = nullptr) {
2018  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2019  return true;
2020 
2021  // C++1y: A constant initializer for an object o [...] may also invoke
2022  // constexpr constructors for o and its subobjects even if those objects
2023  // are of non-literal class types.
2024  //
2025  // C++11 missed this detail for aggregates, so classes like this:
2026  // struct foo_t { union { int i; volatile int j; } u; };
2027  // are not (obviously) initializable like so:
2028  // __attribute__((__require_constant_initialization__))
2029  // static const foo_t x = {{0}};
2030  // because "i" is a subobject with non-literal initialization (due to the
2031  // volatile member of the union). See:
2032  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2033  // Therefore, we use the C++1y behavior.
2034  if (This && Info.EvaluatingDecl == This->getLValueBase())
2035  return true;
2036 
2037  // Prvalue constant expressions must be of literal types.
2038  if (Info.getLangOpts().CPlusPlus11)
2039  Info.FFDiag(E, diag::note_constexpr_nonliteral)
2040  << E->getType();
2041  else
2042  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2043  return false;
2044 }
2045 
2046 /// Check that this core constant expression value is a valid value for a
2047 /// constant expression. If not, report an appropriate diagnostic. Does not
2048 /// check that the expression is of literal type.
2049 static bool
2050 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2051  const APValue &Value,
2053  SourceLocation SubobjectLoc = SourceLocation()) {
2054  if (!Value.hasValue()) {
2055  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2056  << true << Type;
2057  if (SubobjectLoc.isValid())
2058  Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2059  return false;
2060  }
2061 
2062  // We allow _Atomic(T) to be initialized from anything that T can be
2063  // initialized from.
2064  if (const AtomicType *AT = Type->getAs<AtomicType>())
2065  Type = AT->getValueType();
2066 
2067  // Core issue 1454: For a literal constant expression of array or class type,
2068  // each subobject of its value shall have been initialized by a constant
2069  // expression.
2070  if (Value.isArray()) {
2071  QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2072  for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2073  if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2074  Value.getArrayInitializedElt(I), Usage,
2075  SubobjectLoc))
2076  return false;
2077  }
2078  if (!Value.hasArrayFiller())
2079  return true;
2080  return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2081  Usage, SubobjectLoc);
2082  }
2083  if (Value.isUnion() && Value.getUnionField()) {
2084  return CheckConstantExpression(Info, DiagLoc,
2085  Value.getUnionField()->getType(),
2086  Value.getUnionValue(), Usage,
2087  Value.getUnionField()->getLocation());
2088  }
2089  if (Value.isStruct()) {
2090  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2091  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2092  unsigned BaseIndex = 0;
2093  for (const CXXBaseSpecifier &BS : CD->bases()) {
2094  if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2095  Value.getStructBase(BaseIndex), Usage,
2096  BS.getBeginLoc()))
2097  return false;
2098  ++BaseIndex;
2099  }
2100  }
2101  for (const auto *I : RD->fields()) {
2102  if (I->isUnnamedBitfield())
2103  continue;
2104 
2105  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2106  Value.getStructField(I->getFieldIndex()),
2107  Usage, I->getLocation()))
2108  return false;
2109  }
2110  }
2111 
2112  if (Value.isLValue()) {
2113  LValue LVal;
2114  LVal.setFrom(Info.Ctx, Value);
2115  return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2116  }
2117 
2118  if (Value.isMemberPointer())
2119  return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2120 
2121  // Everything else is fine.
2122  return true;
2123 }
2124 
2125 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2126  // A null base expression indicates a null pointer. These are always
2127  // evaluatable, and they are false unless the offset is zero.
2128  if (!Value.getLValueBase()) {
2129  Result = !Value.getLValueOffset().isZero();
2130  return true;
2131  }
2132 
2133  // We have a non-null base. These are generally known to be true, but if it's
2134  // a weak declaration it can be null at runtime.
2135  Result = true;
2136  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2137  return !Decl || !Decl->isWeak();
2138 }
2139 
2140 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2141  switch (Val.getKind()) {
2142  case APValue::None:
2144  return false;
2145  case APValue::Int:
2146  Result = Val.getInt().getBoolValue();
2147  return true;
2148  case APValue::FixedPoint:
2149  Result = Val.getFixedPoint().getBoolValue();
2150  return true;
2151  case APValue::Float:
2152  Result = !Val.getFloat().isZero();
2153  return true;
2154  case APValue::ComplexInt:
2155  Result = Val.getComplexIntReal().getBoolValue() ||
2156  Val.getComplexIntImag().getBoolValue();
2157  return true;
2158  case APValue::ComplexFloat:
2159  Result = !Val.getComplexFloatReal().isZero() ||
2160  !Val.getComplexFloatImag().isZero();
2161  return true;
2162  case APValue::LValue:
2163  return EvalPointerValueAsBool(Val, Result);
2165  Result = Val.getMemberPointerDecl();
2166  return true;
2167  case APValue::Vector:
2168  case APValue::Array:
2169  case APValue::Struct:
2170  case APValue::Union:
2172  return false;
2173  }
2174 
2175  llvm_unreachable("unknown APValue kind");
2176 }
2177 
2178 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2179  EvalInfo &Info) {
2180  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2181  APValue Val;
2182  if (!Evaluate(Val, Info, E))
2183  return false;
2184  return HandleConversionToBool(Val, Result);
2185 }
2186 
2187 template<typename T>
2188 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2189  const T &SrcValue, QualType DestType) {
2190  Info.CCEDiag(E, diag::note_constexpr_overflow)
2191  << SrcValue << DestType;
2192  return Info.noteUndefinedBehavior();
2193 }
2194 
2195 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2196  QualType SrcType, const APFloat &Value,
2197  QualType DestType, APSInt &Result) {
2198  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2199  // Determine whether we are converting to unsigned or signed.
2200  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2201 
2202  Result = APSInt(DestWidth, !DestSigned);
2203  bool ignored;
2204  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2205  & APFloat::opInvalidOp)
2206  return HandleOverflow(Info, E, Value, DestType);
2207  return true;
2208 }
2209 
2210 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2211  QualType SrcType, QualType DestType,
2212  APFloat &Result) {
2213  APFloat Value = Result;
2214  bool ignored;
2215  Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2216  APFloat::rmNearestTiesToEven, &ignored);
2217  return true;
2218 }
2219 
2220 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2221  QualType DestType, QualType SrcType,
2222  const APSInt &Value) {
2223  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2224  // Figure out if this is a truncate, extend or noop cast.
2225  // If the input is signed, do a sign extend, noop, or truncate.
2226  APSInt Result = Value.extOrTrunc(DestWidth);
2227  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2228  if (DestType->isBooleanType())
2229  Result = Value.getBoolValue();
2230  return Result;
2231 }
2232 
2233 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2234  QualType SrcType, const APSInt &Value,
2235  QualType DestType, APFloat &Result) {
2236  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2237  Result.convertFromAPInt(Value, Value.isSigned(),
2238  APFloat::rmNearestTiesToEven);
2239  return true;
2240 }
2241 
2242 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2243  APValue &Value, const FieldDecl *FD) {
2244  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2245 
2246  if (!Value.isInt()) {
2247  // Trying to store a pointer-cast-to-integer into a bitfield.
2248  // FIXME: In this case, we should provide the diagnostic for casting
2249  // a pointer to an integer.
2250  assert(Value.isLValue() && "integral value neither int nor lvalue?");
2251  Info.FFDiag(E);
2252  return false;
2253  }
2254 
2255  APSInt &Int = Value.getInt();
2256  unsigned OldBitWidth = Int.getBitWidth();
2257  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2258  if (NewBitWidth < OldBitWidth)
2259  Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2260  return true;
2261 }
2262 
2263 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2264  llvm::APInt &Res) {
2265  APValue SVal;
2266  if (!Evaluate(SVal, Info, E))
2267  return false;
2268  if (SVal.isInt()) {
2269  Res = SVal.getInt();
2270  return true;
2271  }
2272  if (SVal.isFloat()) {
2273  Res = SVal.getFloat().bitcastToAPInt();
2274  return true;
2275  }
2276  if (SVal.isVector()) {
2277  QualType VecTy = E->getType();
2278  unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2279  QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2280  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2281  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2282  Res = llvm::APInt::getNullValue(VecSize);
2283  for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2284  APValue &Elt = SVal.getVectorElt(i);
2285  llvm::APInt EltAsInt;
2286  if (Elt.isInt()) {
2287  EltAsInt = Elt.getInt();
2288  } else if (Elt.isFloat()) {
2289  EltAsInt = Elt.getFloat().bitcastToAPInt();
2290  } else {
2291  // Don't try to handle vectors of anything other than int or float
2292  // (not sure if it's possible to hit this case).
2293  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2294  return false;
2295  }
2296  unsigned BaseEltSize = EltAsInt.getBitWidth();
2297  if (BigEndian)
2298  Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2299  else
2300  Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2301  }
2302  return true;
2303  }
2304  // Give up if the input isn't an int, float, or vector. For example, we
2305  // reject "(v4i16)(intptr_t)&a".
2306  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2307  return false;
2308 }
2309 
2310 /// Perform the given integer operation, which is known to need at most BitWidth
2311 /// bits, and check for overflow in the original type (if that type was not an
2312 /// unsigned type).
2313 template<typename Operation>
2314 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2315  const APSInt &LHS, const APSInt &RHS,
2316  unsigned BitWidth, Operation Op,
2317  APSInt &Result) {
2318  if (LHS.isUnsigned()) {
2319  Result = Op(LHS, RHS);
2320  return true;
2321  }
2322 
2323  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2324  Result = Value.trunc(LHS.getBitWidth());
2325  if (Result.extend(BitWidth) != Value) {
2326  if (Info.checkingForOverflow())
2327  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2328  diag::warn_integer_constant_overflow)
2329  << Result.toString(10) << E->getType();
2330  else
2331  return HandleOverflow(Info, E, Value, E->getType());
2332  }
2333  return true;
2334 }
2335 
2336 /// Perform the given binary integer operation.
2337 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2338  BinaryOperatorKind Opcode, APSInt RHS,
2339  APSInt &Result) {
2340  switch (Opcode) {
2341  default:
2342  Info.FFDiag(E);
2343  return false;
2344  case BO_Mul:
2345  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2346  std::multiplies<APSInt>(), Result);
2347  case BO_Add:
2348  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2349  std::plus<APSInt>(), Result);
2350  case BO_Sub:
2351  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2352  std::minus<APSInt>(), Result);
2353  case BO_And: Result = LHS & RHS; return true;
2354  case BO_Xor: Result = LHS ^ RHS; return true;
2355  case BO_Or: Result = LHS | RHS; return true;
2356  case BO_Div:
2357  case BO_Rem:
2358  if (RHS == 0) {
2359  Info.FFDiag(E, diag::note_expr_divide_by_zero);
2360  return false;
2361  }
2362  Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2363  // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2364  // this operation and gives the two's complement result.
2365  if (RHS.isNegative() && RHS.isAllOnesValue() &&
2366  LHS.isSigned() && LHS.isMinSignedValue())
2367  return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2368  E->getType());
2369  return true;
2370  case BO_Shl: {
2371  if (Info.getLangOpts().OpenCL)
2372  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2373  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2374  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2375  RHS.isUnsigned());
2376  else if (RHS.isSigned() && RHS.isNegative()) {
2377  // During constant-folding, a negative shift is an opposite shift. Such
2378  // a shift is not a constant expression.
2379  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2380  RHS = -RHS;
2381  goto shift_right;
2382  }
2383  shift_left:
2384  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2385  // the shifted type.
2386  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2387  if (SA != RHS) {
2388  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2389  << RHS << E->getType() << LHS.getBitWidth();
2390  } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2391  // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2392  // operand, and must not overflow the corresponding unsigned type.
2393  // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2394  // E1 x 2^E2 module 2^N.
2395  if (LHS.isNegative())
2396  Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2397  else if (LHS.countLeadingZeros() < SA)
2398  Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2399  }
2400  Result = LHS << SA;
2401  return true;
2402  }
2403  case BO_Shr: {
2404  if (Info.getLangOpts().OpenCL)
2405  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2406  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2407  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2408  RHS.isUnsigned());
2409  else if (RHS.isSigned() && RHS.isNegative()) {
2410  // During constant-folding, a negative shift is an opposite shift. Such a
2411  // shift is not a constant expression.
2412  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2413  RHS = -RHS;
2414  goto shift_left;
2415  }
2416  shift_right:
2417  // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2418  // shifted type.
2419  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2420  if (SA != RHS)
2421  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2422  << RHS << E->getType() << LHS.getBitWidth();
2423  Result = LHS >> SA;
2424  return true;
2425  }
2426 
2427  case BO_LT: Result = LHS < RHS; return true;
2428  case BO_GT: Result = LHS > RHS; return true;
2429  case BO_LE: Result = LHS <= RHS; return true;
2430  case BO_GE: Result = LHS >= RHS; return true;
2431  case BO_EQ: Result = LHS == RHS; return true;
2432  case BO_NE: Result = LHS != RHS; return true;
2433  case BO_Cmp:
2434  llvm_unreachable("BO_Cmp should be handled elsewhere");
2435  }
2436 }
2437 
2438 /// Perform the given binary floating-point operation, in-place, on LHS.
2439 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2440  APFloat &LHS, BinaryOperatorKind Opcode,
2441  const APFloat &RHS) {
2442  switch (Opcode) {
2443  default:
2444  Info.FFDiag(E);
2445  return false;
2446  case BO_Mul:
2447  LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2448  break;
2449  case BO_Add:
2450  LHS.add(RHS, APFloat::rmNearestTiesToEven);
2451  break;
2452  case BO_Sub:
2453  LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2454  break;
2455  case BO_Div:
2456  // [expr.mul]p4:
2457  // If the second operand of / or % is zero the behavior is undefined.
2458  if (RHS.isZero())
2459  Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2460  LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2461  break;
2462  }
2463 
2464  // [expr.pre]p4:
2465  // If during the evaluation of an expression, the result is not
2466  // mathematically defined [...], the behavior is undefined.
2467  // FIXME: C++ rules require us to not conform to IEEE 754 here.
2468  if (LHS.isNaN()) {
2469  Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2470  return Info.noteUndefinedBehavior();
2471  }
2472  return true;
2473 }
2474 
2475 /// Cast an lvalue referring to a base subobject to a derived class, by
2476 /// truncating the lvalue's path to the given length.
2477 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2478  const RecordDecl *TruncatedType,
2479  unsigned TruncatedElements) {
2480  SubobjectDesignator &D = Result.Designator;
2481 
2482  // Check we actually point to a derived class object.
2483  if (TruncatedElements == D.Entries.size())
2484  return true;
2485  assert(TruncatedElements >= D.MostDerivedPathLength &&
2486  "not casting to a derived class");
2487  if (!Result.checkSubobject(Info, E, CSK_Derived))
2488  return false;
2489 
2490  // Truncate the path to the subobject, and remove any derived-to-base offsets.
2491  const RecordDecl *RD = TruncatedType;
2492  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2493  if (RD->isInvalidDecl()) return false;
2494  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2495  const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2496  if (isVirtualBaseClass(D.Entries[I]))
2497  Result.Offset -= Layout.getVBaseClassOffset(Base);
2498  else
2499  Result.Offset -= Layout.getBaseClassOffset(Base);
2500  RD = Base;
2501  }
2502  D.Entries.resize(TruncatedElements);
2503  return true;
2504 }
2505 
2506 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2507  const CXXRecordDecl *Derived,
2508  const CXXRecordDecl *Base,
2509  const ASTRecordLayout *RL = nullptr) {
2510  if (!RL) {
2511  if (Derived->isInvalidDecl()) return false;
2512  RL = &Info.Ctx.getASTRecordLayout(Derived);
2513  }
2514 
2515  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2516  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2517  return true;
2518 }
2519 
2520 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2521  const CXXRecordDecl *DerivedDecl,
2522  const CXXBaseSpecifier *Base) {
2523  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2524 
2525  if (!Base->isVirtual())
2526  return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2527 
2528  SubobjectDesignator &D = Obj.Designator;
2529  if (D.Invalid)
2530  return false;
2531 
2532  // Extract most-derived object and corresponding type.
2533  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2534  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2535  return false;
2536 
2537  // Find the virtual base class.
2538  if (DerivedDecl->isInvalidDecl()) return false;
2539  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2540  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2541  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2542  return true;
2543 }
2544 
2545 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2546  QualType Type, LValue &Result) {
2547  for (CastExpr::path_const_iterator PathI = E->path_begin(),
2548  PathE = E->path_end();
2549  PathI != PathE; ++PathI) {
2550  if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2551  *PathI))
2552  return false;
2553  Type = (*PathI)->getType();
2554  }
2555  return true;
2556 }
2557 
2558 /// Cast an lvalue referring to a derived class to a known base subobject.
2559 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2560  const CXXRecordDecl *DerivedRD,
2561  const CXXRecordDecl *BaseRD) {
2562  CXXBasePaths Paths(/*FindAmbiguities=*/false,
2563  /*RecordPaths=*/true, /*DetectVirtual=*/false);
2564  if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2565  llvm_unreachable("Class must be derived from the passed in base class!");
2566 
2567  for (CXXBasePathElement &Elem : Paths.front())
2568  if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2569  return false;
2570  return true;
2571 }
2572 
2573 /// Update LVal to refer to the given field, which must be a member of the type
2574 /// currently described by LVal.
2575 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2576  const FieldDecl *FD,
2577  const ASTRecordLayout *RL = nullptr) {
2578  if (!RL) {
2579  if (FD->getParent()->isInvalidDecl()) return false;
2580  RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2581  }
2582 
2583  unsigned I = FD->getFieldIndex();
2584  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2585  LVal.addDecl(Info, E, FD);
2586  return true;
2587 }
2588 
2589 /// Update LVal to refer to the given indirect field.
2590 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2591  LValue &LVal,
2592  const IndirectFieldDecl *IFD) {
2593  for (const auto *C : IFD->chain())
2594  if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2595  return false;
2596  return true;
2597 }
2598 
2599 /// Get the size of the given type in char units.
2600 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2601  QualType Type, CharUnits &Size) {
2602  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2603  // extension.
2604  if (Type->isVoidType() || Type->isFunctionType()) {
2605  Size = CharUnits::One();
2606  return true;
2607  }
2608 
2609  if (Type->isDependentType()) {
2610  Info.FFDiag(Loc);
2611  return false;
2612  }
2613 
2614  if (!Type->isConstantSizeType()) {
2615  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2616  // FIXME: Better diagnostic.
2617  Info.FFDiag(Loc);
2618  return false;
2619  }
2620 
2621  Size = Info.Ctx.getTypeSizeInChars(Type);
2622  return true;
2623 }
2624 
2625 /// Update a pointer value to model pointer arithmetic.
2626 /// \param Info - Information about the ongoing evaluation.
2627 /// \param E - The expression being evaluated, for diagnostic purposes.
2628 /// \param LVal - The pointer value to be updated.
2629 /// \param EltTy - The pointee type represented by LVal.
2630 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2631 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2632  LValue &LVal, QualType EltTy,
2633  APSInt Adjustment) {
2634  CharUnits SizeOfPointee;
2635  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2636  return false;
2637 
2638  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2639  return true;
2640 }
2641 
2642 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2643  LValue &LVal, QualType EltTy,
2644  int64_t Adjustment) {
2645  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2646  APSInt::get(Adjustment));
2647 }
2648 
2649 /// Update an lvalue to refer to a component of a complex number.
2650 /// \param Info - Information about the ongoing evaluation.
2651 /// \param LVal - The lvalue to be updated.
2652 /// \param EltTy - The complex number's component type.
2653 /// \param Imag - False for the real component, true for the imaginary.
2654 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2655  LValue &LVal, QualType EltTy,
2656  bool Imag) {
2657  if (Imag) {
2658  CharUnits SizeOfComponent;
2659  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2660  return false;
2661  LVal.Offset += SizeOfComponent;
2662  }
2663  LVal.addComplex(Info, E, EltTy, Imag);
2664  return true;
2665 }
2666 
2667 /// Try to evaluate the initializer for a variable declaration.
2668 ///
2669 /// \param Info Information about the ongoing evaluation.
2670 /// \param E An expression to be used when printing diagnostics.
2671 /// \param VD The variable whose initializer should be obtained.
2672 /// \param Frame The frame in which the variable was created. Must be null
2673 /// if this variable is not local to the evaluation.
2674 /// \param Result Filled in with a pointer to the value of the variable.
2675 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2676  const VarDecl *VD, CallStackFrame *Frame,
2677  APValue *&Result, const LValue *LVal) {
2678 
2679  // If this is a parameter to an active constexpr function call, perform
2680  // argument substitution.
2681  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2682  // Assume arguments of a potential constant expression are unknown
2683  // constant expressions.
2684  if (Info.checkingPotentialConstantExpression())
2685  return false;
2686  if (!Frame || !Frame->Arguments) {
2687  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2688  return false;
2689  }
2690  Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2691  return true;
2692  }
2693 
2694  // If this is a local variable, dig out its value.
2695  if (Frame) {
2696  Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2697  : Frame->getCurrentTemporary(VD);
2698  if (!Result) {
2699  // Assume variables referenced within a lambda's call operator that were
2700  // not declared within the call operator are captures and during checking
2701  // of a potential constant expression, assume they are unknown constant
2702  // expressions.
2703  assert(isLambdaCallOperator(Frame->Callee) &&
2704  (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2705  "missing value for local variable");
2706  if (Info.checkingPotentialConstantExpression())
2707  return false;
2708  // FIXME: implement capture evaluation during constant expr evaluation.
2709  Info.FFDiag(E->getBeginLoc(),
2710  diag::note_unimplemented_constexpr_lambda_feature_ast)
2711  << "captures not currently allowed";
2712  return false;
2713  }
2714  return true;
2715  }
2716 
2717  // Dig out the initializer, and use the declaration which it's attached to.
2718  const Expr *Init = VD->getAnyInitializer(VD);
2719  if (!Init || Init->isValueDependent()) {
2720  // If we're checking a potential constant expression, the variable could be
2721  // initialized later.
2722  if (!Info.checkingPotentialConstantExpression())
2723  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2724  return false;
2725  }
2726 
2727  // If we're currently evaluating the initializer of this declaration, use that
2728  // in-flight value.
2729  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2730  Result = Info.EvaluatingDeclValue;
2731  return true;
2732  }
2733 
2734  // Never evaluate the initializer of a weak variable. We can't be sure that
2735  // this is the definition which will be used.
2736  if (VD->isWeak()) {
2737  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2738  return false;
2739  }
2740 
2741  // Check that we can fold the initializer. In C++, we will have already done
2742  // this in the cases where it matters for conformance.
2744  if (!VD->evaluateValue(Notes)) {
2745  Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2746  Notes.size() + 1) << VD;
2747  Info.Note(VD->getLocation(), diag::note_declared_at);
2748  Info.addNotes(Notes);
2749  return false;
2750  } else if (!VD->checkInitIsICE()) {
2751  Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2752  Notes.size() + 1) << VD;
2753  Info.Note(VD->getLocation(), diag::note_declared_at);
2754  Info.addNotes(Notes);
2755  }
2756 
2757  Result = VD->getEvaluatedValue();
2758  return true;
2759 }
2760 
2762  Qualifiers Quals = T.getQualifiers();
2763  return Quals.hasConst() && !Quals.hasVolatile();
2764 }
2765 
2766 /// Get the base index of the given base class within an APValue representing
2767 /// the given derived class.
2768 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2769  const CXXRecordDecl *Base) {
2770  Base = Base->getCanonicalDecl();
2771  unsigned Index = 0;
2773  E = Derived->bases_end(); I != E; ++I, ++Index) {
2774  if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2775  return Index;
2776  }
2777 
2778  llvm_unreachable("base class missing from derived class's bases list");
2779 }
2780 
2781 /// Extract the value of a character from a string literal.
2782 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2783  uint64_t Index) {
2784  assert(!isa<SourceLocExpr>(Lit) &&
2785  "SourceLocExpr should have already been converted to a StringLiteral");
2786 
2787  // FIXME: Support MakeStringConstant
2788  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2789  std::string Str;
2790  Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2791  assert(Index <= Str.size() && "Index too large");
2792  return APSInt::getUnsigned(Str.c_str()[Index]);
2793  }
2794 
2795  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2796  Lit = PE->getFunctionName();
2797  const StringLiteral *S = cast<StringLiteral>(Lit);
2798  const ConstantArrayType *CAT =
2799  Info.Ctx.getAsConstantArrayType(S->getType());
2800  assert(CAT && "string literal isn't an array");
2801  QualType CharType = CAT->getElementType();
2802  assert(CharType->isIntegerType() && "unexpected character type");
2803 
2804  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2805  CharType->isUnsignedIntegerType());
2806  if (Index < S->getLength())
2807  Value = S->getCodeUnit(Index);
2808  return Value;
2809 }
2810 
2811 // Expand a string literal into an array of characters.
2812 //
2813 // FIXME: This is inefficient; we should probably introduce something similar
2814 // to the LLVM ConstantDataArray to make this cheaper.
2815 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2816  APValue &Result) {
2817  const ConstantArrayType *CAT =
2818  Info.Ctx.getAsConstantArrayType(S->getType());
2819  assert(CAT && "string literal isn't an array");
2820  QualType CharType = CAT->getElementType();
2821  assert(CharType->isIntegerType() && "unexpected character type");
2822 
2823  unsigned Elts = CAT->getSize().getZExtValue();
2824  Result = APValue(APValue::UninitArray(),
2825  std::min(S->getLength(), Elts), Elts);
2826  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2827  CharType->isUnsignedIntegerType());
2828  if (Result.hasArrayFiller())
2829  Result.getArrayFiller() = APValue(Value);
2830  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2831  Value = S->getCodeUnit(I);
2832  Result.getArrayInitializedElt(I) = APValue(Value);
2833  }
2834 }
2835 
2836 // Expand an array so that it has more than Index filled elements.
2837 static void expandArray(APValue &Array, unsigned Index) {
2838  unsigned Size = Array.getArraySize();
2839  assert(Index < Size);
2840 
2841  // Always at least double the number of elements for which we store a value.
2842  unsigned OldElts = Array.getArrayInitializedElts();
2843  unsigned NewElts = std::max(Index+1, OldElts * 2);
2844  NewElts = std::min(Size, std::max(NewElts, 8u));
2845 
2846  // Copy the data across.
2847  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2848  for (unsigned I = 0; I != OldElts; ++I)
2849  NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2850  for (unsigned I = OldElts; I != NewElts; ++I)
2851  NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2852  if (NewValue.hasArrayFiller())
2853  NewValue.getArrayFiller() = Array.getArrayFiller();
2854  Array.swap(NewValue);
2855 }
2856 
2857 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2858 /// conversion. If it's of class type, we may assume that the copy operation
2859 /// is trivial. Note that this is never true for a union type with fields
2860 /// (because the copy always "reads" the active member) and always true for
2861 /// a non-class type.
2864  if (!RD || (RD->isUnion() && !RD->field_empty()))
2865  return true;
2866  if (RD->isEmpty())
2867  return false;
2868 
2869  for (auto *Field : RD->fields())
2870  if (isReadByLvalueToRvalueConversion(Field->getType()))
2871  return true;
2872 
2873  for (auto &BaseSpec : RD->bases())
2874  if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2875  return true;
2876 
2877  return false;
2878 }
2879 
2880 /// Diagnose an attempt to read from any unreadable field within the specified
2881 /// type, which might be a class type.
2882 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2883  QualType T) {
2885  if (!RD)
2886  return false;
2887 
2888  if (!RD->hasMutableFields())
2889  return false;
2890 
2891  for (auto *Field : RD->fields()) {
2892  // If we're actually going to read this field in some way, then it can't
2893  // be mutable. If we're in a union, then assigning to a mutable field
2894  // (even an empty one) can change the active member, so that's not OK.
2895  // FIXME: Add core issue number for the union case.
2896  if (Field->isMutable() &&
2897  (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2898  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2899  Info.Note(Field->getLocation(), diag::note_declared_at);
2900  return true;
2901  }
2902 
2903  if (diagnoseUnreadableFields(Info, E, Field->getType()))
2904  return true;
2905  }
2906 
2907  for (auto &BaseSpec : RD->bases())
2908  if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2909  return true;
2910 
2911  // All mutable fields were empty, and thus not actually read.
2912  return false;
2913 }
2914 
2915 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2916  APValue::LValueBase Base) {
2917  // A temporary we created.
2918  if (Base.getCallIndex())
2919  return true;
2920 
2921  auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2922  if (!Evaluating)
2923  return false;
2924 
2925  // The variable whose initializer we're evaluating.
2926  if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2927  if (declaresSameEntity(Evaluating, BaseD))
2928  return true;
2929 
2930  // A temporary lifetime-extended by the variable whose initializer we're
2931  // evaluating.
2932  if (auto *BaseE = Base.dyn_cast<const Expr *>())
2933  if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2934  if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2935  return true;
2936 
2937  return false;
2938 }
2939 
2940 namespace {
2941 /// A handle to a complete object (an object that is not a subobject of
2942 /// another object).
2943 struct CompleteObject {
2944  /// The identity of the object.
2945  APValue::LValueBase Base;
2946  /// The value of the complete object.
2947  APValue *Value;
2948  /// The type of the complete object.
2949  QualType Type;
2950 
2951  CompleteObject() : Value(nullptr) {}
2952  CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2953  : Base(Base), Value(Value), Type(Type) {}
2954 
2955  bool mayReadMutableMembers(EvalInfo &Info) const {
2956  // In C++14 onwards, it is permitted to read a mutable member whose
2957  // lifetime began within the evaluation.
2958  // FIXME: Should we also allow this in C++11?
2959  if (!Info.getLangOpts().CPlusPlus14)
2960  return false;
2961  return lifetimeStartedInEvaluation(Info, Base);
2962  }
2963 
2964  explicit operator bool() const { return !Type.isNull(); }
2965 };
2966 } // end anonymous namespace
2967 
2968 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2969  bool IsMutable = false) {
2970  // C++ [basic.type.qualifier]p1:
2971  // - A const object is an object of type const T or a non-mutable subobject
2972  // of a const object.
2973  if (ObjType.isConstQualified() && !IsMutable)
2974  SubobjType.addConst();
2975  // - A volatile object is an object of type const T or a subobject of a
2976  // volatile object.
2977  if (ObjType.isVolatileQualified())
2978  SubobjType.addVolatile();
2979  return SubobjType;
2980 }
2981 
2982 /// Find the designated sub-object of an rvalue.
2983 template<typename SubobjectHandler>
2984 typename SubobjectHandler::result_type
2985 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2986  const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2987  if (Sub.Invalid)
2988  // A diagnostic will have already been produced.
2989  return handler.failed();
2990  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2991  if (Info.getLangOpts().CPlusPlus11)
2992  Info.FFDiag(E, Sub.isOnePastTheEnd()
2993  ? diag::note_constexpr_access_past_end
2994  : diag::note_constexpr_access_unsized_array)
2995  << handler.AccessKind;
2996  else
2997  Info.FFDiag(E);
2998  return handler.failed();
2999  }
3000 
3001  APValue *O = Obj.Value;
3002  QualType ObjType = Obj.Type;
3003  const FieldDecl *LastField = nullptr;
3004  const FieldDecl *VolatileField = nullptr;
3005 
3006  // Walk the designator's path to find the subobject.
3007  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3008  // Reading an indeterminate value is undefined, but assigning over one is OK.
3009  if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
3010  if (!Info.checkingPotentialConstantExpression())
3011  Info.FFDiag(E, diag::note_constexpr_access_uninit)
3012  << handler.AccessKind << O->isIndeterminate();
3013  return handler.failed();
3014  }
3015 
3016  // C++ [class.ctor]p5:
3017  // const and volatile semantics are not applied on an object under
3018  // construction.
3019  if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3020  ObjType->isRecordType() &&
3021  Info.isEvaluatingConstructor(
3022  Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3023  Sub.Entries.begin() + I)) !=
3025  ObjType = Info.Ctx.getCanonicalType(ObjType);
3026  ObjType.removeLocalConst();
3027  ObjType.removeLocalVolatile();
3028  }
3029 
3030  // If this is our last pass, check that the final object type is OK.
3031  if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3032  // Accesses to volatile objects are prohibited.
3033  if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3034  if (Info.getLangOpts().CPlusPlus) {
3035  int DiagKind;
3036  SourceLocation Loc;
3037  const NamedDecl *Decl = nullptr;
3038  if (VolatileField) {
3039  DiagKind = 2;
3040  Loc = VolatileField->getLocation();
3041  Decl = VolatileField;
3042  } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3043  DiagKind = 1;
3044  Loc = VD->getLocation();
3045  Decl = VD;
3046  } else {
3047  DiagKind = 0;
3048  if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3049  Loc = E->getExprLoc();
3050  }
3051  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3052  << handler.AccessKind << DiagKind << Decl;
3053  Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3054  } else {
3055  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3056  }
3057  return handler.failed();
3058  }
3059 
3060  // If we are reading an object of class type, there may still be more
3061  // things we need to check: if there are any mutable subobjects, we
3062  // cannot perform this read. (This only happens when performing a trivial
3063  // copy or assignment.)
3064  if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3065  !Obj.mayReadMutableMembers(Info) &&
3066  diagnoseUnreadableFields(Info, E, ObjType))
3067  return handler.failed();
3068  }
3069 
3070  if (I == N) {
3071  if (!handler.found(*O, ObjType))
3072  return false;
3073 
3074  // If we modified a bit-field, truncate it to the right width.
3075  if (isModification(handler.AccessKind) &&
3076  LastField && LastField->isBitField() &&
3077  !truncateBitfieldValue(Info, E, *O, LastField))
3078  return false;
3079 
3080  return true;
3081  }
3082 
3083  LastField = nullptr;
3084  if (ObjType->isArrayType()) {
3085  // Next subobject is an array element.
3086  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3087  assert(CAT && "vla in literal type?");
3088  uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3089  if (CAT->getSize().ule(Index)) {
3090  // Note, it should not be possible to form a pointer with a valid
3091  // designator which points more than one past the end of the array.
3092  if (Info.getLangOpts().CPlusPlus11)
3093  Info.FFDiag(E, diag::note_constexpr_access_past_end)
3094  << handler.AccessKind;
3095  else
3096  Info.FFDiag(E);
3097  return handler.failed();
3098  }
3099 
3100  ObjType = CAT->getElementType();
3101 
3102  if (O->getArrayInitializedElts() > Index)
3103  O = &O->getArrayInitializedElt(Index);
3104  else if (handler.AccessKind != AK_Read) {
3105  expandArray(*O, Index);
3106  O = &O->getArrayInitializedElt(Index);
3107  } else
3108  O = &O->getArrayFiller();
3109  } else if (ObjType->isAnyComplexType()) {
3110  // Next subobject is a complex number.
3111  uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3112  if (Index > 1) {
3113  if (Info.getLangOpts().CPlusPlus11)
3114  Info.FFDiag(E, diag::note_constexpr_access_past_end)
3115  << handler.AccessKind;
3116  else
3117  Info.FFDiag(E);
3118  return handler.failed();
3119  }
3120 
3121  ObjType = getSubobjectType(
3122  ObjType, ObjType->castAs<ComplexType>()->getElementType());
3123 
3124  assert(I == N - 1 && "extracting subobject of scalar?");
3125  if (O->isComplexInt()) {
3126  return handler.found(Index ? O->getComplexIntImag()
3127  : O->getComplexIntReal(), ObjType);
3128  } else {
3129  assert(O->isComplexFloat());
3130  return handler.found(Index ? O->getComplexFloatImag()
3131  : O->getComplexFloatReal(), ObjType);
3132  }
3133  } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3134  if (Field->isMutable() && handler.AccessKind == AK_Read &&
3135  !Obj.mayReadMutableMembers(Info)) {
3136  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3137  << Field;
3138  Info.Note(Field->getLocation(), diag::note_declared_at);
3139  return handler.failed();
3140  }
3141 
3142  // Next subobject is a class, struct or union field.
3143  RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3144  if (RD->isUnion()) {
3145  const FieldDecl *UnionField = O->getUnionField();
3146  if (!UnionField ||
3147  UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3148  Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3149  << handler.AccessKind << Field << !UnionField << UnionField;
3150  return handler.failed();
3151  }
3152  O = &O->getUnionValue();
3153  } else
3154  O = &O->getStructField(Field->getFieldIndex());
3155 
3156  ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3157  LastField = Field;
3158  if (Field->getType().isVolatileQualified())
3159  VolatileField = Field;
3160  } else {
3161  // Next subobject is a base class.
3162  const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3163  const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3164  O = &O->getStructBase(getBaseIndex(Derived, Base));
3165 
3166  ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3167  }
3168  }
3169 }
3170 
3171 namespace {
3172 struct ExtractSubobjectHandler {
3173  EvalInfo &Info;
3174  APValue &Result;
3175 
3176  static const AccessKinds AccessKind = AK_Read;
3177 
3178  typedef bool result_type;
3179  bool failed() { return false; }
3180  bool found(APValue &Subobj, QualType SubobjType) {
3181  Result = Subobj;
3182  return true;
3183  }
3184  bool found(APSInt &Value, QualType SubobjType) {
3185  Result = APValue(Value);
3186  return true;
3187  }
3188  bool found(APFloat &Value, QualType SubobjType) {
3189  Result = APValue(Value);
3190  return true;
3191  }
3192 };
3193 } // end anonymous namespace
3194 
3196 
3197 /// Extract the designated sub-object of an rvalue.
3198 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3199  const CompleteObject &Obj,
3200  const SubobjectDesignator &Sub,
3201  APValue &Result) {
3202  ExtractSubobjectHandler Handler = { Info, Result };
3203  return findSubobject(Info, E, Obj, Sub, Handler);
3204 }
3205 
3206 namespace {
3207 struct ModifySubobjectHandler {
3208  EvalInfo &Info;
3209  APValue &NewVal;
3210  const Expr *E;
3211 
3212  typedef bool result_type;
3213  static const AccessKinds AccessKind = AK_Assign;
3214 
3215  bool checkConst(QualType QT) {
3216  // Assigning to a const object has undefined behavior.
3217  if (QT.isConstQualified()) {
3218  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3219  return false;
3220  }
3221  return true;
3222  }
3223 
3224  bool failed() { return false; }
3225  bool found(APValue &Subobj, QualType SubobjType) {
3226  if (!checkConst(SubobjType))
3227  return false;
3228  // We've been given ownership of NewVal, so just swap it in.
3229  Subobj.swap(NewVal);
3230  return true;
3231  }
3232  bool found(APSInt &Value, QualType SubobjType) {
3233  if (!checkConst(SubobjType))
3234  return false;
3235  if (!NewVal.isInt()) {
3236  // Maybe trying to write a cast pointer value into a complex?
3237  Info.FFDiag(E);
3238  return false;
3239  }
3240  Value = NewVal.getInt();
3241  return true;
3242  }
3243  bool found(APFloat &Value, QualType SubobjType) {
3244  if (!checkConst(SubobjType))
3245  return false;
3246  Value = NewVal.getFloat();
3247  return true;
3248  }
3249 };
3250 } // end anonymous namespace
3251 
3253 
3254 /// Update the designated sub-object of an rvalue to the given value.
3255 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3256  const CompleteObject &Obj,
3257  const SubobjectDesignator &Sub,
3258  APValue &NewVal) {
3259  ModifySubobjectHandler Handler = { Info, NewVal, E };
3260  return findSubobject(Info, E, Obj, Sub, Handler);
3261 }
3262 
3263 /// Find the position where two subobject designators diverge, or equivalently
3264 /// the length of the common initial subsequence.
3265 static unsigned FindDesignatorMismatch(QualType ObjType,
3266  const SubobjectDesignator &A,
3267  const SubobjectDesignator &B,
3268  bool &WasArrayIndex) {
3269  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3270  for (/**/; I != N; ++I) {
3271  if (!ObjType.isNull() &&
3272  (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3273  // Next subobject is an array element.
3274  if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3275  WasArrayIndex = true;
3276  return I;
3277  }
3278  if (ObjType->isAnyComplexType())
3279  ObjType = ObjType->castAs<ComplexType>()->getElementType();
3280  else
3281  ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3282  } else {
3283  if (A.Entries[I].getAsBaseOrMember() !=
3284  B.Entries[I].getAsBaseOrMember()) {
3285  WasArrayIndex = false;
3286  return I;
3287  }
3288  if (const FieldDecl *FD = getAsField(A.Entries[I]))
3289  // Next subobject is a field.
3290  ObjType = FD->getType();
3291  else
3292  // Next subobject is a base class.
3293  ObjType = QualType();
3294  }
3295  }
3296  WasArrayIndex = false;
3297  return I;
3298 }
3299 
3300 /// Determine whether the given subobject designators refer to elements of the
3301 /// same array object.
3302 static bool AreElementsOfSameArray(QualType ObjType,
3303  const SubobjectDesignator &A,
3304  const SubobjectDesignator &B) {
3305  if (A.Entries.size() != B.Entries.size())
3306  return false;
3307 
3308  bool IsArray = A.MostDerivedIsArrayElement;
3309  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3310  // A is a subobject of the array element.
3311  return false;
3312 
3313  // If A (and B) designates an array element, the last entry will be the array
3314  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3315  // of length 1' case, and the entire path must match.
3316  bool WasArrayIndex;
3317  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3318  return CommonLength >= A.Entries.size() - IsArray;
3319 }
3320 
3321 /// Find the complete object to which an LValue refers.
3322 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3323  AccessKinds AK, const LValue &LVal,
3324  QualType LValType) {
3325  if (LVal.InvalidBase) {
3326  Info.FFDiag(E);
3327  return CompleteObject();
3328  }
3329 
3330  if (!LVal.Base) {
3331  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3332  return CompleteObject();
3333  }
3334 
3335  CallStackFrame *Frame = nullptr;
3336  unsigned Depth = 0;
3337  if (LVal.getLValueCallIndex()) {
3338  std::tie(Frame, Depth) =
3339  Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3340  if (!Frame) {
3341  Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3342  << AK << LVal.Base.is<const ValueDecl*>();
3343  NoteLValueLocation(Info, LVal.Base);
3344  return CompleteObject();
3345  }
3346  }
3347 
3348  bool IsAccess = isFormalAccess(AK);
3349 
3350  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3351  // is not a constant expression (even if the object is non-volatile). We also
3352  // apply this rule to C++98, in order to conform to the expected 'volatile'
3353  // semantics.
3354  if (IsAccess && LValType.isVolatileQualified()) {
3355  if (Info.getLangOpts().CPlusPlus)
3356  Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3357  << AK << LValType;
3358  else
3359  Info.FFDiag(E);
3360  return CompleteObject();
3361  }
3362 
3363  // Compute value storage location and type of base object.
3364  APValue *BaseVal = nullptr;
3365  QualType BaseType = getType(LVal.Base);
3366 
3367  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3368  // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3369  // In C++11, constexpr, non-volatile variables initialized with constant
3370  // expressions are constant expressions too. Inside constexpr functions,
3371  // parameters are constant expressions even if they're non-const.
3372  // In C++1y, objects local to a constant expression (those with a Frame) are
3373  // both readable and writable inside constant expressions.
3374  // In C, such things can also be folded, although they are not ICEs.
3375  const VarDecl *VD = dyn_cast<VarDecl>(D);
3376  if (VD) {
3377  if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3378  VD = VDef;
3379  }
3380  if (!VD || VD->isInvalidDecl()) {
3381  Info.FFDiag(E);
3382  return CompleteObject();
3383  }
3384 
3385  // Unless we're looking at a local variable or argument in a constexpr call,
3386  // the variable we're reading must be const.
3387  if (!Frame) {
3388  if (Info.getLangOpts().CPlusPlus14 &&
3390  VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3391  // OK, we can read and modify an object if we're in the process of
3392  // evaluating its initializer, because its lifetime began in this
3393  // evaluation.
3394  } else if (isModification(AK)) {
3395  // All the remaining cases do not permit modification of the object.
3396  Info.FFDiag(E, diag::note_constexpr_modify_global);
3397  return CompleteObject();
3398  } else if (VD->isConstexpr()) {
3399  // OK, we can read this variable.
3400  } else if (BaseType->isIntegralOrEnumerationType()) {
3401  // In OpenCL if a variable is in constant address space it is a const
3402  // value.
3403  if (!(BaseType.isConstQualified() ||
3404  (Info.getLangOpts().OpenCL &&
3405  BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3406  if (!IsAccess)
3407  return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3408  if (Info.getLangOpts().CPlusPlus) {
3409  Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3410  Info.Note(VD->getLocation(), diag::note_declared_at);
3411  } else {
3412  Info.FFDiag(E);
3413  }
3414  return CompleteObject();
3415  }
3416  } else if (!IsAccess) {
3417  return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3418  } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3419  // We support folding of const floating-point types, in order to make
3420  // static const data members of such types (supported as an extension)
3421  // more useful.
3422  if (Info.getLangOpts().CPlusPlus11) {
3423  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3424  Info.Note(VD->getLocation(), diag::note_declared_at);
3425  } else {
3426  Info.CCEDiag(E);
3427  }
3428  } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3429  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3430  // Keep evaluating to see what we can do.
3431  } else {
3432  // FIXME: Allow folding of values of any literal type in all languages.
3433  if (Info.checkingPotentialConstantExpression() &&
3434  VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3435  // The definition of this variable could be constexpr. We can't
3436  // access it right now, but may be able to in future.
3437  } else if (Info.getLangOpts().CPlusPlus11) {
3438  Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3439  Info.Note(VD->getLocation(), diag::note_declared_at);
3440  } else {
3441  Info.FFDiag(E);
3442  }
3443  return CompleteObject();
3444  }
3445  }
3446 
3447  if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3448  return CompleteObject();
3449  } else {
3450  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3451 
3452  if (!Frame) {
3453  if (const MaterializeTemporaryExpr *MTE =
3454  dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3455  assert(MTE->getStorageDuration() == SD_Static &&
3456  "should have a frame for a non-global materialized temporary");
3457 
3458  // Per C++1y [expr.const]p2:
3459  // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3460  // - a [...] glvalue of integral or enumeration type that refers to
3461  // a non-volatile const object [...]
3462  // [...]
3463  // - a [...] glvalue of literal type that refers to a non-volatile
3464  // object whose lifetime began within the evaluation of e.
3465  //
3466  // C++11 misses the 'began within the evaluation of e' check and
3467  // instead allows all temporaries, including things like:
3468  // int &&r = 1;
3469  // int x = ++r;
3470  // constexpr int k = r;
3471  // Therefore we use the C++14 rules in C++11 too.
3472  const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3473  const ValueDecl *ED = MTE->getExtendingDecl();
3474  if (!(BaseType.isConstQualified() &&
3475  BaseType->isIntegralOrEnumerationType()) &&
3476  !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3477  if (!IsAccess)
3478  return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3479  Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3480  Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3481  return CompleteObject();
3482  }
3483 
3484  BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3485  assert(BaseVal && "got reference to unevaluated temporary");
3486  } else {
3487  if (!IsAccess)
3488  return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3489  APValue Val;
3490  LVal.moveInto(Val);
3491  Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3492  << AK
3493  << Val.getAsString(Info.Ctx,
3494  Info.Ctx.getLValueReferenceType(LValType));
3495  NoteLValueLocation(Info, LVal.Base);
3496  return CompleteObject();
3497  }
3498  } else {
3499  BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3500  assert(BaseVal && "missing value for temporary");
3501  }
3502  }
3503 
3504  // In C++14, we can't safely access any mutable state when we might be
3505  // evaluating after an unmodeled side effect.
3506  //
3507  // FIXME: Not all local state is mutable. Allow local constant subobjects
3508  // to be read here (but take care with 'mutable' fields).
3509  if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3510  Info.EvalStatus.HasSideEffects) ||
3511  (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3512  return CompleteObject();
3513 
3514  return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3515 }
3516 
3517 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3518 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3519 /// glvalue referred to by an entity of reference type.
3520 ///
3521 /// \param Info - Information about the ongoing evaluation.
3522 /// \param Conv - The expression for which we are performing the conversion.
3523 /// Used for diagnostics.
3524 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3525 /// case of a non-class type).
3526 /// \param LVal - The glvalue on which we are attempting to perform this action.
3527 /// \param RVal - The produced value will be placed here.
3528 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3529  QualType Type,
3530  const LValue &LVal, APValue &RVal) {
3531  if (LVal.Designator.Invalid)
3532  return false;
3533 
3534  // Check for special cases where there is no existing APValue to look at.
3535  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3536 
3537  if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3538  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3539  // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3540  // initializer until now for such expressions. Such an expression can't be
3541  // an ICE in C, so this only matters for fold.
3542  if (Type.isVolatileQualified()) {
3543  Info.FFDiag(Conv);
3544  return false;
3545  }
3546  APValue Lit;
3547  if (!Evaluate(Lit, Info, CLE->getInitializer()))
3548  return false;
3549  CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3550  return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3551  } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3552  // Special-case character extraction so we don't have to construct an
3553  // APValue for the whole string.
3554  assert(LVal.Designator.Entries.size() <= 1 &&
3555  "Can only read characters from string literals");
3556  if (LVal.Designator.Entries.empty()) {
3557  // Fail for now for LValue to RValue conversion of an array.
3558  // (This shouldn't show up in C/C++, but it could be triggered by a
3559  // weird EvaluateAsRValue call from a tool.)
3560  Info.FFDiag(Conv);
3561  return false;
3562  }
3563  if (LVal.Designator.isOnePastTheEnd()) {
3564  if (Info.getLangOpts().CPlusPlus11)
3565  Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3566  else
3567  Info.FFDiag(Conv);
3568  return false;
3569  }
3570  uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3571  RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3572  return true;
3573  }
3574  }
3575 
3576  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3577  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3578 }
3579 
3580 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3581 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3582  QualType LValType, APValue &Val) {
3583  if (LVal.Designator.Invalid)
3584  return false;
3585 
3586  if (!Info.getLangOpts().CPlusPlus14) {
3587  Info.FFDiag(E);
3588  return false;
3589  }
3590 
3591  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3592  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3593 }
3594 
3595 namespace {
3596 struct CompoundAssignSubobjectHandler {
3597  EvalInfo &Info;
3598  const Expr *E;
3599  QualType PromotedLHSType;
3600  BinaryOperatorKind Opcode;
3601  const APValue &RHS;
3602 
3603  static const AccessKinds AccessKind = AK_Assign;
3604 
3605  typedef bool result_type;
3606 
3607  bool checkConst(QualType QT) {
3608  // Assigning to a const object has undefined behavior.
3609  if (QT.isConstQualified()) {
3610  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3611  return false;
3612  }
3613  return true;
3614  }
3615 
3616  bool failed() { return false; }
3617  bool found(APValue &Subobj, QualType SubobjType) {
3618  switch (Subobj.getKind()) {
3619  case APValue::Int:
3620  return found(Subobj.getInt(), SubobjType);
3621  case APValue::Float:
3622  return found(Subobj.getFloat(), SubobjType);
3623  case APValue::ComplexInt:
3624  case APValue::ComplexFloat:
3625  // FIXME: Implement complex compound assignment.
3626  Info.FFDiag(E);
3627  return false;
3628  case APValue::LValue:
3629  return foundPointer(Subobj, SubobjType);
3630  default:
3631  // FIXME: can this happen?
3632  Info.FFDiag(E);
3633  return false;
3634  }
3635  }
3636  bool found(APSInt &Value, QualType SubobjType) {
3637  if (!checkConst(SubobjType))
3638  return false;
3639 
3640  if (!SubobjType->isIntegerType()) {
3641  // We don't support compound assignment on integer-cast-to-pointer
3642  // values.
3643  Info.FFDiag(E);
3644  return false;
3645  }
3646 
3647  if (RHS.isInt()) {
3648  APSInt LHS =
3649  HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3650  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3651  return false;
3652  Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3653  return true;
3654  } else if (RHS.isFloat()) {
3655  APFloat FValue(0.0);
3656  return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3657  FValue) &&
3658  handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3659  HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3660  Value);
3661  }
3662 
3663  Info.FFDiag(E);
3664  return false;
3665  }
3666  bool found(APFloat &Value, QualType SubobjType) {
3667  return checkConst(SubobjType) &&
3668  HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3669  Value) &&
3670  handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3671  HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3672  }
3673  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3674  if (!checkConst(SubobjType))
3675  return false;
3676 
3677  QualType PointeeType;
3678  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3679  PointeeType = PT->getPointeeType();
3680 
3681  if (PointeeType.isNull() || !RHS.isInt() ||
3682  (Opcode != BO_Add && Opcode != BO_Sub)) {
3683  Info.FFDiag(E);
3684  return false;
3685  }
3686 
3687  APSInt Offset = RHS.getInt();
3688  if (Opcode == BO_Sub)
3689  negateAsSigned(Offset);
3690 
3691  LValue LVal;
3692  LVal.setFrom(Info.Ctx, Subobj);
3693  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3694  return false;
3695  LVal.moveInto(Subobj);
3696  return true;
3697  }
3698 };
3699 } // end anonymous namespace
3700 
3702 
3703 /// Perform a compound assignment of LVal <op>= RVal.
3705  EvalInfo &Info, const Expr *E,
3706  const LValue &LVal, QualType LValType, QualType PromotedLValType,
3707  BinaryOperatorKind Opcode, const APValue &RVal) {
3708  if (LVal.Designator.Invalid)
3709  return false;
3710 
3711  if (!Info.getLangOpts().CPlusPlus14) {
3712  Info.FFDiag(E);
3713  return false;
3714  }
3715 
3716  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3717  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3718  RVal };
3719  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3720 }
3721 
3722 namespace {
3723 struct IncDecSubobjectHandler {
3724  EvalInfo &Info;
3725  const UnaryOperator *E;
3727  APValue *Old;
3728 
3729  typedef bool result_type;
3730 
3731  bool checkConst(QualType QT) {
3732  // Assigning to a const object has undefined behavior.
3733  if (QT.isConstQualified()) {
3734  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3735  return false;
3736  }
3737  return true;
3738  }
3739 
3740  bool failed() { return false; }
3741  bool found(APValue &Subobj, QualType SubobjType) {
3742  // Stash the old value. Also clear Old, so we don't clobber it later
3743  // if we're post-incrementing a complex.
3744  if (Old) {
3745  *Old = Subobj;
3746  Old = nullptr;
3747  }
3748 
3749  switch (Subobj.getKind()) {
3750  case APValue::Int:
3751  return found(Subobj.getInt(), SubobjType);
3752  case APValue::Float:
3753  return found(Subobj.getFloat(), SubobjType);
3754  case APValue::ComplexInt:
3755  return found(Subobj.getComplexIntReal(),
3756  SubobjType->castAs<ComplexType>()->getElementType()
3757  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3758  case APValue::ComplexFloat:
3759  return found(Subobj.getComplexFloatReal(),
3760  SubobjType->castAs<ComplexType>()->getElementType()
3761  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3762  case APValue::LValue:
3763  return foundPointer(Subobj, SubobjType);
3764  default:
3765  // FIXME: can this happen?
3766  Info.FFDiag(E);
3767  return false;
3768  }
3769  }
3770  bool found(APSInt &Value, QualType SubobjType) {
3771  if (!checkConst(SubobjType))
3772  return false;
3773 
3774  if (!SubobjType->isIntegerType()) {
3775  // We don't support increment / decrement on integer-cast-to-pointer
3776  // values.
3777  Info.FFDiag(E);
3778  return false;
3779  }
3780 
3781  if (Old) *Old = APValue(Value);
3782 
3783  // bool arithmetic promotes to int, and the conversion back to bool
3784  // doesn't reduce mod 2^n, so special-case it.
3785  if (SubobjType->isBooleanType()) {
3786  if (AccessKind == AK_Increment)
3787  Value = 1;
3788  else
3789  Value = !Value;
3790  return true;
3791  }
3792 
3793  bool WasNegative = Value.isNegative();
3794  if (AccessKind == AK_Increment) {
3795  ++Value;
3796 
3797  if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3798  APSInt ActualValue(Value, /*IsUnsigned*/true);
3799  return HandleOverflow(Info, E, ActualValue, SubobjType);
3800  }
3801  } else {
3802  --Value;
3803 
3804  if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3805  unsigned BitWidth = Value.getBitWidth();
3806  APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3807  ActualValue.setBit(BitWidth);
3808  return HandleOverflow(Info, E, ActualValue, SubobjType);
3809  }
3810  }
3811  return true;
3812  }
3813  bool found(APFloat &Value, QualType SubobjType) {
3814  if (!checkConst(SubobjType))
3815  return false;
3816 
3817  if (Old) *Old = APValue(Value);
3818 
3819  APFloat One(Value.getSemantics(), 1);
3820  if (AccessKind == AK_Increment)
3821  Value.add(One, APFloat::rmNearestTiesToEven);
3822  else
3823  Value.subtract(One, APFloat::rmNearestTiesToEven);
3824  return true;
3825  }
3826  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3827  if (!checkConst(SubobjType))
3828  return false;
3829 
3830  QualType PointeeType;
3831  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3832  PointeeType = PT->getPointeeType();
3833  else {
3834  Info.FFDiag(E);
3835  return false;
3836  }
3837 
3838  LValue LVal;
3839  LVal.setFrom(Info.Ctx, Subobj);
3840  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3841  AccessKind == AK_Increment ? 1 : -1))
3842  return false;
3843  LVal.moveInto(Subobj);
3844  return true;
3845  }
3846 };
3847 } // end anonymous namespace
3848 
3849 /// Perform an increment or decrement on LVal.
3850 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3851  QualType LValType, bool IsIncrement, APValue *Old) {
3852  if (LVal.Designator.Invalid)
3853  return false;
3854 
3855  if (!Info.getLangOpts().CPlusPlus14) {
3856  Info.FFDiag(E);
3857  return false;
3858  }
3859 
3860  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3861  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3862  IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3863  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3864 }
3865 
3866 /// Build an lvalue for the object argument of a member function call.
3867 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3868  LValue &This) {
3869  if (Object->getType()->isPointerType())
3870  return EvaluatePointer(Object, This, Info);
3871 
3872  if (Object->isGLValue())
3873  return EvaluateLValue(Object, This, Info);
3874 
3875  if (Object->getType()->isLiteralType(Info.Ctx))
3876  return EvaluateTemporary(Object, This, Info);
3877 
3878  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3879  return false;
3880 }
3881 
3882 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3883 /// lvalue referring to the result.
3884 ///
3885 /// \param Info - Information about the ongoing evaluation.
3886 /// \param LV - An lvalue referring to the base of the member pointer.
3887 /// \param RHS - The member pointer expression.
3888 /// \param IncludeMember - Specifies whether the member itself is included in
3889 /// the resulting LValue subobject designator. This is not possible when
3890 /// creating a bound member function.
3891 /// \return The field or method declaration to which the member pointer refers,
3892 /// or 0 if evaluation fails.
3893 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3894  QualType LVType,
3895  LValue &LV,
3896  const Expr *RHS,
3897  bool IncludeMember = true) {
3898  MemberPtr MemPtr;
3899  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3900  return nullptr;
3901 
3902  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3903  // member value, the behavior is undefined.
3904  if (!MemPtr.getDecl()) {
3905  // FIXME: Specific diagnostic.
3906  Info.FFDiag(RHS);
3907  return nullptr;
3908  }
3909 
3910  if (MemPtr.isDerivedMember()) {
3911  // This is a member of some derived class. Truncate LV appropriately.
3912  // The end of the derived-to-base path for the base object must match the
3913  // derived-to-base path for the member pointer.
3914  if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3915  LV.Designator.Entries.size()) {
3916  Info.FFDiag(RHS);
3917  return nullptr;
3918  }
3919  unsigned PathLengthToMember =
3920  LV.Designator.Entries.size() - MemPtr.Path.size();
3921  for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3922  const CXXRecordDecl *LVDecl = getAsBaseClass(
3923  LV.Designator.Entries[PathLengthToMember + I]);
3924  const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3925  if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3926  Info.FFDiag(RHS);
3927  return nullptr;
3928  }
3929  }
3930 
3931  // Truncate the lvalue to the appropriate derived class.
3932  if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3933  PathLengthToMember))
3934  return nullptr;
3935  } else if (!MemPtr.Path.empty()) {
3936  // Extend the LValue path with the member pointer's path.
3937  LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3938  MemPtr.Path.size() + IncludeMember);
3939 
3940  // Walk down to the appropriate base class.
3941  if (const PointerType *PT = LVType->getAs<PointerType>())
3942  LVType = PT->getPointeeType();
3943  const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3944  assert(RD && "member pointer access on non-class-type expression");
3945  // The first class in the path is that of the lvalue.
3946  for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3947  const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3948  if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3949  return nullptr;
3950  RD = Base;
3951  }
3952  // Finally cast to the class containing the member.
3953  if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3954  MemPtr.getContainingRecord()))
3955  return nullptr;
3956  }
3957 
3958  // Add the member. Note that we cannot build bound member functions here.
3959  if (IncludeMember) {
3960  if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3961  if (!HandleLValueMember(Info, RHS, LV, FD))
3962  return nullptr;
3963  } else if (const IndirectFieldDecl *IFD =
3964  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3965  if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3966  return nullptr;
3967  } else {
3968  llvm_unreachable("can't construct reference to bound member function");
3969  }
3970  }
3971 
3972  return MemPtr.getDecl();
3973 }
3974 
3975 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3976  const BinaryOperator *BO,
3977  LValue &LV,
3978  bool IncludeMember = true) {
3979  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3980 
3981  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3982  if (Info.noteFailure()) {
3983  MemberPtr MemPtr;
3984  EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3985  }
3986  return nullptr;
3987  }
3988 
3989  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3990  BO->getRHS(), IncludeMember);
3991 }
3992 
3993 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3994 /// the provided lvalue, which currently refers to the base object.
3995 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3996  LValue &Result) {
3997  SubobjectDesignator &D = Result.Designator;
3998  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3999  return false;
4000 
4001  QualType TargetQT = E->getType();
4002  if (const PointerType *PT = TargetQT->getAs<PointerType>())
4003  TargetQT = PT->getPointeeType();
4004 
4005  // Check this cast lands within the final derived-to-base subobject path.
4006  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4007  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4008  << D.MostDerivedType << TargetQT;
4009  return false;
4010  }
4011 
4012  // Check the type of the final cast. We don't need to check the path,
4013  // since a cast can only be formed if the path is unique.
4014  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4015  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4016  const CXXRecordDecl *FinalType;
4017  if (NewEntriesSize == D.MostDerivedPathLength)
4018  FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4019  else
4020  FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4021  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4022  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4023  << D.MostDerivedType << TargetQT;
4024  return false;
4025  }
4026 
4027  // Truncate the lvalue to the appropriate derived class.
4028  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4029 }
4030 
4031 namespace {
4033  /// Evaluation failed.
4034  ESR_Failed,
4035  /// Hit a 'return' statement.
4036  ESR_Returned,
4037  /// Evaluation succeeded.
4038  ESR_Succeeded,
4039  /// Hit a 'continue' statement.
4040  ESR_Continue,
4041  /// Hit a 'break' statement.
4042  ESR_Break,
4043  /// Still scanning for 'case' or 'default' statement.
4044  ESR_CaseNotFound
4045 };
4046 }
4047 
4048 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4049  // We don't need to evaluate the initializer for a static local.
4050  if (!VD->hasLocalStorage())
4051  return true;
4052 
4053  LValue Result;
4054  APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4055 
4056  const Expr *InitE = VD->getInit();
4057  if (!InitE) {
4058  Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4059  << false << VD->getType();
4060  Val = APValue();
4061  return false;
4062  }
4063 
4064  if (InitE->isValueDependent())
4065  return false;
4066 
4067  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4068  // Wipe out any partially-computed value, to allow tracking that this
4069  // evaluation failed.
4070  Val = APValue();
4071  return false;
4072  }
4073 
4074  return true;
4075 }
4076 
4077 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4078  bool OK = true;
4079 
4080  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4081  OK &= EvaluateVarDecl(Info, VD);
4082 
4083  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4084  for (auto *BD : DD->bindings())
4085  if (auto *VD = BD->getHoldingVar())
4086  OK &= EvaluateDecl(Info, VD);
4087 
4088  return OK;
4089 }
4090 
4091 
4092 /// Evaluate a condition (either a variable declaration or an expression).
4093 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4094  const Expr *Cond, bool &Result) {
4095  FullExpressionRAII Scope(Info);
4096  if (CondDecl && !EvaluateDecl(Info, CondDecl))
4097  return false;
4098  return EvaluateAsBooleanCondition(Cond, Result, Info);
4099 }
4100 
4101 namespace {
4102 /// A location where the result (returned value) of evaluating a
4103 /// statement should be stored.
4104 struct StmtResult {
4105  /// The APValue that should be filled in with the returned value.
4106  APValue &Value;
4107  /// The location containing the result, if any (used to support RVO).
4108  const LValue *Slot;
4109 };
4110 
4111 struct TempVersionRAII {
4112  CallStackFrame &Frame;
4113 
4114  TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4115  Frame.pushTempVersion();
4116  }
4117 
4118  ~TempVersionRAII() {
4119  Frame.popTempVersion();
4120  }
4121 };
4122 
4123 }
4124 
4125 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4126  const Stmt *S,
4127  const SwitchCase *SC = nullptr);
4128 
4129 /// Evaluate the body of a loop, and translate the result as appropriate.
4130 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4131  const Stmt *Body,
4132  const SwitchCase *Case = nullptr) {
4133  BlockScopeRAII Scope(Info);
4134  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4135  case ESR_Break:
4136  return ESR_Succeeded;
4137  case ESR_Succeeded:
4138  case ESR_Continue:
4139  return ESR_Continue;
4140  case ESR_Failed:
4141  case ESR_Returned:
4142  case ESR_CaseNotFound:
4143  return ESR;
4144  }
4145  llvm_unreachable("Invalid EvalStmtResult!");
4146 }
4147 
4148 /// Evaluate a switch statement.
4149 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4150  const SwitchStmt *SS) {
4151  BlockScopeRAII Scope(Info);
4152 
4153  // Evaluate the switch condition.
4154  APSInt Value;
4155  {
4156  FullExpressionRAII Scope(Info);
4157  if (const Stmt *Init = SS->getInit()) {
4158  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4159  if (ESR != ESR_Succeeded)
4160  return ESR;
4161  }
4162  if (SS->getConditionVariable() &&
4163  !EvaluateDecl(Info, SS->getConditionVariable()))
4164  return ESR_Failed;
4165  if (!EvaluateInteger(SS->getCond(), Value, Info))
4166  return ESR_Failed;
4167  }
4168 
4169  // Find the switch case corresponding to the value of the condition.
4170  // FIXME: Cache this lookup.
4171  const SwitchCase *Found = nullptr;
4172  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4173  SC = SC->getNextSwitchCase()) {
4174  if (isa<DefaultStmt>(SC)) {
4175  Found = SC;
4176  continue;
4177  }
4178 
4179  const CaseStmt *CS = cast<CaseStmt>(SC);
4180  APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4181  APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4182  : LHS;
4183  if (LHS <= Value && Value <= RHS) {
4184  Found = SC;
4185  break;
4186  }
4187  }
4188 
4189  if (!Found)
4190  return ESR_Succeeded;
4191 
4192  // Search the switch body for the switch case and evaluate it from there.
4193  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4194  case ESR_Break:
4195  return ESR_Succeeded;
4196  case ESR_Succeeded:
4197  case ESR_Continue:
4198  case ESR_Failed:
4199  case ESR_Returned:
4200  return ESR;
4201  case ESR_CaseNotFound:
4202  // This can only happen if the switch case is nested within a statement
4203  // expression. We have no intention of supporting that.
4204  Info.FFDiag(Found->getBeginLoc(),
4205  diag::note_constexpr_stmt_expr_unsupported);
4206  return ESR_Failed;
4207  }
4208  llvm_unreachable("Invalid EvalStmtResult!");
4209 }
4210 
4211 // Evaluate a statement.
4212 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4213  const Stmt *S, const SwitchCase *Case) {
4214  if (!Info.nextStep(S))
4215  return ESR_Failed;
4216 
4217  // If we're hunting down a 'case' or 'default' label, recurse through
4218  // substatements until we hit the label.
4219  if (Case) {
4220  // FIXME: We don't start the lifetime of objects whose initialization we
4221  // jump over. However, such objects must be of class type with a trivial
4222  // default constructor that initialize all subobjects, so must be empty,
4223  // so this almost never matters.
4224  switch (S->getStmtClass()) {
4225  case Stmt::CompoundStmtClass:
4226  // FIXME: Precompute which substatement of a compound statement we
4227  // would jump to, and go straight there rather than performing a
4228  // linear scan each time.
4229  case Stmt::LabelStmtClass:
4230  case Stmt::AttributedStmtClass:
4231  case Stmt::DoStmtClass:
4232  break;
4233 
4234  case Stmt::CaseStmtClass:
4235  case Stmt::DefaultStmtClass:
4236  if (Case == S)
4237  Case = nullptr;
4238  break;
4239 
4240  case Stmt::IfStmtClass: {
4241  // FIXME: Precompute which side of an 'if' we would jump to, and go
4242  // straight there rather than scanning both sides.
4243  const IfStmt *IS = cast<IfStmt>(S);
4244 
4245  // Wrap the evaluation in a block scope, in case it's a DeclStmt
4246  // preceded by our switch label.
4247  BlockScopeRAII Scope(Info);
4248 
4249  EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4250  if (ESR != ESR_CaseNotFound || !IS->getElse())
4251  return ESR;
4252  return EvaluateStmt(Result, Info, IS->getElse(), Case);
4253  }
4254 
4255  case Stmt::WhileStmtClass: {
4256  EvalStmtResult ESR =
4257  EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4258  if (ESR != ESR_Continue)
4259  return ESR;
4260  break;
4261  }
4262 
4263  case Stmt::ForStmtClass: {
4264  const ForStmt *FS = cast<ForStmt>(S);
4265  EvalStmtResult ESR =
4266  EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4267  if (ESR != ESR_Continue)
4268  return ESR;
4269  if (FS->getInc()) {
4270  FullExpressionRAII IncScope(Info);
4271  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4272  return ESR_Failed;
4273  }
4274  break;
4275  }
4276 
4277  case Stmt::DeclStmtClass:
4278  // FIXME: If the variable has initialization that can't be jumped over,
4279  // bail out of any immediately-surrounding compound-statement too.
4280  default:
4281  return ESR_CaseNotFound;
4282  }
4283  }
4284 
4285  switch (S->getStmtClass()) {
4286  default:
4287  if (const Expr *E = dyn_cast<Expr>(S)) {
4288  // Don't bother evaluating beyond an expression-statement which couldn't
4289  // be evaluated.
4290  FullExpressionRAII Scope(Info);
4291  if (!EvaluateIgnoredValue(Info, E))
4292  return ESR_Failed;
4293  return ESR_Succeeded;
4294  }
4295 
4296  Info.FFDiag(S->getBeginLoc());
4297  return ESR_Failed;
4298 
4299  case Stmt::NullStmtClass:
4300  return ESR_Succeeded;
4301 
4302  case Stmt::DeclStmtClass: {
4303  const DeclStmt *DS = cast<DeclStmt>(S);
4304  for (const auto *DclIt : DS->decls()) {
4305  // Each declaration initialization is its own full-expression.
4306  // FIXME: This isn't quite right; if we're performing aggregate
4307  // initialization, each braced subexpression is its own full-expression.
4308  FullExpressionRAII Scope(Info);
4309  if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4310  return ESR_Failed;
4311  }
4312  return ESR_Succeeded;
4313  }
4314 
4315  case Stmt::ReturnStmtClass: {
4316  const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4317  FullExpressionRAII Scope(Info);
4318  if (RetExpr &&
4319  !(Result.Slot
4320  ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4321  : Evaluate(Result.Value, Info, RetExpr)))
4322  return ESR_Failed;
4323  return ESR_Returned;
4324  }
4325 
4326  case Stmt::CompoundStmtClass: {
4327  BlockScopeRAII Scope(Info);
4328 
4329  const CompoundStmt *CS = cast<CompoundStmt>(S);
4330  for (const auto *BI : CS->body()) {
4331  EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4332  if (ESR == ESR_Succeeded)
4333  Case = nullptr;
4334  else if (ESR != ESR_CaseNotFound)
4335  return ESR;
4336  }
4337  return Case ? ESR_CaseNotFound : ESR_Succeeded;
4338  }
4339 
4340  case Stmt::IfStmtClass: {
4341  const IfStmt *IS = cast<IfStmt>(S);
4342 
4343  // Evaluate the condition, as either a var decl or as an expression.
4344  BlockScopeRAII Scope(Info);
4345  if (const Stmt *Init = IS->getInit()) {
4346  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4347  if (ESR != ESR_Succeeded)
4348  return ESR;
4349  }
4350  bool Cond;
4351  if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4352  return ESR_Failed;
4353 
4354  if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4355  EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4356  if (ESR != ESR_Succeeded)
4357  return ESR;
4358  }
4359  return ESR_Succeeded;
4360  }
4361 
4362  case Stmt::WhileStmtClass: {
4363  const WhileStmt *WS = cast<WhileStmt>(S);
4364  while (true) {
4365  BlockScopeRAII Scope(Info);
4366  bool Continue;
4367  if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4368  Continue))
4369  return ESR_Failed;
4370  if (!Continue)
4371  break;
4372 
4373  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4374  if (ESR != ESR_Continue)
4375  return ESR;
4376  }
4377  return ESR_Succeeded;
4378  }
4379 
4380  case Stmt::DoStmtClass: {
4381  const DoStmt *DS = cast<DoStmt>(S);
4382  bool Continue;
4383  do {
4384  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4385  if (ESR != ESR_Continue)
4386  return ESR;
4387  Case = nullptr;
4388 
4389  FullExpressionRAII CondScope(Info);
4390  if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4391  return ESR_Failed;
4392  } while (Continue);
4393  return ESR_Succeeded;
4394  }
4395 
4396  case Stmt::ForStmtClass: {
4397  const ForStmt *FS = cast<ForStmt>(S);
4398  BlockScopeRAII Scope(Info);
4399  if (FS->getInit()) {
4400  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4401  if (ESR != ESR_Succeeded)
4402  return ESR;
4403  }
4404  while (true) {
4405  BlockScopeRAII Scope(Info);
4406  bool Continue = true;
4407  if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4408  FS->getCond(), Continue))
4409  return ESR_Failed;
4410  if (!Continue)
4411  break;
4412 
4413  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4414  if (ESR != ESR_Continue)
4415  return ESR;
4416 
4417  if (FS->getInc()) {
4418  FullExpressionRAII IncScope(Info);
4419  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4420  return ESR_Failed;
4421  }
4422  }
4423  return ESR_Succeeded;
4424  }
4425 
4426  case Stmt::CXXForRangeStmtClass: {
4427  const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4428  BlockScopeRAII Scope(Info);
4429 
4430  // Evaluate the init-statement if present.
4431  if (FS->getInit()) {
4432  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4433  if (ESR != ESR_Succeeded)
4434  return ESR;
4435  }
4436 
4437  // Initialize the __range variable.
4438  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4439  if (ESR != ESR_Succeeded)
4440  return ESR;
4441 
4442  // Create the __begin and __end iterators.
4443  ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4444  if (ESR != ESR_Succeeded)
4445  return ESR;
4446  ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4447  if (ESR != ESR_Succeeded)
4448  return ESR;
4449 
4450  while (true) {
4451  // Condition: __begin != __end.
4452  {
4453  bool Continue = true;
4454  FullExpressionRAII CondExpr(Info);
4455  if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4456  return ESR_Failed;
4457  if (!Continue)
4458  break;
4459  }
4460 
4461  // User's variable declaration, initialized by *__begin.
4462  BlockScopeRAII InnerScope(Info);
4463  ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4464  if (ESR != ESR_Succeeded)
4465  return ESR;
4466 
4467  // Loop body.
4468  ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4469  if (ESR != ESR_Continue)
4470  return ESR;
4471 
4472  // Increment: ++__begin
4473  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4474  return ESR_Failed;
4475  }
4476 
4477  return ESR_Succeeded;
4478  }
4479 
4480  case Stmt::SwitchStmtClass:
4481  return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4482 
4483  case Stmt::ContinueStmtClass:
4484  return ESR_Continue;
4485 
4486  case Stmt::BreakStmtClass:
4487  return ESR_Break;
4488 
4489  case Stmt::LabelStmtClass:
4490  return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4491 
4492  case Stmt::AttributedStmtClass:
4493  // As a general principle, C++11 attributes can be ignored without
4494  // any semantic impact.
4495  return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4496  Case);
4497 
4498  case Stmt::CaseStmtClass:
4499  case Stmt::DefaultStmtClass:
4500  return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4501  case Stmt::CXXTryStmtClass:
4502  // Evaluate try blocks by evaluating all sub statements.
4503  return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4504  }
4505 }
4506 
4507 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4508 /// default constructor. If so, we'll fold it whether or not it's marked as
4509 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4510 /// so we need special handling.
4511 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4512  const CXXConstructorDecl *CD,
4513  bool IsValueInitialization) {
4514  if (!CD->isTrivial() || !CD->isDefaultConstructor())
4515  return false;
4516 
4517  // Value-initialization does not call a trivial default constructor, so such a
4518  // call is a core constant expression whether or not the constructor is
4519  // constexpr.
4520  if (!CD->isConstexpr() && !IsValueInitialization) {
4521  if (Info.getLangOpts().CPlusPlus11) {
4522  // FIXME: If DiagDecl is an implicitly-declared special member function,
4523  // we should be much more explicit about why it's not constexpr.
4524  Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4525  << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4526  Info.Note(CD->getLocation(), diag::note_declared_at);
4527  } else {
4528  Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4529  }
4530  }
4531  return true;
4532 }
4533 
4534 /// CheckConstexprFunction - Check that a function can be called in a constant
4535 /// expression.
4536 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4537  const FunctionDecl *Declaration,
4538  const FunctionDecl *Definition,
4539  const Stmt *Body) {
4540  // Potential constant expressions can contain calls to declared, but not yet
4541  // defined, constexpr functions.
4542  if (Info.checkingPotentialConstantExpression() && !Definition &&
4543  Declaration->isConstexpr())
4544  return false;
4545 
4546  // Bail out if the function declaration itself is invalid. We will
4547  // have produced a relevant diagnostic while parsing it, so just
4548  // note the problematic sub-expression.
4549  if (Declaration->isInvalidDecl()) {
4550  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4551  return false;
4552  }
4553 
4554  // DR1872: An instantiated virtual constexpr function can't be called in a
4555  // constant expression (prior to C++20). We can still constant-fold such a
4556  // call.
4557  if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4558  cast<CXXMethodDecl>(Declaration)->isVirtual())
4559  Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4560 
4561  if (Definition && Definition->isInvalidDecl()) {
4562  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4563  return false;
4564  }
4565 
4566  // Can we evaluate this function call?
4567  if (Definition && Definition->isConstexpr() && Body)
4568  return true;
4569 
4570  if (Info.getLangOpts().CPlusPlus11) {
4571  const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4572 
4573  // If this function is not constexpr because it is an inherited
4574  // non-constexpr constructor, diagnose that directly.
4575  auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4576  if (CD && CD->isInheritingConstructor()) {
4577  auto *Inherited = CD->getInheritedConstructor().getConstructor();
4578  if (!Inherited->isConstexpr())
4579  DiagDecl = CD = Inherited;
4580  }
4581 
4582  // FIXME: If DiagDecl is an implicitly-declared special member function
4583  // or an inheriting constructor, we should be much more explicit about why
4584  // it's not constexpr.
4585  if (CD && CD->isInheritingConstructor())
4586  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4587  << CD->getInheritedConstructor().getConstructor()->getParent();
4588  else
4589  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4590  << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4591  Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4592  } else {
4593  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4594  }
4595  return false;
4596 }
4597 
4598 namespace {
4599 struct CheckDynamicTypeHandler {
4601  typedef bool result_type;
4602  bool failed() { return false; }
4603  bool found(APValue &Subobj, QualType SubobjType) { return true; }
4604  bool found(APSInt &Value, QualType SubobjType) { return true; }
4605  bool found(APFloat &Value, QualType SubobjType) { return true; }
4606 };
4607 } // end anonymous namespace
4608 
4609 /// Check that we can access the notional vptr of an object / determine its
4610 /// dynamic type.
4611 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4612  AccessKinds AK, bool Polymorphic) {
4613  if (This.Designator.Invalid)
4614  return false;
4615 
4616  CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4617 
4618  if (!Obj)
4619  return false;
4620 
4621  if (!Obj.Value) {
4622  // The object is not usable in constant expressions, so we can't inspect
4623  // its value to see if it's in-lifetime or what the active union members
4624  // are. We can still check for a one-past-the-end lvalue.
4625  if (This.Designator.isOnePastTheEnd() ||
4626  This.Designator.isMostDerivedAnUnsizedArray()) {
4627  Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4628  ? diag::note_constexpr_access_past_end
4629  : diag::note_constexpr_access_unsized_array)
4630  << AK;
4631  return false;
4632  } else if (Polymorphic) {
4633  // Conservatively refuse to perform a polymorphic operation if we would
4634  // not be able to read a notional 'vptr' value.
4635  APValue Val;
4636  This.moveInto(Val);
4637  QualType StarThisType =
4638  Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4639  Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4640  << AK << Val.getAsString(Info.Ctx, StarThisType);
4641  return false;
4642  }
4643  return true;
4644  }
4645 
4646  CheckDynamicTypeHandler Handler{AK};
4647  return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4648 }
4649 
4650 /// Check that the pointee of the 'this' pointer in a member function call is
4651 /// either within its lifetime or in its period of construction or destruction.
4652 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4653  const LValue &This) {
4654  return checkDynamicType(Info, E, This, AK_MemberCall, false);
4655 }
4656 
4657 struct DynamicType {
4658  /// The dynamic class type of the object.
4660  /// The corresponding path length in the lvalue.
4661  unsigned PathLength;
4662 };
4663 
4664 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4665  unsigned PathLength) {
4666  assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4667  Designator.Entries.size() && "invalid path length");
4668  return (PathLength == Designator.MostDerivedPathLength)
4669  ? Designator.MostDerivedType->getAsCXXRecordDecl()
4670  : getAsBaseClass(Designator.Entries[PathLength - 1]);
4671 }
4672 
4673 /// Determine the dynamic type of an object.
4674 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4675  LValue &This, AccessKinds AK) {
4676  // If we don't have an lvalue denoting an object of class type, there is no
4677  // meaningful dynamic type. (We consider objects of non-class type to have no
4678  // dynamic type.)
4679  if (!checkDynamicType(Info, E, This, AK, true))
4680  return None;
4681 
4682  // Refuse to compute a dynamic type in the presence of virtual bases. This
4683  // shouldn't happen other than in constant-folding situations, since literal
4684  // types can't have virtual bases.
4685  //
4686  // Note that consumers of DynamicType assume that the type has no virtual
4687  // bases, and will need modifications if this restriction is relaxed.
4688  const CXXRecordDecl *Class =
4689  This.Designator.MostDerivedType->getAsCXXRecordDecl();
4690  if (!Class || Class->getNumVBases()) {
4691  Info.FFDiag(E);
4692  return None;
4693  }
4694 
4695  // FIXME: For very deep class hierarchies, it might be beneficial to use a
4696  // binary search here instead. But the overwhelmingly common case is that
4697  // we're not in the middle of a constructor, so it probably doesn't matter
4698  // in practice.
4699  ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4700  for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4701  PathLength <= Path.size(); ++PathLength) {
4702  switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4703  Path.slice(0, PathLength))) {
4704  case ConstructionPhase::Bases:
4705  // We're constructing a base class. This is not the dynamic type.
4706  break;
4707 
4709  case ConstructionPhase::AfterBases:
4710  // We've finished constructing the base classes, so this is the dynamic
4711  // type.
4712  return DynamicType{getBaseClassType(This.Designator, PathLength),
4713  PathLength};
4714  }
4715  }
4716 
4717  // CWG issue 1517: we're constructing a base class of the object described by
4718  // 'This', so that object has not yet begun its period of construction and
4719  // any polymorphic operation on it results in undefined behavior.
4720  Info.FFDiag(E);
4721  return None;
4722 }
4723 
4724 /// Perform virtual dispatch.
4726  EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4727  llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4728  Optional<DynamicType> DynType =
4729  ComputeDynamicType(Info, E, This, AK_MemberCall);
4730  if (!DynType)
4731  return nullptr;
4732 
4733  // Find the final overrider. It must be declared in one of the classes on the
4734  // path from the dynamic type to the static type.
4735  // FIXME: If we ever allow literal types to have virtual base classes, that
4736  // won't be true.
4737  const CXXMethodDecl *Callee = Found;
4738  unsigned PathLength = DynType->PathLength;
4739  for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4740  const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4741  const CXXMethodDecl *Overrider =
4742  Found->getCorrespondingMethodDeclaredInClass(Class, false);
4743  if (Overrider) {
4744  Callee = Overrider;
4745  break;
4746  }
4747  }
4748 
4749  // C++2a [class.abstract]p6:
4750  // the effect of making a virtual call to a pure virtual function [...] is
4751  // undefined
4752  if (Callee->isPure()) {
4753  Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4754  Info.Note(Callee->getLocation(), diag::note_declared_at);
4755  return nullptr;
4756  }
4757 
4758  // If necessary, walk the rest of the path to determine the sequence of
4759  // covariant adjustment steps to apply.
4760  if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4761  Found->getReturnType())) {
4762  CovariantAdjustmentPath.push_back(Callee->getReturnType());
4763  for (unsigned CovariantPathLength = PathLength + 1;
4764  CovariantPathLength != This.Designator.Entries.size();
4765  ++CovariantPathLength) {
4766  const CXXRecordDecl *NextClass =
4767  getBaseClassType(This.Designator, CovariantPathLength);
4768  const CXXMethodDecl *Next =
4769  Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4770  if (Next && !Info.Ctx.hasSameUnqualifiedType(
4771  Next->getReturnType(), CovariantAdjustmentPath.back()))
4772  CovariantAdjustmentPath.push_back(Next->getReturnType());
4773  }
4774  if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4775  CovariantAdjustmentPath.back()))
4776  CovariantAdjustmentPath.push_back(Found->getReturnType());
4777  }
4778 
4779  // Perform 'this' adjustment.
4780  if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4781  return nullptr;
4782 
4783  return Callee;
4784 }
4785 
4786 /// Perform the adjustment from a value returned by a virtual function to
4787 /// a value of the statically expected type, which may be a pointer or
4788 /// reference to a base class of the returned type.
4789 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4790  APValue &Result,
4791  ArrayRef<QualType> Path) {
4792  assert(Result.isLValue() &&
4793  "unexpected kind of APValue for covariant return");
4794  if (Result.isNullPointer())
4795  return true;
4796 
4797  LValue LVal;
4798  LVal.setFrom(Info.Ctx, Result);
4799 
4800  const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4801  for (unsigned I = 1; I != Path.size(); ++I) {
4802  const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4803  assert(OldClass && NewClass && "unexpected kind of covariant return");
4804  if (OldClass != NewClass &&
4805  !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4806  return false;
4807  OldClass = NewClass;
4808  }
4809 
4810  LVal.moveInto(Result);
4811  return true;
4812 }
4813 
4814 /// Determine whether \p Base, which is known to be a direct base class of
4815 /// \p Derived, is a public base class.
4816 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4817  const CXXRecordDecl *Base) {
4818  for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4819  auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4820  if (BaseClass && declaresSameEntity(BaseClass, Base))
4821  return BaseSpec.getAccessSpecifier() == AS_public;
4822  }
4823  llvm_unreachable("Base is not a direct base of Derived");
4824 }
4825 
4826 /// Apply the given dynamic cast operation on the provided lvalue.
4827 ///
4828 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4829 /// to find a suitable target subobject.
4830 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4831  LValue &Ptr) {
4832  // We can't do anything with a non-symbolic pointer value.
4833  SubobjectDesignator &D = Ptr.Designator;
4834  if (D.Invalid)
4835  return false;
4836 
4837  // C++ [expr.dynamic.cast]p6:
4838  // If v is a null pointer value, the result is a null pointer value.
4839  if (Ptr.isNullPointer() && !E->isGLValue())
4840  return true;
4841 
4842  // For all the other cases, we need the pointer to point to an object within
4843  // its lifetime / period of construction / destruction, and we need to know
4844  // its dynamic type.
4845  Optional<DynamicType> DynType =
4846  ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4847  if (!DynType)
4848  return false;
4849 
4850  // C++ [expr.dynamic.cast]p7:
4851  // If T is "pointer to cv void", then the result is a pointer to the most
4852  // derived object
4853  if (E->getType()->isVoidPointerType())
4854  return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4855 
4857  assert(C && "dynamic_cast target is not void pointer nor class");
4858  CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4859 
4860  auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4861  // C++ [expr.dynamic.cast]p9:
4862  if (!E->isGLValue()) {
4863  // The value of a failed cast to pointer type is the null pointer value
4864  // of the required result type.
4865  auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4866  Ptr.setNull(E->getType(), TargetVal);
4867  return true;
4868  }
4869 
4870  // A failed cast to reference type throws [...] std::bad_cast.
4871  unsigned DiagKind;
4872  if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4873  DynType->Type->isDerivedFrom(C)))
4874  DiagKind = 0;
4875  else if (!Paths || Paths->begin() == Paths->end())
4876  DiagKind = 1;
4877  else if (Paths->isAmbiguous(CQT))
4878  DiagKind = 2;
4879  else {
4880  assert(Paths->front().Access != AS_public && "why did the cast fail?");
4881  DiagKind = 3;
4882  }
4883  Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4884  << DiagKind << Ptr.Designator.getType(Info.Ctx)
4885  << Info.Ctx.getRecordType(DynType->Type)
4886  << E->getType().getUnqualifiedType();
4887  return false;
4888  };
4889 
4890  // Runtime check, phase 1:
4891  // Walk from the base subobject towards the derived object looking for the
4892  // target type.
4893  for (int PathLength = Ptr.Designator.Entries.size();
4894  PathLength >= (int)DynType->PathLength; --PathLength) {
4895  const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4896  if (declaresSameEntity(Class, C))
4897  return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4898  // We can only walk across public inheritance edges.
4899  if (PathLength > (int)DynType->PathLength &&
4900  !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4901  Class))
4902  return RuntimeCheckFailed(nullptr);
4903  }
4904 
4905  // Runtime check, phase 2:
4906  // Search the dynamic type for an unambiguous public base of type C.
4907  CXXBasePaths Paths(/*FindAmbiguities=*/true,
4908  /*RecordPaths=*/true, /*DetectVirtual=*/false);
4909  if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4910  Paths.front().Access == AS_public) {
4911  // Downcast to the dynamic type...
4912  if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4913  return false;
4914  // ... then upcast to the chosen base class subobject.
4915  for (CXXBasePathElement &Elem : Paths.front())
4916  if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4917  return false;
4918  return true;
4919  }
4920 
4921  // Otherwise, the runtime check fails.
4922  return RuntimeCheckFailed(&Paths);
4923 }
4924 
4925 namespace {
4926 struct StartLifetimeOfUnionMemberHandler {
4927  const FieldDecl *Field;
4928 
4929  static const AccessKinds AccessKind = AK_Assign;
4930 
4931  APValue getDefaultInitValue(QualType SubobjType) {
4932  if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4933  if (RD->isUnion())
4934  return APValue((const FieldDecl*)nullptr);
4935 
4936  APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4937  std::distance(RD->field_begin(), RD->field_end()));
4938 
4939  unsigned Index = 0;
4940  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4941  End = RD->bases_end(); I != End; ++I, ++Index)
4942  Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4943 
4944  for (const auto *I : RD->fields()) {
4945  if (I->isUnnamedBitfield())
4946  continue;
4947  Struct.getStructField(I->getFieldIndex()) =
4948  getDefaultInitValue(I->getType());
4949  }
4950  return Struct;
4951  }
4952 
4953  if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4954  SubobjType->getAsArrayTypeUnsafe())) {
4955  APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4956  if (Array.hasArrayFiller())
4957  Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4958  return Array;
4959  }
4960 
4961  return APValue::IndeterminateValue();
4962  }
4963 
4964  typedef bool result_type;
4965  bool failed() { return false; }
4966  bool found(APValue &Subobj, QualType SubobjType) {
4967  // We are supposed to perform no initialization but begin the lifetime of
4968  // the object. We interpret that as meaning to do what default
4969  // initialization of the object would do if all constructors involved were
4970  // trivial:
4971  // * All base, non-variant member, and array element subobjects' lifetimes
4972  // begin
4973  // * No variant members' lifetimes begin
4974  // * All scalar subobjects whose lifetimes begin have indeterminate values
4975  assert(SubobjType->isUnionType());
4976  if (!declaresSameEntity(Subobj.getUnionField(), Field))
4977  Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4978  return true;
4979  }
4980  bool found(APSInt &Value, QualType SubobjType) {
4981  llvm_unreachable("wrong value kind for union object");
4982  }
4983  bool found(APFloat &Value, QualType SubobjType) {
4984  llvm_unreachable("wrong value kind for union object");
4985  }
4986 };
4987 } // end anonymous namespace
4988 
4990 
4991 /// Handle a builtin simple-assignment or a call to a trivial assignment
4992 /// operator whose left-hand side might involve a union member access. If it
4993 /// does, implicitly start the lifetime of any accessed union elements per
4994 /// C++20 [class.union]5.
4995 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4996  const LValue &LHS) {
4997  if (LHS.InvalidBase || LHS.Designator.Invalid)
4998  return false;
4999 
5001  // C++ [class.union]p5:
5002  // define the set S(E) of subexpressions of E as follows:
5003  unsigned PathLength = LHS.Designator.Entries.size();
5004  for (const Expr *E = LHSExpr; E != nullptr;) {
5005  // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5006  if (auto *ME = dyn_cast<MemberExpr>(E)) {
5007  auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5008  if (!FD)
5009  break;
5010 
5011  // ... and also contains A.B if B names a union member
5012  if (FD->getParent()->isUnion())
5013  UnionPathLengths.push_back({PathLength - 1, FD});
5014 
5015  E = ME->getBase();
5016  --PathLength;
5017  assert(declaresSameEntity(FD,
5018  LHS.Designator.Entries[PathLength]
5019  .getAsBaseOrMember().getPointer()));
5020 
5021  // -- If E is of the form A[B] and is interpreted as a built-in array
5022  // subscripting operator, S(E) is [S(the array operand, if any)].
5023  } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5024  // Step over an ArrayToPointerDecay implicit cast.
5025  auto *Base = ASE->getBase()->IgnoreImplicit();
5026  if (!Base->getType()->isArrayType())
5027  break;
5028 
5029  E = Base;
5030  --PathLength;
5031 
5032  } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5033  // Step over a derived-to-base conversion.
5034  E = ICE->getSubExpr();
5035  if (ICE->getCastKind() == CK_NoOp)
5036  continue;
5037  if (ICE->getCastKind() != CK_DerivedToBase &&
5038  ICE->getCastKind() != CK_UncheckedDerivedToBase)
5039  break;
5040  // Walk path backwards as we walk up from the base to the derived class.
5041  for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5042  --PathLength;
5043  (void)Elt;
5044  assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5045  LHS.Designator.Entries[PathLength]
5046  .getAsBaseOrMember().getPointer()));
5047  }
5048 
5049  // -- Otherwise, S(E) is empty.
5050  } else {
5051  break;
5052  }
5053  }
5054 
5055  // Common case: no unions' lifetimes are started.
5056  if (UnionPathLengths.empty())
5057  return true;
5058 
5059  // if modification of X [would access an inactive union member], an object
5060  // of the type of X is implicitly created
5061  CompleteObject Obj =
5062  findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5063  if (!Obj)
5064  return false;
5065  for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5066  llvm::reverse(UnionPathLengths)) {
5067  // Form a designator for the union object.
5068  SubobjectDesignator D = LHS.Designator;
5069  D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5070 
5071  StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5072  if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5073  return false;
5074  }
5075 
5076  return true;
5077 }
5078 
5079 /// Determine if a class has any fields that might need to be copied by a
5080 /// trivial copy or move operation.
5081 static bool hasFields(const CXXRecordDecl *RD) {
5082  if (!RD || RD->isEmpty())
5083  return false;
5084  for (auto *FD : RD->fields()) {
5085  if (FD->isUnnamedBitfield())
5086  continue;
5087  return true;
5088  }
5089  for (auto &Base : RD->bases())
5090  if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5091  return true;
5092  return false;
5093 }
5094 
5095 namespace {
5096 typedef SmallVector<APValue, 8> ArgVector;
5097 }
5098 
5099 /// EvaluateArgs - Evaluate the arguments to a function call.
5100 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5101  EvalInfo &Info, const FunctionDecl *Callee) {
5102  bool Success = true;
5103  llvm::SmallBitVector ForbiddenNullArgs;
5104  if (Callee->hasAttr<NonNullAttr>()) {
5105  ForbiddenNullArgs.resize(Args.size());
5106  for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5107  if (!Attr->args_size()) {
5108  ForbiddenNullArgs.set();
5109  break;
5110  } else
5111  for (auto Idx : Attr->args()) {
5112  unsigned ASTIdx = Idx.getASTIndex();
5113  if (ASTIdx >= Args.size())
5114  continue;
5115  ForbiddenNullArgs[ASTIdx] = 1;
5116  }
5117  }
5118  }
5119  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5120  I != E; ++I) {
5121  if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5122  // If we're checking for a potential constant expression, evaluate all
5123  // initializers even if some of them fail.
5124  if (!Info.noteFailure())
5125  return false;
5126  Success = false;
5127  } else if (!ForbiddenNullArgs.empty() &&
5128  ForbiddenNullArgs[I - Args.begin()] &&
5129  ArgValues[I - Args.begin()].isNullPointer()) {
5130  Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5131  if (!Info.noteFailure())
5132  return false;
5133  Success = false;
5134  }
5135  }
5136  return Success;
5137 }
5138 
5139 /// Evaluate a function call.
5141  const FunctionDecl *Callee, const LValue *This,
5142  ArrayRef<const Expr*> Args, const Stmt *Body,
5143  EvalInfo &Info, APValue &Result,
5144  const LValue *ResultSlot) {
5145  ArgVector ArgValues(Args.size());
5146  if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5147  return false;
5148 
5149  if (!Info.CheckCallLimit(CallLoc))
5150  return false;
5151 
5152  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5153 
5154  // For a trivial copy or move assignment, perform an APValue copy. This is
5155  // essential for unions, where the operations performed by the assignment
5156  // operator cannot be represented as statements.
5157  //
5158  // Skip this for non-union classes with no fields; in that case, the defaulted
5159  // copy/move does not actually read the object.
5160  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5161  if (MD && MD->isDefaulted() &&
5162  (MD->getParent()->isUnion() ||
5163  (MD->isTrivial() && hasFields(MD->getParent())))) {
5164  assert(This &&
5165  (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5166  LValue RHS;
5167  RHS.setFrom(Info.Ctx, ArgValues[0]);
5168  APValue RHSValue;
5169  if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5170  RHS, RHSValue))
5171  return false;
5172  if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5173  !HandleUnionActiveMemberChange(Info, Args[0], *This))
5174  return false;
5175  if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5176  RHSValue))
5177  return false;
5178  This->moveInto(Result);
5179  return true;
5180  } else if (MD && isLambdaCallOperator(MD)) {
5181  // We're in a lambda; determine the lambda capture field maps unless we're
5182  // just constexpr checking a lambda's call operator. constexpr checking is
5183  // done before the captures have been added to the closure object (unless
5184  // we're inferring constexpr-ness), so we don't have access to them in this
5185  // case. But since we don't need the captures to constexpr check, we can
5186  // just ignore them.
5187  if (!Info.checkingPotentialConstantExpression())
5188  MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5189  Frame.LambdaThisCaptureField);
5190  }
5191 
5192  StmtResult Ret = {Result, ResultSlot};
5193  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5194  if (ESR == ESR_Succeeded) {
5195  if (Callee->getReturnType()->isVoidType())
5196  return true;
5197  Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5198  }
5199  return ESR == ESR_Returned;
5200 }
5201 
5202 /// Evaluate a constructor call.
5203 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5204  APValue *ArgValues,
5205  const CXXConstructorDecl *Definition,
5206  EvalInfo &Info, APValue &Result) {
5207  SourceLocation CallLoc = E->getExprLoc();
5208  if (!Info.CheckCallLimit(CallLoc))
5209  return false;
5210 
5211  const CXXRecordDecl *RD = Definition->getParent();
5212  if (RD->getNumVBases()) {
5213  Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5214  return false;
5215  }
5216 
5217  EvalInfo::EvaluatingConstructorRAII EvalObj(
5218  Info,
5219  ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5220  RD->getNumBases());
5221  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5222 
5223  // FIXME: Creating an APValue just to hold a nonexistent return value is
5224  // wasteful.
5225  APValue RetVal;
5226  StmtResult Ret = {RetVal, nullptr};
5227 
5228  // If it's a delegating constructor, delegate.
5229  if (Definition->isDelegatingConstructor()) {
5231  {
5232  FullExpressionRAII InitScope(Info);
5233  if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5234  return false;
5235  }
5236  return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5237  }
5238 
5239  // For a trivial copy or move constructor, perform an APValue copy. This is
5240  // essential for unions (or classes with anonymous union members), where the
5241  // operations performed by the constructor cannot be represented by
5242  // ctor-initializers.
5243  //
5244  // Skip this for empty non-union classes; we should not perform an
5245  // lvalue-to-rvalue conversion on them because their copy constructor does not
5246  // actually read them.
5247  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5248  (Definition->getParent()->isUnion() ||
5249  (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5250  LValue RHS;
5251  RHS.setFrom(Info.Ctx, ArgValues[0]);
5253  Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5254  RHS, Result);
5255  }
5256 
5257  // Reserve space for the struct members.
5258  if (!RD->isUnion() && !Result.hasValue())
5259  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5260  std::distance(RD->field_begin(), RD->field_end()));
5261 
5262  if (RD->isInvalidDecl()) return false;
5263  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5264 
5265  // A scope for temporaries lifetime-extended by reference members.
5266  BlockScopeRAII LifetimeExtendedScope(Info);
5267 
5268  bool Success = true;
5269  unsigned BasesSeen = 0;
5270 #ifndef NDEBUG
5272 #endif
5273  for (const auto *I : Definition->inits()) {
5274  LValue Subobject = This;
5275  LValue SubobjectParent = This;
5276  APValue *Value = &Result;
5277 
5278  // Determine the subobject to initialize.
5279  FieldDecl *FD = nullptr;
5280  if (I->isBaseInitializer()) {
5281  QualType BaseType(I->getBaseClass(), 0);
5282 #ifndef NDEBUG
5283  // Non-virtual base classes are initialized in the order in the class
5284  // definition. We have already checked for virtual base classes.
5285  assert(!BaseIt->isVirtual() && "virtual base for literal type");
5286  assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5287  "base class initializers not in expected order");
5288  ++BaseIt;
5289 #endif
5290  if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5291  BaseType->getAsCXXRecordDecl(), &Layout))
5292  return false;
5293  Value = &Result.getStructBase(BasesSeen++);
5294  } else if ((FD = I->getMember())) {
5295  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5296  return false;
5297  if (RD->isUnion()) {
5298  Result = APValue(FD);
5299  Value = &Result.getUnionValue();
5300  } else {
5301  Value = &Result.getStructField(FD->getFieldIndex());
5302  }
5303  } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5304  // Walk the indirect field decl's chain to find the object to initialize,
5305  // and make sure we've initialized every step along it.
5306  auto IndirectFieldChain = IFD->chain();
5307  for (auto *C : IndirectFieldChain) {
5308  FD = cast<FieldDecl>(C);
5309  CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5310  // Switch the union field if it differs. This happens if we had
5311  // preceding zero-initialization, and we're now initializing a union
5312  // subobject other than the first.
5313  // FIXME: In this case, the values of the other subobjects are
5314  // specified, since zero-initialization sets all padding bits to zero.
5315  if (!Value->hasValue() ||
5316  (Value->isUnion() && Value->getUnionField() != FD)) {
5317  if (CD->isUnion())
5318  *Value = APValue(FD);
5319  else
5320  *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5321  std::distance(CD->field_begin(), CD->field_end()));
5322  }
5323  // Store Subobject as its parent before updating it for the last element
5324  // in the chain.
5325  if (C == IndirectFieldChain.back())
5326  SubobjectParent = Subobject;
5327  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5328  return false;
5329  if (CD->isUnion())
5330  Value = &Value->getUnionValue();
5331  else
5332  Value = &Value->getStructField(FD->getFieldIndex());
5333  }
5334  } else {
5335  llvm_unreachable("unknown base initializer kind");
5336  }
5337 
5338  // Need to override This for implicit field initializers as in this case
5339  // This refers to innermost anonymous struct/union containing initializer,
5340  // not to currently constructed class.
5341  const Expr *Init = I->getInit();
5342  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5343  isa<CXXDefaultInitExpr>(Init));
5344  FullExpressionRAII InitScope(Info);
5345  if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5346  (FD && FD->isBitField() &&
5347  !truncateBitfieldValue(Info, Init, *Value, FD))) {
5348  // If we're checking for a potential constant expression, evaluate all
5349  // initializers even if some of them fail.
5350  if (!Info.noteFailure())
5351  return false;
5352  Success = false;
5353  }
5354 
5355  // This is the point at which the dynamic type of the object becomes this
5356  // class type.
5357  if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5358  EvalObj.finishedConstructingBases();
5359  }
5360 
5361  return Success &&
5362  EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5363 }
5364 
5365 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5366  ArrayRef<const Expr*> Args,
5367  const CXXConstructorDecl *Definition,
5368  EvalInfo &Info, APValue &Result) {
5369  ArgVector ArgValues(Args.size());
5370  if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5371  return false;
5372 
5373  return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5374  Info, Result);
5375 }
5376 
5377 //===----------------------------------------------------------------------===//
5378 // Generic Evaluation
5379 //===----------------------------------------------------------------------===//
5380 namespace {
5381 
5382 class BitCastBuffer {
5383  // FIXME: We're going to need bit-level granularity when we support
5384  // bit-fields.
5385  // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5386  // we don't support a host or target where that is the case. Still, we should
5387  // use a more generic type in case we ever do.
5389 
5390  static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5391  "Need at least 8 bit unsigned char");
5392 
5393  bool TargetIsLittleEndian;
5394 
5395 public:
5396  BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5397  : Bytes(Width.getQuantity()),
5398  TargetIsLittleEndian(TargetIsLittleEndian) {}
5399 
5400  LLVM_NODISCARD
5401  bool readObject(CharUnits Offset, CharUnits Width,
5402  SmallVectorImpl<unsigned char> &Output) const {
5403  for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5404  // If a byte of an integer is uninitialized, then the whole integer is
5405  // uninitalized.
5406  if (!Bytes[I.getQuantity()])
5407  return false;
5408  Output.push_back(*Bytes[I.getQuantity()]);
5409  }
5410  if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5411  std::reverse(Output.begin(), Output.end());
5412  return true;
5413  }
5414 
5415  void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5416  if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5417  std::reverse(Input.begin(), Input.end());
5418 
5419  size_t Index = 0;
5420  for (unsigned char Byte : Input) {
5421  assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5422  Bytes[Offset.getQuantity() + Index] = Byte;
5423  ++Index;
5424  }
5425  }
5426 
5427  size_t size() { return Bytes.size(); }
5428 };
5429 
5430 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5431 /// target would represent the value at runtime.
5432 class APValueToBufferConverter {
5433  EvalInfo &Info;
5434  BitCastBuffer Buffer;
5435  const CastExpr *BCE;
5436 
5437  APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5438  const CastExpr *BCE)
5439  : Info(Info),
5440  Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5441  BCE(BCE) {}
5442 
5443  bool visit(const APValue &Val, QualType Ty) {
5444  return visit(Val, Ty, CharUnits::fromQuantity(0));
5445  }
5446 
5447  // Write out Val with type Ty into Buffer starting at Offset.
5448  bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5449  assert((size_t)Offset.getQuantity() <= Buffer.size());
5450 
5451  // As a special case, nullptr_t has an indeterminate value.
5452  if (Ty->isNullPtrType())
5453  return true;
5454 
5455  // Dig through Src to find the byte at SrcOffset.
5456  switch (Val.getKind()) {
5458  case APValue::None:
5459  return true;
5460 
5461  case APValue::Int:
5462  return visitInt(Val.getInt(), Ty, Offset);
5463  case APValue::Float:
5464  return visitFloat(Val.getFloat(), Ty, Offset);
5465  case APValue::Array:
5466  return visitArray(Val, Ty, Offset);
5467  case APValue::Struct:
5468  return visitRecord(Val, Ty, Offset);
5469 
5470  case APValue::ComplexInt:
5471  case APValue::ComplexFloat:
5472  case APValue::Vector:
5473  case APValue::FixedPoint:
5474  // FIXME: We should support these.
5475 
5476  case APValue::Union:
5478  case APValue::AddrLabelDiff: {
5479  Info.FFDiag(BCE->getBeginLoc(),
5480  diag::note_constexpr_bit_cast_unsupported_type)
5481  << Ty;
5482  return false;
5483  }
5484 
5485  case APValue::LValue:
5486  llvm_unreachable("LValue subobject in bit_cast?");
5487  }
5488  llvm_unreachable("Unhandled APValue::ValueKind");
5489  }
5490 
5491  bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5492  const RecordDecl *RD = Ty->getAsRecordDecl();
5493  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5494 
5495  // Visit the base classes.
5496  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5497  for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5498  const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5499  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5500 
5501  if (!visitRecord(Val.getStructBase(I), BS.getType(),
5502  Layout.getBaseClassOffset(BaseDecl) + Offset))
5503  return false;
5504  }
5505  }
5506 
5507  // Visit the fields.
5508  unsigned FieldIdx = 0;
5509  for (FieldDecl *FD : RD->fields()) {
5510  if (FD->isBitField()) {
5511  Info.FFDiag(BCE->getBeginLoc(),
5512  diag::note_constexpr_bit_cast_unsupported_bitfield);
5513  return false;
5514  }
5515 
5516  uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5517 
5518  assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5519  "only bit-fields can have sub-char alignment");
5520  CharUnits FieldOffset =
5521  Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5522  QualType FieldTy = FD->getType();
5523  if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5524  return false;
5525  ++FieldIdx;
5526  }
5527 
5528  return true;
5529  }
5530 
5531  bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5532  const auto *CAT =
5533  dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5534  if (!CAT)
5535  return false;
5536 
5537  CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5538  unsigned NumInitializedElts = Val.getArrayInitializedElts();
5539  unsigned ArraySize = Val.getArraySize();
5540  // First, initialize the initialized elements.
5541  for (unsigned I = 0; I != NumInitializedElts; ++I) {
5542  const APValue &SubObj = Val.getArrayInitializedElt(I);
5543  if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5544  return false;
5545  }
5546 
5547  // Next, initialize the rest of the array using the filler.
5548  if (Val.hasArrayFiller()) {
5549  const APValue &Filler = Val.getArrayFiller();
5550  for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5551  if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5552  return false;
5553  }
5554  }
5555 
5556  return true;
5557  }
5558 
5559  bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5560  CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5562  llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5563  Buffer.writeObject(Offset, Bytes);
5564  return true;
5565  }
5566 
5567  bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5568  APSInt AsInt(Val.bitcastToAPInt());
5569  return visitInt(AsInt, Ty, Offset);
5570  }
5571 
5572 public:
5573  static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5574  const CastExpr *BCE) {
5575  CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5576  APValueToBufferConverter Converter(Info, DstSize, BCE);
5577  if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5578  return None;
5579  return Converter.Buffer;
5580  }
5581 };
5582 
5583 /// Write an BitCastBuffer into an APValue.
5584 class BufferToAPValueConverter {
5585  EvalInfo &Info;
5586  const BitCastBuffer &Buffer;
5587  const CastExpr *BCE;
5588 
5589  BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5590  const CastExpr *BCE)
5591  : Info(Info), Buffer(Buffer), BCE(BCE) {}
5592 
5593  // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5594  // with an invalid type, so anything left is a deficiency on our part (FIXME).
5595  // Ideally this will be unreachable.
5596  llvm::NoneType unsupportedType(QualType Ty) {
5597  Info.FFDiag(BCE->getBeginLoc(),
5598  diag::note_constexpr_bit_cast_unsupported_type)
5599  << Ty;
5600  return None;
5601  }
5602 
5604  const EnumType *EnumSugar = nullptr) {
5605  if (T->isNullPtrType()) {
5606  uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5607  return APValue((Expr *)nullptr,
5608  /*Offset=*/CharUnits::fromQuantity(NullValue),
5609  APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5610  }
5611 
5612  CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5614  if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5615  // If this is std::byte or unsigned char, then its okay to store an
5616  // indeterminate value.
5617  bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5618  bool IsUChar =
5619  !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5620  T->isSpecificBuiltinType(BuiltinType::Char_U));
5621  if (!IsStdByte && !IsUChar) {
5622  QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
5623  Info.FFDiag(BCE->getExprLoc(),
5624  diag::note_constexpr_bit_cast_indet_dest)
5625  << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5626  return None;
5627  }
5628 
5629  return APValue::IndeterminateValue();
5630  }
5631 
5632  APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5633  llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5634 
5635  if (T->isIntegralOrEnumerationType()) {
5636  Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5637  return APValue(Val);
5638  }
5639 
5640  if (T->isRealFloatingType()) {
5641  const llvm::fltSemantics &Semantics =
5642  Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5643  return APValue(APFloat(Semantics, Val));
5644  }
5645 
5646  return unsupportedType(QualType(T, 0));
5647  }
5648 
5649  Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5650  const RecordDecl *RD = RTy->getAsRecordDecl();
5651  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5652 
5653  unsigned NumBases = 0;
5654  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5655  NumBases = CXXRD->getNumBases();
5656 
5657  APValue ResultVal(APValue::UninitStruct(), NumBases,
5658  std::distance(RD->field_begin(), RD->field_end()));
5659 
5660  // Visit the base classes.
5661  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5662  for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5663  const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5664  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5665  if (BaseDecl->isEmpty() ||
5666  Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5667  continue;
5668 
5669  Optional<APValue> SubObj = visitType(
5670  BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5671  if (!SubObj)
5672  return None;
5673  ResultVal.getStructBase(I) = *SubObj;
5674  }
5675  }
5676 
5677  // Visit the fields.
5678  unsigned FieldIdx = 0;
5679  for (FieldDecl *FD : RD->fields()) {
5680  // FIXME: We don't currently support bit-fields. A lot of the logic for
5681  // this is in CodeGen, so we need to factor it around.
5682  if (FD->isBitField()) {
5683  Info.FFDiag(BCE->getBeginLoc(),
5684  diag::note_constexpr_bit_cast_unsupported_bitfield);
5685  return None;
5686  }
5687 
5688  uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5689  assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5690 
5691  CharUnits FieldOffset =
5692  CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5693  Offset;
5694  QualType FieldTy = FD->getType();
5695  Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5696  if (!SubObj)
5697  return None;
5698  ResultVal.getStructField(FieldIdx) = *SubObj;
5699  ++FieldIdx;
5700  }
5701 
5702  return ResultVal;
5703  }
5704 
5705  Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5706  QualType RepresentationType = Ty->getDecl()->getIntegerType();
5707  assert(!RepresentationType.isNull() &&
5708  "enum forward decl should be caught by Sema");
5709  const BuiltinType *AsBuiltin =
5710  RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5711  assert(AsBuiltin && "non-integral enum underlying type?");
5712  // Recurse into the underlying type. Treat std::byte transparently as
5713  // unsigned char.
5714  return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5715  }
5716 
5717  Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5718  size_t Size = Ty->getSize().getLimitedValue();
5719  CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5720 
5721  APValue ArrayValue(APValue::UninitArray(), Size, Size);
5722  for (size_t I = 0; I != Size; ++I) {
5723  Optional<APValue> ElementValue =
5724  visitType(Ty->getElementType(), Offset + I * ElementWidth);
5725  if (!ElementValue)
5726  return None;
5727  ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5728  }
5729 
5730  return ArrayValue;
5731  }
5732 
5733  Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5734  return unsupportedType(QualType(Ty, 0));
5735  }
5736 
5737  Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5738  QualType Can = Ty.getCanonicalType();
5739 
5740  switch (Can->getTypeClass()) {
5741 #define TYPE(Class, Base) \
5742  case Type::Class: \
5743  return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5744 #define ABSTRACT_TYPE(Class, Base)
5745 #define NON_CANONICAL_TYPE(Class, Base) \
5746  case Type::Class: \
5747  llvm_unreachable("non-canonical type should be impossible!");
5748 #define DEPENDENT_TYPE(Class, Base) \
5749  case Type::Class: \
5750  llvm_unreachable( \
5751  "dependent types aren't supported in the constant evaluator!");
5752 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5753  case Type::Class: \
5754  llvm_unreachable("either dependent or not canonical!");
5755 #include "clang/AST/TypeNodes.def"
5756  }
5757  llvm_unreachable("Unhandled Type::TypeClass");
5758  }
5759 
5760 public:
5761  // Pull out a full value of type DstType.
5762  static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5763  const CastExpr *BCE) {
5764  BufferToAPValueConverter Converter(Info, Buffer, BCE);
5765  return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5766  }
5767 };
5768 
5769 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5770  QualType Ty, EvalInfo *Info,
5771  const ASTContext &Ctx,
5772  bool CheckingDest) {
5773  Ty = Ty.getCanonicalType();
5774 
5775  auto diag = [&](int Reason) {
5776  if (Info)
5777  Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5778  << CheckingDest << (Reason == 4) << Reason;
5779  return false;
5780  };
5781  auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5782  if (Info)
5783  Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5784  << NoteTy << Construct << Ty;
5785  return false;
5786  };
5787 
5788  if (Ty->isUnionType())
5789  return diag(0);
5790  if (Ty->isPointerType())
5791  return diag(1);
5792  if (Ty->isMemberPointerType())
5793  return diag(2);
5794  if (Ty.isVolatileQualified())
5795  return diag(3);
5796 
5797  if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5798  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5799  for (CXXBaseSpecifier &BS : CXXRD->bases())
5800  if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5801  CheckingDest))
5802  return note(1, BS.getType(), BS.getBeginLoc());
5803  }
5804  for (FieldDecl *FD : Record->fields()) {
5805  if (FD->getType()->isReferenceType())
5806  return diag(4);
5807  if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5808  CheckingDest))
5809  return note(0, FD->getType(), FD->getBeginLoc());
5810  }
5811  }
5812 
5813  if (Ty->isArrayType() &&
5814  !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5815  Info, Ctx, CheckingDest))
5816  return false;
5817 
5818  return true;
5819 }
5820 
5821 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5822  const ASTContext &Ctx,
5823  const CastExpr *BCE) {
5824  bool DestOK = checkBitCastConstexprEligibilityType(
5825  BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5826  bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5827  BCE->getBeginLoc(),
5828  BCE->getSubExpr()->getType(), Info, Ctx, false);
5829  return SourceOK;
5830 }
5831 
5832 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5833  APValue &SourceValue,
5834  const CastExpr *BCE) {
5835  assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5836  "no host or target supports non 8-bit chars");
5837  assert(SourceValue.isLValue() &&
5838  "LValueToRValueBitcast requires an lvalue operand!");
5839 
5840  if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5841  return false;
5842 
5843  LValue SourceLValue;
5844  APValue SourceRValue;
5845  SourceLValue.setFrom(Info.Ctx, SourceValue);
5846  if (!handleLValueToRValueConversion(Info, BCE,
5847  BCE->getSubExpr()->getType().withConst(),
5848  SourceLValue, SourceRValue))
5849  return false;
5850 
5851  // Read out SourceValue into a char buffer.
5852  Optional<BitCastBuffer> Buffer =
5853  APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5854  if (!Buffer)
5855  return false;
5856 
5857  // Write out the buffer into a new APValue.
5858  Optional<APValue> MaybeDestValue =
5859  BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5860  if (!MaybeDestValue)
5861  return false;
5862 
5863  DestValue = std::move(*MaybeDestValue);
5864  return true;
5865 }
5866 
5867 template <class Derived>
5868 class ExprEvaluatorBase
5869  : public ConstStmtVisitor<Derived, bool> {
5870 private:
5871  Derived &getDerived() { return static_cast<Derived&>(*this); }
5872  bool DerivedSuccess(const APValue &V, const Expr *E) {
5873  return getDerived().Success(V, E);
5874  }
5875  bool DerivedZeroInitialization(const Expr *E) {
5876  return getDerived().ZeroInitialization(E);
5877  }
5878 
5879  // Check whether a conditional operator with a non-constant condition is a
5880  // potential constant expression. If neither arm is a potential constant
5881  // expression, then the conditional operator is not either.
5882  template<typename ConditionalOperator>
5883  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5884  assert(Info.checkingPotentialConstantExpression());
5885 
5886  // Speculatively evaluate both arms.
5888  {
5889  SpeculativeEvaluationRAII Speculate(Info, &Diag);
5890  StmtVisitorTy::Visit(E->getFalseExpr());
5891  if (Diag.empty())
5892  return;
5893  }
5894 
5895  {
5896  SpeculativeEvaluationRAII Speculate(Info, &Diag);
5897  Diag.clear();
5898  StmtVisitorTy::Visit(E->getTrueExpr());
5899  if (Diag.empty())
5900  return;
5901  }
5902 
5903  Error(E, diag::note_constexpr_conditional_never_const);
5904  }
5905 
5906 
5907  template<typename ConditionalOperator>
5908  bool HandleConditionalOperator(const ConditionalOperator *E) {
5909  bool BoolResult;
5910  if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5911  if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5912  CheckPotentialConstantConditional(E);
5913  return false;
5914  }
5915  if (Info.noteFailure()) {
5916  StmtVisitorTy::Visit(E->getTrueExpr());
5917  StmtVisitorTy::Visit(E->getFalseExpr());
5918  }
5919  return false;
5920  }
5921 
5922  Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5923  return StmtVisitorTy::Visit(EvalExpr);
5924  }
5925 
5926 protected:
5927  EvalInfo &Info;
5928  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5929  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5930 
5931  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5932  return Info.CCEDiag(E, D);
5933  }
5934 
5935  bool ZeroInitialization(const Expr *E) { return Error(E); }
5936 
5937 public:
5938  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5939 
5940  EvalInfo &getEvalInfo() { return Info; }
5941 
5942  /// Report an evaluation error. This should only be called when an error is
5943  /// first discovered. When propagating an error, just return false.
5944  bool Error(const Expr *E, diag::kind D) {
5945  Info.FFDiag(E, D);
5946  return false;
5947  }
5948  bool Error(const Expr *E) {
5949  return Error(E, diag::note_invalid_subexpr_in_const_expr);
5950  }
5951 
5952  bool VisitStmt(const Stmt *) {
5953  llvm_unreachable("Expression evaluator should not be called on stmts");
5954  }
5955  bool VisitExpr(const Expr *E) {
5956  return Error(E);
5957  }
5958 
5959  bool VisitConstantExpr(const ConstantExpr *E)
5960  { return StmtVisitorTy::Visit(E->getSubExpr()); }
5961  bool VisitParenExpr(const ParenExpr *E)
5962  { return StmtVisitorTy::Visit(E->getSubExpr()); }
5963  bool VisitUnaryExtension(const UnaryOperator *E)
5964  { return StmtVisitorTy::Visit(E->getSubExpr()); }
5965  bool VisitUnaryPlus(const UnaryOperator *E)
5966  { return StmtVisitorTy::Visit(E->getSubExpr()); }
5967  bool VisitChooseExpr(const ChooseExpr *E)
5968  { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5969  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5970  { return StmtVisitorTy::Visit(E->getResultExpr()); }
5971  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5972  { return StmtVisitorTy::Visit(E->getReplacement()); }
5973  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5974  TempVersionRAII RAII(*Info.CurrentCall);
5975  SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5976  return StmtVisitorTy::Visit(E->getExpr());
5977  }
5978  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5979  TempVersionRAII RAII(*Info.CurrentCall);
5980  // The initializer may not have been parsed yet, or might be erroneous.
5981  if (!E->getExpr())
5982  return Error(E);
5983  SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5984  return StmtVisitorTy::Visit(E->getExpr());
5985  }
5986 
5987  // We cannot create any objects for which cleanups are required, so there is
5988  // nothing to do here; all cleanups must come from unevaluated subexpressions.
5989  bool VisitExprWithCleanups(const ExprWithCleanups *E)
5990  { return StmtVisitorTy::Visit(E->getSubExpr()); }
5991 
5992  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5993  CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5994  return static_cast<Derived*>(this)->VisitCastExpr(E);
5995  }
5996  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5997  if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5998  CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5999  return static_cast<Derived*>(this)->VisitCastExpr(E);
6000  }
6001  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6002  return static_cast<Derived*>(this)->VisitCastExpr(E);
6003  }
6004 
6005  bool VisitBinaryOperator(const BinaryOperator *E) {
6006  switch (E->getOpcode()) {
6007  default:
6008  return Error(E);
6009 
6010  case BO_Comma:
6011  VisitIgnoredValue(E->getLHS());
6012  return StmtVisitorTy::Visit(E->getRHS());
6013 
6014  case BO_PtrMemD:
6015  case BO_PtrMemI: {
6016  LValue Obj;
6017  if (!HandleMemberPointerAccess(Info, E, Obj))
6018  return false;
6019  APValue Result;
6020  if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6021  return false;
6022  return DerivedSuccess(Result, E);
6023  }
6024  }
6025  }
6026 
6027  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6028  // Evaluate and cache the common expression. We treat it as a temporary,
6029  // even though it's not quite the same thing.
6030  if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
6031  Info, E->getCommon()))
6032  return false;
6033 
6034  return HandleConditionalOperator(E);
6035  }
6036 
6037  bool VisitConditionalOperator(const ConditionalOperator *E) {
6038  bool IsBcpCall = false;
6039  // If the condition (ignoring parens) is a __builtin_constant_p call,
6040  // the result is a constant expression if it can be folded without
6041  // side-effects. This is an important GNU extension. See GCC PR38377
6042  // for discussion.
6043  if (const CallExpr *CallCE =
6044  dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6045  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6046  IsBcpCall = true;
6047 
6048  // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6049  // constant expression; we can't check whether it's potentially foldable.
6050  if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6051  return false;
6052 
6053  FoldConstant Fold(Info, IsBcpCall);
6054  if (!HandleConditionalOperator(E)) {
6055  Fold.keepDiagnostics();
6056  return false;
6057  }
6058 
6059  return true;
6060  }
6061 
6062  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6063  if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6064  return DerivedSuccess(*Value, E);
6065 
6066  const Expr *Source = E->getSourceExpr();
6067  if (!Source)
6068  return Error(E);
6069  if (Source == E) { // sanity checking.
6070  assert(0 && "OpaqueValueExpr recursively refers to itself");
6071  return Error(E);
6072  }
6073  return StmtVisitorTy::Visit(Source);
6074  }
6075 
6076  bool VisitCallExpr(const CallExpr *E) {
6077  APValue Result;
6078  if (!handleCallExpr(E, Result, nullptr))
6079  return false;
6080  return DerivedSuccess(Result, E);
6081  }
6082 
6083  bool handleCallExpr(const CallExpr *E, APValue &Result,
6084  const LValue *ResultSlot) {
6085  const Expr *Callee = E->getCallee()->IgnoreParens();
6086  QualType CalleeType = Callee->getType();
6087 
6088  const FunctionDecl *FD = nullptr;
6089  LValue *This = nullptr, ThisVal;
6090  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6091  bool HasQualifier = false;
6092 
6093  // Extract function decl and 'this' pointer from the callee.
6094  if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6095  const CXXMethodDecl *Member = nullptr;
6096  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6097  // Explicit bound member calls, such as x.f() or p->g();
6098  if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6099  return false;
6100  Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6101  if (!Member)
6102  return Error(Callee);
6103  This = &ThisVal;
6104  HasQualifier = ME->hasQualifier();
6105  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6106  // Indirect bound member calls ('.*' or '->*').
6107  Member = dyn_cast_or_null<CXXMethodDecl>(
6108  HandleMemberPointerAccess(Info, BE, ThisVal, false));
6109  if (!Member)
6110  return Error(Callee);
6111  This = &ThisVal;
6112  } else
6113  return Error(Callee);
6114  FD = Member;
6115  } else if (CalleeType->isFunctionPointerType()) {
6116  LValue Call;
6117  if (!EvaluatePointer(Callee, Call, Info))
6118  return false;
6119 
6120  if (!Call.getLValueOffset().isZero())
6121  return Error(Callee);
6122  FD = dyn_cast_or_null<FunctionDecl>(
6123  Call.getLValueBase().dyn_cast<const ValueDecl*>());
6124  if (!FD)
6125  return Error(Callee);
6126  // Don't call function pointers which have been cast to some other type.
6127  // Per DR (no number yet), the caller and callee can differ in noexcept.
6128  if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6129  CalleeType->getPointeeType(), FD->getType())) {
6130  return Error(E);
6131  }
6132 
6133  // Overloaded operator calls to member functions are represented as normal
6134  // calls with '*this' as the first argument.
6135  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6136  if (MD && !MD->isStatic()) {
6137  // FIXME: When selecting an implicit conversion for an overloaded
6138  // operator delete, we sometimes try to evaluate calls to conversion
6139  // operators without a 'this' parameter!
6140  if (Args.empty())
6141  return Error(E);
6142 
6143  if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6144  return false;
6145  This = &ThisVal;
6146  Args = Args.slice(1);
6147  } else if (MD && MD->isLambdaStaticInvoker()) {
6148  // Map the static invoker for the lambda back to the call operator.
6149  // Conveniently, we don't have to slice out the 'this' argument (as is
6150  // being done for the non-static case), since a static member function
6151  // doesn't have an implicit argument passed in.
6152  const CXXRecordDecl *ClosureClass = MD->getParent();
6153  assert(
6154  ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6155  "Number of captures must be zero for conversion to function-ptr");
6156 
6157  const CXXMethodDecl *LambdaCallOp =
6158  ClosureClass->getLambdaCallOperator();
6159 
6160  // Set 'FD', the function that will be called below, to the call
6161  // operator. If the closure object represents a generic lambda, find
6162  // the corresponding specialization of the call operator.
6163 
6164  if (ClosureClass->isGenericLambda()) {
6165  assert(MD->isFunctionTemplateSpecialization() &&
6166  "A generic lambda's static-invoker function must be a "
6167  "template specialization");
6169  FunctionTemplateDecl *CallOpTemplate =
6170  LambdaCallOp->getDescribedFunctionTemplate();
6171  void *InsertPos = nullptr;
6172  FunctionDecl *CorrespondingCallOpSpecialization =
6173  CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6174  assert(CorrespondingCallOpSpecialization &&
6175  "We must always have a function call operator specialization "
6176  "that corresponds to our static invoker specialization");
6177  FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6178  } else
6179  FD = LambdaCallOp;
6180  }
6181  } else
6182  return Error(E);
6183 
6184  SmallVector<QualType, 4> CovariantAdjustmentPath;
6185  if (This) {
6186  auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6187  if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6188  // Perform virtual dispatch, if necessary.
6189  FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6190  CovariantAdjustmentPath);
6191  if (!FD)
6192  return false;
6193  } else {
6194  // Check that the 'this' pointer points to an object of the right type.
6195  if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6196  return false;
6197  }
6198  }
6199 
6200  const FunctionDecl *Definition = nullptr;
6201  Stmt *Body = FD->getBody(Definition);
6202 
6203  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6204  !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6205  Result, ResultSlot))
6206  return false;
6207 
6208  if (!CovariantAdjustmentPath.empty() &&
6209  !HandleCovariantReturnAdjustment(Info, E, Result,
6210  CovariantAdjustmentPath))
6211  return false;
6212 
6213  return true;
6214  }
6215 
6216  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6217  return StmtVisitorTy::Visit(E->getInitializer());
6218  }
6219  bool VisitInitListExpr(const InitListExpr *E) {
6220  if (E->getNumInits() == 0)
6221  return DerivedZeroInitialization(E);
6222  if (E->getNumInits() == 1)
6223  return StmtVisitorTy::Visit(E->getInit(0));
6224  return Error(E);
6225  }
6226  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6227  return DerivedZeroInitialization(E);
6228  }
6229  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6230  return DerivedZeroInitialization(E);
6231  }
6232  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6233  return DerivedZeroInitialization(E);
6234  }
6235 
6236  /// A member expression where the object is a prvalue is itself a prvalue.
6237  bool VisitMemberExpr(const MemberExpr *E) {
6238  assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6239  "missing temporary materialization conversion");
6240  assert(!E->isArrow() && "missing call to bound member function?");
6241 
6242  APValue Val;
6243  if (!Evaluate(Val, Info, E->getBase()))
6244  return false;
6245 
6246  QualType BaseTy = E->getBase()->getType();
6247 
6248  const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6249  if (!FD) return Error(E);
6250  assert(!FD->getType()->isReferenceType() && "prvalue reference?");
6251  assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6252  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6253 
6254  // Note: there is no lvalue base here. But this case should only ever
6255  // happen in C or in C++98, where we cannot be evaluating a constexpr
6256  // constructor, which is the only case the base matters.
6257  CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6258  SubobjectDesignator Designator(BaseTy);
6259  Designator.addDeclUnchecked(FD);
6260 
6261  APValue Result;
6262  return extractSubobject(Info, E, Obj, Designator, Result) &&
6263  DerivedSuccess(Result, E);
6264  }
6265 
6266  bool VisitCastExpr(const CastExpr *E) {
6267  switch (E->getCastKind()) {
6268  default:
6269  break;
6270 
6271  case CK_AtomicToNonAtomic: {
6272  APValue AtomicVal;
6273  // This does not need to be done in place even for class/array types:
6274  // atomic-to-non-atomic conversion implies copying the object
6275  // representation.
6276  if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6277  return false;
6278  return DerivedSuccess(AtomicVal, E);
6279  }
6280 
6281  case CK_NoOp:
6282  case CK_UserDefinedConversion:
6283  return StmtVisitorTy::Visit(E->getSubExpr());
6284 
6285  case CK_LValueToRValue: {
6286  LValue LVal;
6287  if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6288  return false;
6289  APValue RVal;
6290  // Note, we use the subexpression's type in order to retain cv-qualifiers.
6291  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6292  LVal, RVal))
6293  return false;
6294  return DerivedSuccess(RVal, E);
6295  }
6296  case CK_LValueToRValueBitCast: {
6297  APValue DestValue, SourceValue;
6298  if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6299  return false;
6300  if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6301  return false;
6302  return DerivedSuccess(DestValue, E);
6303  }
6304  }
6305 
6306  return Error(E);
6307  }
6308 
6309  bool VisitUnaryPostInc(const UnaryOperator *UO) {
6310  return VisitUnaryPostIncDec(UO);
6311  }
6312  bool VisitUnaryPostDec(const UnaryOperator *UO) {
6313  return VisitUnaryPostIncDec(UO);
6314  }
6315  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6316  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6317  return Error(UO);
6318 
6319  LValue LVal;
6320  if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6321  return false;
6322  APValue RVal;
6323  if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6324  UO->isIncrementOp(), &RVal))
6325  return false;
6326  return DerivedSuccess(RVal, UO);
6327  }
6328 
6329  bool VisitStmtExpr(const StmtExpr *E) {
6330  // We will have checked the full-expressions inside the statement expression
6331  // when they were completed, and don't need to check them again now.
6332  if (Info.checkingForOverflow())
6333  return Error(E);
6334 
6335  BlockScopeRAII Scope(Info);
6336  const CompoundStmt *CS = E->getSubStmt();
6337  if (CS->body_empty())
6338  return true;
6339 
6341  BE = CS->body_end();
6342  /**/; ++BI) {
6343  if (BI + 1 == BE) {
6344  const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6345  if (!FinalExpr) {
6346  Info.FFDiag((*BI)->getBeginLoc(),
6347  diag::note_constexpr_stmt_expr_unsupported);
6348  return false;
6349  }
6350  return this->Visit(FinalExpr);
6351  }
6352 
6353  APValue ReturnValue;
6354  StmtResult Result = { ReturnValue, nullptr };
6355  EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6356  if (ESR != ESR_Succeeded) {
6357  // FIXME: If the statement-expression terminated due to 'return',
6358  // 'break', or 'continue', it would be nice to propagate that to
6359  // the outer statement evaluation rather than bailing out.
6360  if (ESR != ESR_Failed)
6361  Info.FFDiag((*BI)->getBeginLoc(),
6362  diag::note_constexpr_stmt_expr_unsupported);
6363  return false;
6364  }
6365  }
6366 
6367  llvm_unreachable("Return from function from the loop above.");
6368  }
6369 
6370  /// Visit a value which is evaluated, but whose value is ignored.
6371  void VisitIgnoredValue(const Expr *E) {
6372  EvaluateIgnoredValue(Info, E);
6373  }
6374 
6375  /// Potentially visit a MemberExpr's base expression.
6376  void VisitIgnoredBaseExpression(const Expr *E) {
6377  // While MSVC doesn't evaluate the base expression, it does diagnose the
6378  // presence of side-effecting behavior.
6379  if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6380  return;
6381  VisitIgnoredValue(E);
6382  }
6383 };
6384 
6385 } // namespace
6386 
6387 //===----------------------------------------------------------------------===//
6388 // Common base class for lvalue and temporary evaluation.
6389 //===----------------------------------------------------------------------===//
6390 namespace {
6391 template<class Derived>
6392 class LValueExprEvaluatorBase
6393  : public ExprEvaluatorBase<Derived> {
6394 protected:
6395  LValue &Result;
6396  bool InvalidBaseOK;
6397  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6398  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6399 
6400  bool Success(APValue::LValueBase B) {
6401  Result.set(B);
6402  return true;
6403  }
6404 
6405  bool evaluatePointer(const Expr *E, LValue &Result) {
6406  return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6407  }
6408 
6409 public:
6410  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6411  : ExprEvaluatorBaseTy(Info), Result(Result),
6412  InvalidBaseOK(InvalidBaseOK) {}
6413 
6414  bool Success(const APValue &V, const Expr *E) {
6415  Result.setFrom(this->Info.Ctx, V);
6416  return true;
6417  }
6418 
6419  bool VisitMemberExpr(const MemberExpr *E) {
6420  // Handle non-static data members.
6421  QualType BaseTy;
6422  bool EvalOK;
6423  if (E->isArrow()) {
6424  EvalOK = evaluatePointer(E->getBase(), Result);
6425  BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6426  } else if (E->getBase()->isRValue()) {
6427  assert(E->getBase()->getType()->isRecordType());
6428  EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6429  BaseTy = E->getBase()->getType();
6430  } else {
6431  EvalOK = this->Visit(E->getBase());
6432  BaseTy = E->getBase()->getType();
6433  }
6434  if (!EvalOK) {
6435  if (!InvalidBaseOK)
6436  return false;
6437  Result.setInvalid(E);
6438  return true;
6439  }
6440 
6441  const ValueDecl *MD = E->getMemberDecl();
6442  if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6443  assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6444  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6445  (void)BaseTy;
6446  if (!HandleLValueMember(this->Info, E, Result, FD))
6447  return false;
6448  } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6449  if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6450  return false;
6451  } else
6452  return this->Error(E);
6453 
6454  if (MD->getType()->isReferenceType()) {
6455  APValue RefValue;
6456  if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6457  RefValue))
6458  return false;
6459  return Success(RefValue, E);
6460  }
6461  return true;
6462  }
6463 
6464  bool VisitBinaryOperator(const BinaryOperator *E) {
6465  switch (E->getOpcode()) {
6466  default:
6467  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6468 
6469  case BO_PtrMemD:
6470  case BO_PtrMemI:
6471  return HandleMemberPointerAccess(this->Info, E, Result);
6472  }
6473  }
6474 
6475  bool VisitCastExpr(const CastExpr *E) {
6476  switch (E->getCastKind()) {
6477  default:
6478  return ExprEvaluatorBaseTy::VisitCastExpr(E);
6479 
6480  case CK_DerivedToBase:
6481  case CK_UncheckedDerivedToBase:
6482  if (!this->Visit(E->getSubExpr()))
6483  return false;
6484 
6485  // Now figure out the necessary offset to add to the base LV to get from
6486  // the derived class to the base class.
6487  return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6488  Result);
6489  }
6490  }
6491 };
6492 }
6493 
6494 //===----------------------------------------------------------------------===//
6495 // LValue Evaluation
6496 //
6497 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6498 // function designators (in C), decl references to void objects (in C), and
6499 // temporaries (if building with -Wno-address-of-temporary).
6500 //
6501 // LValue evaluation produces values comprising a base expression of one of the
6502 // following types:
6503 // - Declarations
6504 // * VarDecl
6505 // * FunctionDecl
6506 // - Literals
6507 // * CompoundLiteralExpr in C (and in global scope in C++)
6508 // * StringLiteral
6509 // * PredefinedExpr
6510 // * ObjCStringLiteralExpr
6511 // * ObjCEncodeExpr
6512 // * AddrLabelExpr
6513 // * BlockExpr
6514 // * CallExpr for a MakeStringConstant builtin
6515 // - typeid(T) expressions, as TypeInfoLValues
6516 // - Locals and temporaries
6517 // * MaterializeTemporaryExpr
6518 // * Any Expr, with a CallIndex indicating the function in which the temporary
6519 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
6520 // from the AST (FIXME).
6521 // * A MaterializeTemporaryExpr that has static storage duration, with no
6522 // CallIndex, for a lifetime-extended temporary.
6523 // plus an offset in bytes.
6524 //===----------------------------------------------------------------------===//
6525 namespace {
6526 class LValueExprEvaluator
6527  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6528 public:
6529  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6530  LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6531 
6532  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6533  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6534 
6535  bool VisitDeclRefExpr(const DeclRefExpr *E);
6536  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6537  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6538  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6539  bool VisitMemberExpr(const MemberExpr *E);
6540  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6541  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6542  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6543  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6544  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6545  bool VisitUnaryDeref(const UnaryOperator *E);
6546  bool VisitUnaryReal(const UnaryOperator *E);
6547  bool VisitUnaryImag(const UnaryOperator *E);
6548  bool VisitUnaryPreInc(const UnaryOperator *UO) {
6549  return VisitUnaryPreIncDec(UO);
6550  }
6551  bool VisitUnaryPreDec(const UnaryOperator *UO) {
6552  return VisitUnaryPreIncDec(UO);
6553  }
6554  bool VisitBinAssign(const BinaryOperator *BO);
6555  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6556 
6557  bool VisitCastExpr(const CastExpr *E) {
6558  switch (E->getCastKind()) {
6559  default:
6560  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6561 
6562  case CK_LValueBitCast:
6563  this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6564  if (!Visit(E->getSubExpr()))
6565  return false;
6566  Result.Designator.setInvalid();
6567  return true;
6568 
6569  case CK_BaseToDerived:
6570  if (!Visit(E->getSubExpr()))
6571  return false;
6572  return HandleBaseToDerivedCast(Info, E, Result);
6573 
6574  case CK_Dynamic:
6575  if (!Visit(E->getSubExpr()))
6576  return false;
6577  return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6578  }
6579  }
6580 };
6581 } // end anonymous namespace
6582 
6583 /// Evaluate an expression as an lvalue. This can be legitimately called on
6584 /// expressions which are not glvalues, in three cases:
6585 /// * function designators in C, and
6586 /// * "extern void" objects
6587 /// * @selector() expressions in Objective-C
6588 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6589  bool InvalidBaseOK) {
6590  assert(E->isGLValue() || E->getType()->isFunctionType() ||
6591  E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6592  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6593 }
6594 
6595 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6596  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6597  return Success(FD);
6598  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6599  return VisitVarDecl(E, VD);
6600  if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6601  return Visit(BD->getBinding());
6602  return Error(E);
6603 }
6604 
6605 
6606 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6607 
6608  // If we are within a lambda's call operator, check whether the 'VD' referred
6609  // to within 'E' actually represents a lambda-capture that maps to a
6610  // data-member/field within the closure object, and if so, evaluate to the
6611  // field or what the field refers to.
6612  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6613  isa<DeclRefExpr>(E) &&
6614  cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6615  // We don't always have a complete capture-map when checking or inferring if
6616  // the function call operator meets the requirements of a constexpr function
6617  // - but we don't need to evaluate the captures to determine constexprness
6618  // (dcl.constexpr C++17).
6619  if (Info.checkingPotentialConstantExpression())
6620  return false;
6621 
6622  if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6623  // Start with 'Result' referring to the complete closure object...
6624  Result = *Info.CurrentCall->This;
6625  // ... then update it to refer to the field of the closure object
6626  // that represents the capture.
6627  if (!HandleLValueMember(Info, E, Result, FD))
6628  return false;
6629  // And if the field is of reference type, update 'Result' to refer to what
6630  // the field refers to.
6631  if (FD->getType()->isReferenceType()) {
6632  APValue RVal;
6633  if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6634  RVal))
6635  return false;
6636  Result.setFrom(Info.Ctx, RVal);
6637  }
6638  return true;
6639  }
6640  }
6641  CallStackFrame *Frame = nullptr;
6642  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6643  // Only if a local variable was declared in the function currently being
6644  // evaluated, do we expect to be able to find its value in the current
6645  // frame. (Otherwise it was likely declared in an enclosing context and
6646  // could either have a valid evaluatable value (for e.g. a constexpr
6647  // variable) or be ill-formed (and trigger an appropriate evaluation
6648  // diagnostic)).
6649  if (Info.CurrentCall->Callee &&
6650  Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6651  Frame = Info.CurrentCall;
6652  }
6653  }
6654 
6655  if (!VD->getType()->isReferenceType()) {
6656  if (Frame) {
6657  Result.set({VD, Frame->Index,
6658  Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6659  return true;
6660  }
6661  return Success(VD);
6662  }
6663 
6664  APValue *V;
6665  if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6666  return false;
6667  if (!V->hasValue()) {
6668  // FIXME: Is it possible for V to be indeterminate here? If so, we should
6669  // adjust the diagnostic to say that.
6670  if (!Info.checkingPotentialConstantExpression())
6671  Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6672  return false;
6673  }
6674  return Success(*V, E);
6675 }
6676 
6677 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6678  const MaterializeTemporaryExpr *E) {
6679  // Walk through the expression to find the materialized temporary itself.
6680  SmallVector<const Expr *, 2> CommaLHSs;
6682  const Expr *Inner = E->GetTemporaryExpr()->
6683  skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6684 
6685  // If we passed any comma operators, evaluate their LHSs.
6686  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6687  if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6688  return false;
6689 
6690  // A materialized temporary with static storage duration can appear within the
6691  // result of a constant expression evaluation, so we need to preserve its
6692  // value for use outside this evaluation.
6693  APValue *Value;
6694  if (E->getStorageDuration() == SD_Static) {
6695  Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6696  *Value = APValue();
6697  Result.set(E);
6698  } else {
6700  *Info.CurrentCall);
6701  }
6702 
6703  QualType Type = Inner->getType();
6704 
6705  // Materialize the temporary itself.
6706  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6707  (E->getStorageDuration() == SD_Static &&
6708  !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6709  *Value = APValue();
6710  return false;
6711  }
6712 
6713  // Adjust our lvalue to refer to the desired subobject.
6714  for (unsigned I = Adjustments.size(); I != 0; /**/) {
6715  --I;
6716  switch (Adjustments[I].Kind) {
6718  if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6719  Type, Result))
6720  return false;
6721  Type = Adjustments[I].DerivedToBase.BasePath->getType();
6722  break;
6723 
6725  if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6726  return false;
6727  Type = Adjustments[I].Field->getType();
6728  break;
6729 
6731  if (!HandleMemberPointerAccess(this->Info, Type, Result,
6732  Adjustments[I].Ptr.RHS))
6733  return false;
6734  Type = Adjustments[I].Ptr.MPT->getPointeeType();
6735  break;
6736  }
6737  }
6738 
6739  return true;
6740 }
6741 
6742 bool
6743 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6744  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6745  "lvalue compound literal in c++?");
6746  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6747  // only see this when folding in C, so there's no standard to follow here.
6748  return Success(E);
6749 }
6750 
6751 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6753 
6754  if (!E->isPotentiallyEvaluated()) {
6755  if (E->isTypeOperand())
6756  TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6757  else
6758  TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6759  } else {
6760  if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6761  Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6762  << E->getExprOperand()->getType()
6763  << E->getExprOperand()->getSourceRange();
6764  }
6765 
6766  if (!Visit(E->getExprOperand()))
6767  return false;
6768 
6769  Optional<DynamicType> DynType =
6770  ComputeDynamicType(Info, E, Result, AK_TypeId);
6771  if (!DynType)
6772  return false;
6773 
6774  TypeInfo =
6775  TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6776  }
6777 
6778  return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6779 }
6780 
6781 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6782  return Success(E);
6783 }
6784 
6785 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6786  // Handle static data members.
6787  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6788  VisitIgnoredBaseExpression(E->getBase());
6789  return VisitVarDecl(E, VD);
6790  }
6791 
6792  // Handle static member functions.
6793  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6794  if (MD->isStatic()) {
6795  VisitIgnoredBaseExpression(E->getBase());
6796  return Success(MD);
6797  }
6798  }
6799 
6800  // Handle non-static data members.
6801  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6802 }
6803 
6804 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6805  // FIXME: Deal with vectors as array subscript bases.
6806  if (E->getBase()->getType()->isVectorType())
6807  return Error(E);
6808 
6809  bool Success = true;
6810  if (!evaluatePointer(E->getBase(), Result)) {
6811  if (!Info.noteFailure())
6812  return false;
6813  Success = false;
6814  }
6815 
6816  APSInt Index;
6817  if (!EvaluateInteger(E->getIdx(), Index, Info))
6818  return false;
6819 
6820  return Success &&
6821  HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6822 }
6823 
6824 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6825  return evaluatePointer(E->getSubExpr(), Result);
6826 }
6827 
6828 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6829  if (!Visit(E->getSubExpr()))
6830  return false;
6831  // __real is a no-op on scalar lvalues.
6832  if (E->getSubExpr()->getType()->isAnyComplexType())
6833  HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6834  return true;
6835 }
6836 
6837 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6838  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6839  "lvalue __imag__ on scalar?");
6840  if (!Visit(E->getSubExpr()))
6841  return false;
6842  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6843  return true;
6844 }
6845 
6846 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6847  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6848  return Error(UO);
6849 
6850  if (!this->Visit(UO->getSubExpr()))
6851  return false;
6852 
6853  return handleIncDec(
6854  this->Info, UO, Result, UO->getSubExpr()->getType(),
6855  UO->isIncrementOp(), nullptr);
6856 }
6857 
6858 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6859  const CompoundAssignOperator *CAO) {
6860  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6861  return Error(CAO);
6862 
6863  APValue RHS;
6864 
6865  // The overall lvalue result is the result of evaluating the LHS.
6866  if (!this->Visit(CAO->getLHS())) {
6867  if (Info.noteFailure())
6868  Evaluate(RHS, this->Info, CAO->getRHS());
6869  return false;
6870  }
6871 
6872  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6873  return false;
6874 
6875  return handleCompoundAssignment(
6876  this->Info, CAO,
6877  Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6878  CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6879 }
6880 
6881 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6882  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6883  return Error(E);
6884 
6885  APValue NewVal;
6886 
6887  if (!this->Visit(E->getLHS())) {
6888  if (Info.noteFailure())
6889  Evaluate(NewVal, this->Info, E->getRHS());
6890  return false;
6891  }
6892 
6893  if (!Evaluate(NewVal, this->Info, E->getRHS()))
6894  return false;
6895 
6896  if (Info.getLangOpts().CPlusPlus2a &&
6898  return false;
6899 
6900  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6901  NewVal);
6902 }
6903 
6904 //===----------------------------------------------------------------------===//
6905 // Pointer Evaluation
6906 //===----------------------------------------------------------------------===//
6907 
6908 /// Attempts to compute the number of bytes available at the pointer
6909 /// returned by a function with the alloc_size attribute. Returns true if we
6910 /// were successful. Places an unsigned number into `Result`.
6911 ///
6912 /// This expects the given CallExpr to be a call to a function with an
6913 /// alloc_size attribute.
6915  const CallExpr *Call,
6916  llvm::APInt &Result) {
6917  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6918 
6919  assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6920  unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6921  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6922  if (Call->getNumArgs() <= SizeArgNo)
6923  return false;
6924 
6925  auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6927  if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6928  return false;
6929  Into = ExprResult.Val.getInt();
6930  if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6931  return false;
6932  Into = Into.zextOrSelf(BitsInSizeT);
6933  return true;
6934  };
6935 
6936  APSInt SizeOfElem;
6937  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6938  return false;
6939 
6940  if (!AllocSize->getNumElemsParam().isValid()) {
6941  Result = std::move(SizeOfElem);
6942  return true;
6943  }
6944 
6945  APSInt NumberOfElems;
6946  unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6947  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6948  return false;
6949 
6950  bool Overflow;
6951  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6952  if (Overflow)
6953  return false;
6954 
6955  Result = std::move(BytesAvailable);
6956  return true;
6957 }
6958 
6959 /// Convenience function. LVal's base must be a call to an alloc_size
6960 /// function.
6962  const LValue &LVal,
6963  llvm::APInt &Result) {
6964  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6965  "Can't get the size of a non alloc_size function");
6966  const auto *Base = LVal.getLValueBase().get<const Expr *>();
6967  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6968  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6969 }
6970 
6971 /// Attempts to evaluate the given LValueBase as the result of a call to
6972 /// a function with the alloc_size attribute. If it was possible to do so, this
6973 /// function will return true, make Result's Base point to said function call,
6974 /// and mark Result's Base as invalid.
6975 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6976  LValue &Result) {
6977  if (Base.isNull())
6978  return false;
6979 
6980  // Because we do no form of static analysis, we only support const variables.
6981  //
6982  // Additionally, we can't support parameters, nor can we support static
6983  // variables (in the latter case, use-before-assign isn't UB; in the former,
6984  // we have no clue what they'll be assigned to).
6985  const auto *VD =
6986  dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6987  if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6988  return false;
6989 
6990  const Expr *Init = VD->getAnyInitializer();
6991  if (!Init)
6992  return false;
6993 
6994  const Expr *E = Init->IgnoreParens();
6995  if (!tryUnwrapAllocSizeCall(E))
6996  return false;
6997 
6998  // Store E instead of E unwrapped so that the type of the LValue's base is
6999  // what the user wanted.
7000  Result.setInvalid(E);
7001 
7002  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7003  Result.addUnsizedArray(Info, E, Pointee);
7004  return true;
7005 }
7006 
7007 namespace {
7008 class PointerExprEvaluator
7009  : public ExprEvaluatorBase<PointerExprEvaluator> {
7010  LValue &Result;
7011  bool InvalidBaseOK;
7012 
7013  bool Success(const Expr *E) {
7014  Result.set(E);
7015  return true;
7016  }
7017 
7018  bool evaluateLValue(const Expr *E, LValue &Result) {
7019  return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7020  }
7021 
7022  bool evaluatePointer(const Expr *E, LValue &Result) {
7023  return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7024  }
7025 
7026  bool visitNonBuiltinCallExpr(const CallExpr *E);
7027 public:
7028 
7029  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7030  : ExprEvaluatorBaseTy(info), Result(Result),
7031  InvalidBaseOK(InvalidBaseOK) {}
7032 
7033  bool Success(const APValue &V, const Expr *E) {
7034  Result.setFrom(Info.Ctx, V);
7035  return true;
7036  }
7037  bool ZeroInitialization(const Expr *E) {
7038  auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7039  Result.setNull(E->getType(), TargetVal);
7040  return true;
7041  }
7042 
7043  bool VisitBinaryOperator(const BinaryOperator *E);
7044  bool VisitCastExpr(const CastExpr* E);
7045  bool VisitUnaryAddrOf(const UnaryOperator *E);
7046  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7047  { return Success(E); }
7048  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7050  return Success(E);
7051  if (Info.noteFailure())
7052  EvaluateIgnoredValue(Info, E->getSubExpr());
7053  return Error(E);
7054  }
7055  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7056  { return Success(E); }
7057  bool VisitCallExpr(const CallExpr *E);
7058  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7059  bool VisitBlockExpr(const BlockExpr *E) {
7060  if (!E->getBlockDecl()->hasCaptures())
7061  return Success(E);
7062  return Error(E);
7063  }
7064  bool VisitCXXThisExpr(const CXXThisExpr *E) {
7065  // Can't look at 'this' when checking a potential constant expression.
7066  if (Info.checkingPotentialConstantExpression())
7067  return false;
7068  if (!Info.CurrentCall->This) {
7069  if (Info.getLangOpts().CPlusPlus11)
7070  Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7071  else
7072  Info.FFDiag(E);
7073  return false;
7074  }
7075  Result = *Info.CurrentCall->This;
7076  // If we are inside a lambda's call operator, the 'this' expression refers
7077  // to the enclosing '*this' object (either by value or reference) which is
7078  // either copied into the closure object's field that represents the '*this'
7079  // or refers to '*this'.
7080  if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7081  // Update 'Result' to refer to the data member/field of the closure object
7082  // that represents the '*this' capture.
7083  if (!HandleLValueMember(Info, E, Result,
7084  Info.CurrentCall->LambdaThisCaptureField))
7085  return false;
7086  // If we captured '*this' by reference, replace the field with its referent.
7087  if (Info.CurrentCall->LambdaThisCaptureField->getType()
7088  ->isPointerType()) {
7089  APValue RVal;
7090  if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7091  RVal))
7092  return false;
7093 
7094  Result.setFrom(Info.Ctx, RVal);
7095  }
7096  }
7097  return true;
7098  }
7099 
7100  bool VisitSourceLocExpr(const SourceLocExpr *E) {
7101  assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7102  APValue LValResult = E->EvaluateInContext(
7103  Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7104  Result.setFrom(Info.Ctx, LValResult);
7105  return true;
7106  }
7107 
7108  // FIXME: Missing: @protocol, @selector
7109 };
7110 } // end anonymous namespace
7111 
7112 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7113  bool InvalidBaseOK) {
7114  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7115  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7116 }
7117 
7118 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7119  if (E->getOpcode() != BO_Add &&
7120  E->getOpcode() != BO_Sub)
7121  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7122 
7123  const Expr *PExp = E->getLHS();
7124  const Expr *IExp = E->getRHS();
7125  if (IExp->getType()->isPointerType())
7126  std::swap(PExp, IExp);
7127 
7128  bool EvalPtrOK = evaluatePointer(PExp, Result);
7129  if (!EvalPtrOK && !Info.noteFailure())
7130  return false;
7131 
7132  llvm::APSInt Offset;
7133  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7134  return false;
7135 
7136  if (E->getOpcode() == BO_Sub)
7137  negateAsSigned(Offset);
7138 
7139  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7140  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7141 }
7142 
7143 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7144  return evaluateLValue(E->getSubExpr(), Result);
7145 }
7146 
7147 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7148  const Expr *SubExpr = E->getSubExpr();
7149 
7150  switch (E->getCastKind()) {
7151  default:
7152  break;
7153  case CK_BitCast:
7154  case CK_CPointerToObjCPointerCast:
7155  case CK_BlockPointerToObjCPointerCast:
7156  case CK_AnyPointerToBlockPointerCast:
7157  case CK_AddressSpaceConversion:
7158  if (!Visit(SubExpr))
7159  return false;
7160  // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7161  // permitted in constant expressions in C++11. Bitcasts from cv void* are
7162  // also static_casts, but we disallow them as a resolution to DR1312.
7163  if (!E->getType()->isVoidPointerType()) {
7164  Result.Designator.setInvalid();
7165  if (SubExpr->getType()->isVoidPointerType())
7166  CCEDiag(E, diag::note_constexpr_invalid_cast)
7167  << 3 << SubExpr->getType();
7168  else
7169  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7170  }
7171  if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7172  ZeroInitialization(E);
7173  return true;
7174 
7175  case CK_DerivedToBase:
7176  case CK_UncheckedDerivedToBase:
7177  if (!evaluatePointer(E->getSubExpr(), Result))
7178  return false;
7179  if (!Result.Base && Result.Offset.isZero())
7180  return true;
7181 
7182  // Now figure out the necessary offset to add to the base LV to get from
7183  // the derived class to the base class.
7184  return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7185  castAs<PointerType>()->getPointeeType(),
7186  Result);
7187 
7188  case CK_BaseToDerived:
7189  if (!Visit(E->getSubExpr()))
7190  return false;
7191  if (!Result.Base && Result.Offset.isZero())
7192  return true;
7193  return HandleBaseToDerivedCast(Info, E, Result);
7194 
7195  case CK_Dynamic:
7196  if (!Visit(E->getSubExpr()))
7197  return false;
7198  return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7199 
7200  case CK_NullToPointer:
7201  VisitIgnoredValue(E->getSubExpr());
7202  return ZeroInitialization(E);
7203 
7204  case CK_IntegralToPointer: {
7205  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7206 
7207  APValue Value;
7208  if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7209  break;
7210 
7211  if (Value.isInt()) {
7212  unsigned Size = Info.Ctx.getTypeSize(E->getType());
7213  uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7214  Result.Base = (Expr*)nullptr;
7215  Result.InvalidBase = false;
7216  Result.Offset = CharUnits::fromQuantity(N);
7217  Result.Designator.setInvalid();
7218  Result.IsNullPtr = false;
7219  return true;
7220  } else {
7221  // Cast is of an lvalue, no need to change value.
7222  Result.setFrom(Info.Ctx, Value);
7223  return true;
7224  }
7225  }
7226 
7227  case CK_ArrayToPointerDecay: {
7228  if (SubExpr->isGLValue()) {
7229  if (!evaluateLValue(SubExpr, Result))
7230  return false;
7231  } else {
7232  APValue &Value = createTemporary(SubExpr, false, Result,
7233  *Info.CurrentCall);
7234  if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7235  return false;
7236  }
7237  // The result is a pointer to the first element of the array.
7238  auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7239  if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7240  Result.addArray(Info, E, CAT);
7241  else
7242  Result.addUnsizedArray(Info, E, AT->getElementType());
7243  return true;
7244  }
7245 
7246  case CK_FunctionToPointerDecay:
7247  return evaluateLValue(SubExpr, Result);
7248 
7249  case CK_LValueToRValue: {
7250  LValue LVal;
7251  if (!evaluateLValue(E->getSubExpr(), LVal))
7252  return false;
7253 
7254  APValue RVal;
7255  // Note, we use the subexpression's type in order to retain cv-qualifiers.
7256  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7257  LVal, RVal))
7258  return InvalidBaseOK &&
7259  evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7260  return Success(RVal, E);
7261  }
7262  }
7263 
7264  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7265 }
7266 
7267 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7268  UnaryExprOrTypeTrait ExprKind) {
7269  // C++ [expr.alignof]p3:
7270  // When alignof is applied to a reference type, the result is the
7271  // alignment of the referenced type.
7272  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7273  T = Ref->getPointeeType();
7274 
7275  if (T.getQualifiers().hasUnaligned())
7276  return CharUnits::One();
7277 
7278  const bool AlignOfReturnsPreferred =
7279  Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7280 
7281  // __alignof is defined to return the preferred alignment.
7282  // Before 8, clang returned the preferred alignment for alignof and _Alignof
7283  // as well.
7284  if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7285  return Info.Ctx.toCharUnitsFromBits(
7286  Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7287  // alignof and _Alignof are defined to return the ABI alignment.
7288  else if (ExprKind == UETT_AlignOf)
7289  return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7290  else
7291  llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
7292 }
7293 
7294 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7295  UnaryExprOrTypeTrait ExprKind) {
7296  E = E->IgnoreParens();
7297 
7298  // The kinds of expressions that we have special-case logic here for
7299  // should be kept up to date with the special checks for those
7300  // expressions in Sema.
7301 
7302  // alignof decl is always accepted, even if it doesn't make sense: we default
7303  // to 1 in those cases.
7304  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7305  return Info.Ctx.getDeclAlign(DRE->getDecl(),
7306  /*RefAsPointee*/true);
7307 
7308  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7309  return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7310  /*RefAsPointee*/true);
7311 
7312  return GetAlignOfType(Info, E->getType(), ExprKind);
7313 }
7314 
7315 // To be clear: this happily visits unsupported builtins. Better name welcomed.
7316 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7317  if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7318  return true;
7319 
7320  if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7321  return false;
7322 
7323  Result.setInvalid(E);
7324  QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7325  Result.addUnsizedArray(Info, E, PointeeTy);
7326  return true;
7327 }
7328 
7329 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7330  if (IsStringLiteralCall(E))
7331  return Success(E);
7332 
7333  if (unsigned BuiltinOp = E->getBuiltinCallee())
7334  return VisitBuiltinCallExpr(E, BuiltinOp);
7335 
7336  return visitNonBuiltinCallExpr(E);
7337 }
7338 
7339 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7340  unsigned BuiltinOp) {
7341  switch (BuiltinOp) {
7342  case Builtin::BI__builtin_addressof:
7343  return evaluateLValue(E->getArg(0), Result);
7344  case Builtin::BI__builtin_assume_aligned: {
7345  // We need to be very careful here because: if the pointer does not have the
7346  // asserted alignment, then the behavior is undefined, and undefined
7347  // behavior is non-constant.
7348  if (!evaluatePointer(E->getArg(0), Result))
7349  return false;
7350 
7351  LValue OffsetResult(Result);
7352  APSInt Alignment;
7353  if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7354  return false;
7355  CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7356 
7357  if (E->getNumArgs() > 2) {
7358  APSInt Offset;
7359  if (!EvaluateInteger(E->getArg(2), Offset, Info))
7360  return false;
7361 
7362  int64_t AdditionalOffset = -Offset.getZExtValue();
7363  OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7364  }
7365 
7366  // If there is a base object, then it must have the correct alignment.
7367  if (OffsetResult.Base) {
7368  CharUnits BaseAlignment;
7369  if (const ValueDecl *VD =
7370  OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7371  BaseAlignment = Info.Ctx.getDeclAlign(VD);
7372  } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7373  BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7374  } else {
7375  BaseAlignment = GetAlignOfType(
7376  Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7377  }
7378 
7379  if (BaseAlignment < Align) {
7380  Result.Designator.setInvalid();
7381  // FIXME: Add support to Diagnostic for long / long long.
7382  CCEDiag(E->getArg(0),
7383  diag::note_constexpr_baa_insufficient_alignment) << 0
7384  << (unsigned)BaseAlignment.getQuantity()
7385  << (unsigned)Align.getQuantity();
7386  return false;
7387  }
7388  }
7389 
7390  // The offset must also have the correct alignment.
7391  if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7392  Result.Designator.setInvalid();
7393 
7394  (OffsetResult.Base
7395  ? CCEDiag(E->getArg(0),
7396  diag::note_constexpr_baa_insufficient_alignment) << 1
7397  : CCEDiag(E->getArg(0),
7398  diag::note_constexpr_baa_value_insufficient_alignment))
7399  << (int)OffsetResult.Offset.getQuantity()
7400  << (unsigned)Align.getQuantity();
7401  return false;
7402  }
7403 
7404  return true;
7405  }
7406  case Builtin::BI__builtin_launder:
7407  return evaluatePointer(E->getArg(0), Result);
7408  case Builtin::BIstrchr:
7409  case Builtin::BIwcschr:
7410  case Builtin::BImemchr:
7411  case Builtin::BIwmemchr:
7412  if (Info.getLangOpts().CPlusPlus11)
7413  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7414  << /*isConstexpr*/0 << /*isConstructor*/0
7415  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7416  else
7417  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7418  LLVM_FALLTHROUGH;
7419  case Builtin::BI__builtin_strchr:
7420  case Builtin::BI__builtin_wcschr:
7421  case Builtin::BI__builtin_memchr:
7422  case Builtin::BI__builtin_char_memchr:
7423  case Builtin::BI__builtin_wmemchr: {
7424  if (!Visit(E->getArg(0)))
7425  return false;
7426  APSInt Desired;
7427  if (!EvaluateInteger(E->getArg(1), Desired, Info))
7428  return false;
7429  uint64_t MaxLength = uint64_t(-1);
7430  if (BuiltinOp != Builtin::BIstrchr &&
7431  BuiltinOp != Builtin::BIwcschr &&
7432  BuiltinOp != Builtin::BI__builtin_strchr &&
7433  BuiltinOp != Builtin::BI__builtin_wcschr) {
7434  APSInt N;
7435  if (!EvaluateInteger(E->getArg(2), N, Info))
7436  return false;
7437  MaxLength = N.getExtValue();
7438  }
7439  // We cannot find the value if there are no candidates to match against.
7440  if (MaxLength == 0u)
7441  return ZeroInitialization(E);
7442  if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7443  Result.Designator.Invalid)
7444  return false;
7445  QualType CharTy = Result.Designator.getType(Info.Ctx);
7446  bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7447  BuiltinOp == Builtin::BI__builtin_memchr;
7448  assert(IsRawByte ||
7449  Info.Ctx.hasSameUnqualifiedType(
7450  CharTy, E->getArg(0)->getType()->getPointeeType()));
7451  // Pointers to const void may point to objects of incomplete type.
7452  if (IsRawByte && CharTy->isIncompleteType()) {
7453  Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7454  return false;
7455  }
7456  // Give up on byte-oriented matching against multibyte elements.
7457  // FIXME: We can compare the bytes in the correct order.
7458  if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7459  return false;
7460  // Figure out what value we're actually looking for (after converting to
7461  // the corresponding unsigned type if necessary).
7462  uint64_t DesiredVal;
7463  bool StopAtNull = false;
7464  switch (BuiltinOp) {
7465  case Builtin::BIstrchr:
7466  case Builtin::BI__builtin_strchr:
7467  // strchr compares directly to the passed integer, and therefore
7468  // always fails if given an int that is not a char.
7469  if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7470  E->getArg(1)->getType(),
7471  Desired),
7472  Desired))
7473  return ZeroInitialization(E);
7474  StopAtNull = true;
7475  LLVM_FALLTHROUGH;
7476  case Builtin::BImemchr:
7477  case Builtin::BI__builtin_memchr:
7478  case Builtin::BI__builtin_char_memchr:
7479  // memchr compares by converting both sides to unsigned char. That's also
7480  // correct for strchr if we get this far (to cope with plain char being
7481  // unsigned in the strchr case).
7482  DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7483  break;
7484 
7485  case Builtin::BIwcschr:
7486  case Builtin::BI__builtin_wcschr:
7487  StopAtNull = true;
7488  LLVM_FALLTHROUGH;
7489  case Builtin::BIwmemchr:
7490  case Builtin::BI__builtin_wmemchr:
7491  // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7492  DesiredVal = Desired.getZExtValue();
7493  break;
7494  }
7495 
7496  for (; MaxLength; --MaxLength) {
7497  APValue Char;
7498  if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7499  !Char.isInt())
7500  return false;
7501  if (Char.getInt().getZExtValue() == DesiredVal)
7502  return true;
7503  if (StopAtNull && !Char.getInt())
7504  break;
7505  if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7506  return false;
7507  }
7508  // Not found: return nullptr.
7509  return ZeroInitialization(E);
7510  }
7511 
7512  case Builtin::BImemcpy:
7513  case Builtin::BImemmove:
7514  case Builtin::BIwmemcpy:
7515  case Builtin::BIwmemmove:
7516  if (Info.getLangOpts().CPlusPlus11)
7517  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7518  << /*isConstexpr*/0 << /*isConstructor*/0
7519  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7520  else
7521  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7522  LLVM_FALLTHROUGH;
7523  case Builtin::BI__builtin_memcpy:
7524  case Builtin::BI__builtin_memmove:
7525  case Builtin::BI__builtin_wmemcpy:
7526  case Builtin::BI__builtin_wmemmove: {
7527  bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7528  BuiltinOp == Builtin::BIwmemmove ||
7529  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7530  BuiltinOp == Builtin::BI__builtin_wmemmove;
7531  bool Move = BuiltinOp == Builtin::BImemmove ||
7532  BuiltinOp == Builtin::BIwmemmove ||
7533  BuiltinOp == Builtin::BI__builtin_memmove ||
7534  BuiltinOp == Builtin::BI__builtin_wmemmove;
7535 
7536  // The result of mem* is the first argument.
7537  if (!Visit(E->getArg(0)))
7538  return false;
7539  LValue Dest = Result;
7540 
7541  LValue Src;
7542  if (!EvaluatePointer(E->getArg(1), Src, Info))
7543  return false;
7544 
7545  APSInt N;
7546  if (!EvaluateInteger(E->getArg(2), N, Info))
7547  return false;
7548  assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7549 
7550  // If the size is zero, we treat this as always being a valid no-op.
7551  // (Even if one of the src and dest pointers is null.)
7552  if (!N)
7553  return true;
7554 
7555  // Otherwise, if either of the operands is null, we can't proceed. Don't
7556  // try to determine the type of the copied objects, because there aren't
7557  // any.
7558  if (!Src.Base || !Dest.Base) {
7559  APValue Val;
7560  (!Src.Base ? Src : Dest).moveInto(Val);
7561  Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7562  << Move << WChar << !!Src.Base
7563  << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7564  return false;
7565  }
7566  if (Src.Designator.Invalid || Dest.Designator.Invalid)
7567  return false;
7568 
7569  // We require that Src and Dest are both pointers to arrays of
7570  // trivially-copyable type. (For the wide version, the designator will be
7571  // invalid if the designated object is not a wchar_t.)
7572  QualType T = Dest.Designator.getType(Info.Ctx);
7573  QualType SrcT = Src.Designator.getType(Info.Ctx);
7574  if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7575  Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7576  return false;
7577  }
7578  if (T->isIncompleteType()) {
7579  Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7580  return false;
7581  }
7582  if (!T.isTriviallyCopyableType(Info.Ctx)) {
7583  Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7584  return false;
7585  }
7586 
7587  // Figure out how many T's we're copying.
7588  uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7589  if (!WChar) {
7590  uint64_t Remainder;
7591  llvm::APInt OrigN = N;
7592  llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7593  if (Remainder) {
7594  Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7595  << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7596  << (unsigned)TSize;
7597  return false;
7598  }
7599  }
7600 
7601  // Check that the copying will remain within the arrays, just so that we
7602  // can give a more meaningful diagnostic. This implicitly also checks that
7603  // N fits into 64 bits.
7604  uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7605  uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7606  if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7607  Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7608  << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7609  << N.toString(10, /*Signed*/false);
7610  return false;
7611  }
7612  uint64_t NElems = N.getZExtValue();
7613  uint64_t NBytes = NElems * TSize;
7614 
7615  // Check for overlap.
7616  int Direction = 1;
7617  if (HasSameBase(Src, Dest)) {
7618  uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7619  uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7620  if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7621  // Dest is inside the source region.
7622  if (!Move) {
7623  Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7624  return false;
7625  }
7626  // For memmove and friends, copy backwards.
7627  if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7628  !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7629  return false;
7630  Direction = -1;
7631  } else if (!Move && SrcOffset >= DestOffset &&
7632  SrcOffset - DestOffset < NBytes) {
7633  // Src is inside the destination region for memcpy: invalid.
7634  Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7635  return false;
7636  }
7637  }
7638 
7639  while (true) {
7640  APValue Val;
7641  if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7642  !handleAssignment(Info, E, Dest, T, Val))
7643  return false;
7644  // Do not iterate past the last element; if we're copying backwards, that
7645  // might take us off the start of the array.
7646  if (--NElems == 0)
7647  return true;
7648  if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7649  !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7650  return false;
7651  }
7652  }
7653 
7654  default:
7655  return visitNonBuiltinCallExpr(E);
7656  }
7657 }
7658 
7659 //===----------------------------------------------------------------------===//
7660 // Member Pointer Evaluation
7661 //===----------------------------------------------------------------------===//
7662 
7663 namespace {
7664 class MemberPointerExprEvaluator
7665  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7666  MemberPtr &Result;
7667 
7668  bool Success(const ValueDecl *D) {
7669  Result = MemberPtr(D);
7670  return true;
7671  }
7672 public:
7673 
7674  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7675  : ExprEvaluatorBaseTy(Info), Result(Result) {}
7676 
7677  bool Success(const APValue &V, const Expr *E) {
7678  Result.setFrom(V);
7679  return true;
7680  }
7681  bool ZeroInitialization(const Expr *E) {
7682  return Success((const ValueDecl*)nullptr);
7683  }
7684 
7685  bool VisitCastExpr(const CastExpr *E);
7686  bool VisitUnaryAddrOf(const UnaryOperator *E);
7687 };
7688 } // end anonymous namespace
7689 
7690 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7691  EvalInfo &Info) {
7692  assert(E->isRValue() && E->getType()->isMemberPointerType());
7693  return MemberPointerExprEvaluator(Info, Result).Visit(E);
7694 }
7695 
7696 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7697  switch (E->getCastKind()) {
7698  default:
7699  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7700 
7701  case CK_NullToMemberPointer:
7702  VisitIgnoredValue(E->getSubExpr());
7703  return ZeroInitialization(E);
7704 
7705  case CK_BaseToDerivedMemberPointer: {
7706  if (!Visit(E->getSubExpr()))
7707  return false;
7708  if (E->path_empty())
7709  return true;
7710  // Base-to-derived member pointer casts store the path in derived-to-base
7711  // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7712  // the wrong end of the derived->base arc, so stagger the path by one class.
7713  typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7714  for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7715  PathI != PathE; ++PathI) {
7716  assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7717  const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7718  if (!Result.castToDerived(Derived))
7719  return Error(E);
7720  }
7721  const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7722  if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7723  return Error(E);
7724  return true;
7725  }
7726 
7727  case CK_DerivedToBaseMemberPointer:
7728  if (!Visit(E->getSubExpr()))
7729  return false;
7730  for (CastExpr::path_const_iterator PathI = E->path_begin(),
7731  PathE = E->path_end(); PathI != PathE; ++PathI) {
7732  assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7733  const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7734  if (!Result.castToBase(Base))
7735  return Error(E);
7736  }
7737  return true;
7738  }
7739 }
7740 
7741 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7742  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7743  // member can be formed.
7744  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7745 }
7746 
7747 //===----------------------------------------------------------------------===//
7748 // Record Evaluation
7749 //===----------------------------------------------------------------------===//
7750 
7751 namespace {
7752  class RecordExprEvaluator
7753  : public ExprEvaluatorBase<RecordExprEvaluator> {
7754  const LValue &This;
7755  APValue &Result;
7756  public:
7757 
7758  RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7759  : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7760 
7761  bool Success(const APValue &V, const Expr *E) {
7762  Result = V;
7763  return true;
7764  }
7765  bool ZeroInitialization(const Expr *E) {
7766  return ZeroInitialization(E, E->getType());
7767  }
7768  bool ZeroInitialization(const Expr *E, QualType T);
7769 
7770  bool VisitCallExpr(const CallExpr *E) {
7771  return handleCallExpr(E, Result, &This);
7772  }
7773  bool VisitCastExpr(const CastExpr *E);
7774  bool VisitInitListExpr(const InitListExpr *E);
7775  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7776  return VisitCXXConstructExpr(E, E->getType());
7777  }
7778  bool VisitLambdaExpr(const LambdaExpr *E);
7779  bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7780  bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7781  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7782 
7783  bool VisitBinCmp(const BinaryOperator *E);
7784  };
7785 }
7786 
7787 /// Perform zero-initialization on an object of non-union class type.
7788 /// C++11 [dcl.init]p5:
7789 /// To zero-initialize an object or reference of type T means:
7790 /// [...]
7791 /// -- if T is a (possibly cv-qualified) non-union class type,
7792 /// each non-static data member and each base-class subobject is
7793 /// zero-initialized
7794 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7795  const RecordDecl *RD,
7796  const LValue &This, APValue &Result) {
7797  assert(!RD->isUnion() && "Expected non-union class type");
7798  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7799  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7800  std::distance(RD->field_begin(), RD->field_end()));
7801 
7802  if (RD->isInvalidDecl()) return false;
7803  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7804 
7805  if (CD) {
7806  unsigned Index = 0;
7807  for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7808  End = CD->bases_end(); I != End; ++I, ++Index) {
7809  const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7810  LValue Subobject = This;
7811  if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7812  return false;
7813  if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7814  Result.getStructBase(Index)))
7815  return false;
7816  }
7817  }
7818 
7819  for (const auto *I : RD->fields()) {
7820  // -- if T is a reference type, no initialization is performed.
7821  if (I->getType()->isReferenceType())
7822  continue;
7823 
7824  LValue Subobject = This;
7825  if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7826  return false;
7827 
7828  ImplicitValueInitExpr VIE(I->getType());
7829  if (!EvaluateInPlace(
7830  Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7831  return false;
7832  }
7833 
7834  return true;
7835 }
7836 
7837 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7838  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7839  if (RD->isInvalidDecl()) return false;
7840  if (RD->isUnion()) {
7841  // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7842  // object's first non-static named data member is zero-initialized
7844  if (I == RD->field_end()) {
7845  Result = APValue((const FieldDecl*)nullptr);
7846  return true;
7847  }
7848 
7849  LValue Subobject = This;
7850  if (!HandleLValueMember(Info, E, Subobject, *I))
7851  return false;
7852  Result = APValue(*I);
7853  ImplicitValueInitExpr VIE(I->getType());
7854  return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7855  }
7856 
7857  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7858  Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7859  return false;
7860  }
7861 
7862  return HandleClassZeroInitialization(Info, E, RD, This, Result);
7863 }
7864 
7865 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7866  switch (E->getCastKind()) {
7867  default:
7868  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7869 
7870  case CK_ConstructorConversion:
7871  return Visit(E->getSubExpr());
7872 
7873  case CK_DerivedToBase:
7874  case CK_UncheckedDerivedToBase: {
7875  APValue DerivedObject;
7876  if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7877  return false;
7878  if (!DerivedObject.isStruct())
7879  return Error(E->getSubExpr());
7880 
7881  // Derived-to-base rvalue conversion: just slice off the derived part.
7882  APValue *Value = &DerivedObject;
7883  const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7884  for (CastExpr::path_const_iterator PathI = E->path_begin(),
7885  PathE = E->path_end(); PathI != PathE; ++PathI) {
7886  assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7887  const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7888  Value = &Value->getStructBase(getBaseIndex(RD, Base));
7889  RD = Base;
7890  }
7891  Result = *Value;
7892  return true;
7893  }
7894  }
7895 }
7896 
7897 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7898  if (E->isTransparent())
7899  return Visit(E->getInit(0));
7900 
7901  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7902  if (RD->isInvalidDecl()) return false;
7903  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7904  auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7905 
7906  EvalInfo::EvaluatingConstructorRAII EvalObj(
7907  Info,
7908  ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7909  CXXRD && CXXRD->getNumBases());
7910 
7911  if (RD->isUnion()) {
7912  const FieldDecl *Field = E->getInitializedFieldInUnion();
7913  Result = APValue(Field);
7914  if (!Field)
7915  return true;
7916 
7917  // If the initializer list for a union does not contain any elements, the
7918  // first element of the union is value-initialized.
7919  // FIXME: The element should be initialized from an initializer list.
7920  // Is this difference ever observable for initializer lists which
7921  // we don't build?
7922  ImplicitValueInitExpr VIE(Field->getType());
7923  const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7924 
7925  LValue Subobject = This;
7926  if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7927  return false;
7928 
7929  // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7930  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7931  isa<CXXDefaultInitExpr>(InitExpr));
7932 
7933  return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7934  }
7935 
7936  if (!Result.hasValue())
7937  Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7938  std::distance(RD->field_begin(), RD->field_end()));
7939  unsigned ElementNo = 0;
7940  bool Success = true;
7941 
7942  // Initialize base classes.
7943  if (CXXRD && CXXRD->getNumBases()) {
7944  for (const auto &Base : CXXRD->bases()) {
7945  assert(ElementNo < E->getNumInits() && "missing init for base class");
7946  const Expr *Init = E->getInit(ElementNo);
7947 
7948  LValue Subobject = This;
7949  if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7950  return false;
7951 
7952  APValue &FieldVal = Result.getStructBase(ElementNo);
7953  if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7954  if (!Info.noteFailure())
7955  return false;
7956  Success = false;
7957  }
7958  ++ElementNo;
7959  }
7960 
7961  EvalObj.finishedConstructingBases();
7962  }
7963 
7964  // Initialize members.
7965  for (const auto *Field : RD->fields()) {
7966  // Anonymous bit-fields are not considered members of the class for
7967  // purposes of aggregate initialization.
7968  if (Field->isUnnamedBitfield())
7969  continue;
7970 
7971  LValue Subobject = This;
7972 
7973  bool HaveInit = ElementNo < E->getNumInits();
7974 
7975  // FIXME: Diagnostics here should point to the end of the initializer
7976  // list, not the start.
7977  if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7978  Subobject, Field, &Layout))
7979  return false;
7980 
7981  // Perform an implicit value-initialization for members beyond the end of
7982  // the initializer list.
7983  ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7984  const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7985 
7986  // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7987  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7988  isa<CXXDefaultInitExpr>(Init));
7989 
7990  APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7991  if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7992  (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7993  FieldVal, Field))) {
7994  if (!Info.noteFailure())
7995  return false;
7996  Success = false;
7997  }
7998  }
7999 
8000  return Success;
8001 }
8002 
8003 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8004  QualType T) {
8005  // Note that E's type is not necessarily the type of our class here; we might
8006  // be initializing an array element instead.
8007  const CXXConstructorDecl *FD = E->getConstructor();
8008  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8009 
8010  bool ZeroInit = E->requiresZeroInitialization();
8011  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
8012  // If we've already performed zero-initialization, we're already done.
8013  if (Result.hasValue())
8014  return true;
8015 
8016  // We can get here in two different ways:
8017  // 1) We're performing value-initialization, and should zero-initialize
8018  // the object, or
8019  // 2) We're performing default-initialization of an object with a trivial
8020  // constexpr default constructor, in which case we should start the
8021  // lifetimes of all the base subobjects (there can be no data member
8022  // subobjects in this case) per [basic.life]p1.
8023  // Either way, ZeroInitialization is appropriate.
8024  return ZeroInitialization(E, T);
8025  }
8026 
8027  const FunctionDecl *Definition = nullptr;
8028  auto Body = FD->getBody(Definition);
8029 
8030  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8031  return false;
8032 
8033  // Avoid materializing a temporary for an elidable copy/move constructor.
8034  if (E->isElidable() && !ZeroInit)
8035  if (const MaterializeTemporaryExpr *ME
8036  = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8037  return Visit(ME->GetTemporaryExpr());
8038 
8039  if (ZeroInit && !ZeroInitialization(E, T))
8040  return false;
8041 
8042  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
8043  return HandleConstructorCall(E, This, Args,
8044  cast<CXXConstructorDecl>(Definition), Info,
8045  Result);
8046 }
8047 
8048 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8049  const CXXInheritedCtorInitExpr *E) {
8050  if (!Info.CurrentCall) {
8051  assert(Info.checkingPotentialConstantExpression());
8052  return false;
8053  }
8054 
8055  const CXXConstructorDecl *FD = E->getConstructor();
8056  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8057  return false;
8058 
8059  const FunctionDecl *Definition = nullptr;
8060  auto Body = FD->getBody(Definition);
8061 
8062  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8063  return false;
8064 
8065  return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
8066  cast<CXXConstructorDecl>(Definition), Info,
8067  Result);
8068 }
8069 
8070 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8071  const CXXStdInitializerListExpr *E) {
8072  const ConstantArrayType *ArrayType =
8073  Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8074 
8075  LValue Array;
8076  if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8077  return false;
8078 
8079  // Get a pointer to the first element of the array.
8080  Array.addArray(Info, E, ArrayType);
8081 
8082  // FIXME: Perform the checks on the field types in SemaInit.
8083  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8084  RecordDecl::field_iterator Field = Record->field_begin();
8085  if (Field == Record->field_end())
8086  return Error(E);
8087 
8088  // Start pointer.
8089  if (!Field->getType()->isPointerType() ||
8090  !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8091  ArrayType->getElementType()))
8092  return Error(E);
8093 
8094  // FIXME: What if the initializer_list type has base classes, etc?
8095  Result = APValue(APValue::UninitStruct(), 0, 2);
8096  Array.moveInto(Result.getStructField(0));
8097 
8098  if (++Field == Record->field_end())
8099  return Error(E);
8100 
8101  if (Field->getType()->isPointerType() &&
8102  Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8103  ArrayType->getElementType())) {
8104  // End pointer.
8105  if (!HandleLValueArrayAdjustment(Info, E, Array,
8106  ArrayType->getElementType(),
8107  ArrayType->getSize().getZExtValue()))
8108  return false;
8109  Array.moveInto(Result.getStructField(1));
8110  } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8111  // Length.
8112  Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8113  else
8114  return Error(E);
8115 
8116  if (++Field != Record->field_end())
8117  return Error(E);
8118 
8119  return true;
8120 }
8121 
8122 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8123  const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8124  if (ClosureClass->isInvalidDecl()) return false;
8125 
8126  if (Info.checkingPotentialConstantExpression()) return true;
8127 
8128  const size_t NumFields =
8129  std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8130 
8131  assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8132  E->capture_init_end()) &&
8133  "The number of lambda capture initializers should equal the number of "
8134  "fields within the closure type");
8135 
8136  Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8137  // Iterate through all the lambda's closure object's fields and initialize
8138  // them.
8139  auto *CaptureInitIt = E->capture_init_begin();
8140  const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8141  bool Success = true;
8142  for (const auto *Field : ClosureClass->fields()) {
8143  assert(CaptureInitIt != E->capture_init_end());
8144  // Get the initializer for this field
8145  Expr *const CurFieldInit = *CaptureInitIt++;
8146 
8147  // If there is no initializer, either this is a VLA or an error has
8148  // occurred.
8149  if (!CurFieldInit)
8150  return Error(E);
8151 
8152  APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8153  if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8154  if (!Info.keepEvaluatingAfterFailure())
8155  return false;
8156  Success = false;
8157  }
8158  ++CaptureIt;
8159  }
8160  return Success;
8161 }
8162 
8163 static bool EvaluateRecord(const Expr *E, const LValue &This,
8164  APValue &Result, EvalInfo &Info) {
8165  assert(E->isRValue() && E->getType()->isRecordType() &&
8166  "can't evaluate expression as a record rvalue");
8167  return RecordExprEvaluator(Info, This, Result).Visit(E);
8168 }
8169 
8170 //===----------------------------------------------------------------------===//
8171 // Temporary Evaluation
8172 //
8173 // Temporaries are represented in the AST as rvalues, but generally behave like
8174 // lvalues. The full-object of which the temporary is a subobject is implicitly
8175 // materialized so that a reference can bind to it.
8176 //===----------------------------------------------------------------------===//
8177 namespace {
8178 class TemporaryExprEvaluator
8179  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8180 public:
8181  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8182  LValueExprEvaluatorBaseTy(Info, Result, false) {}
8183 
8184  /// Visit an expression which constructs the value of this temporary.
8185  bool VisitConstructExpr(const Expr *E) {
8186  APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8187  return EvaluateInPlace(Value, Info, Result, E);
8188  }
8189 
8190  bool VisitCastExpr(const CastExpr *E) {
8191  switch (E->getCastKind()) {
8192  default:
8193  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8194 
8195  case CK_ConstructorConversion:
8196  return VisitConstructExpr(E->getSubExpr());
8197  }
8198  }
8199  bool VisitInitListExpr(const InitListExpr *E) {
8200  return VisitConstructExpr(E);
8201  }
8202  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8203  return VisitConstructExpr(E);
8204  }
8205  bool VisitCallExpr(const CallExpr *E) {
8206  return VisitConstructExpr(E);
8207  }
8208  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8209  return VisitConstructExpr(E);
8210  }
8211  bool VisitLambdaExpr(const LambdaExpr *E) {
8212  return VisitConstructExpr(E);
8213  }
8214 };
8215 } // end anonymous namespace
8216 
8217 /// Evaluate an expression of record type as a temporary.
8218 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8219  assert(E->isRValue() && E->getType()->isRecordType());
8220  return TemporaryExprEvaluator(Info, Result).Visit(E);
8221 }
8222 
8223 //===----------------------------------------------------------------------===//
8224 // Vector Evaluation
8225 //===----------------------------------------------------------------------===//
8226 
8227 namespace {
8228  class VectorExprEvaluator
8229  : public ExprEvaluatorBase<VectorExprEvaluator> {
8230  APValue &Result;
8231  public:
8232 
8233  VectorExprEvaluator(EvalInfo &info, APValue &Result)
8234  : ExprEvaluatorBaseTy(info), Result(Result) {}
8235 
8236  bool Success(ArrayRef<APValue> V, const Expr *E) {
8237  assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8238  // FIXME: remove this APValue copy.
8239  Result = APValue(V.data(), V.size());
8240  return true;
8241  }
8242  bool Success(const APValue &V, const Expr *E) {
8243  assert(V.isVector());
8244  Result = V;
8245  return true;
8246  }
8247  bool ZeroInitialization(const Expr *E);
8248 
8249  bool VisitUnaryReal(const UnaryOperator *E)
8250  { return Visit(E->getSubExpr()); }
8251  bool VisitCastExpr(const CastExpr* E);
8252  bool VisitInitListExpr(const InitListExpr *E);
8253  bool VisitUnaryImag(const UnaryOperator *E);
8254  // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8255  // binary comparisons, binary and/or/xor,
8256  // shufflevector, ExtVectorElementExpr
8257  };
8258 } // end anonymous namespace
8259 
8260 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8261  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
8262  return VectorExprEvaluator(Info, Result).Visit(E);
8263 }
8264 
8265 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8266  const VectorType *VTy = E->getType()->castAs<VectorType>();
8267  unsigned NElts = VTy->getNumElements();
8268 
8269  const Expr *SE = E->getSubExpr();
8270  QualType SETy = SE->getType();
8271 
8272  switch (E->getCastKind()) {
8273  case CK_VectorSplat: {
8274  APValue Val = APValue();
8275  if (SETy->isIntegerType()) {
8276  APSInt IntResult;
8277  if (!EvaluateInteger(SE, IntResult, Info))
8278  return false;
8279  Val = APValue(std::move(IntResult));
8280  } else if (SETy->isRealFloatingType()) {
8281  APFloat FloatResult(0.0);
8282  if (!EvaluateFloat(SE, FloatResult, Info))
8283  return false;
8284  Val = APValue(std::move(FloatResult));
8285  } else {
8286  return Error(E);
8287  }
8288 
8289  // Splat and create vector APValue.
8290  SmallVector<APValue, 4> Elts(NElts, Val);
8291  return Success(Elts, E);
8292  }
8293  case CK_BitCast: {
8294  // Evaluate the operand into an APInt we can extract from.
8295  llvm::APInt SValInt;
8296  if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8297  return false;
8298  // Extract the elements
8299  QualType EltTy = VTy->getElementType();
8300  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8301  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8303  if (EltTy->isRealFloatingType()) {
8304  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8305  unsigned FloatEltSize = EltSize;
8306  if (&Sem == &APFloat::x87DoubleExtended())
8307  FloatEltSize = 80;
8308  for (unsigned i = 0; i < NElts; i++) {
8309  llvm::APInt Elt;
8310  if (BigEndian)
8311  Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8312  else
8313  Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8314  Elts.push_back(APValue(APFloat(Sem, Elt)));
8315  }
8316  } else if (EltTy->isIntegerType()) {
8317  for (unsigned i = 0; i < NElts; i++) {
8318  llvm::APInt Elt;
8319  if (BigEndian)
8320  Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8321  else
8322  Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8323  Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8324  }
8325  } else {
8326  return Error(E);
8327  }
8328  return Success(Elts, E);
8329  }
8330  default:
8331  return ExprEvaluatorBaseTy::VisitCastExpr(E);
8332  }
8333 }
8334 
8335 bool
8336 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8337  const VectorType *VT = E->getType()->castAs<VectorType>();
8338  unsigned NumInits = E->getNumInits();
8339  unsigned NumElements = VT->getNumElements();
8340 
8341  QualType EltTy = VT->getElementType();
8342  SmallVector<APValue, 4> Elements;
8343 
8344  // The number of initializers can be less than the number of
8345  // vector elements. For OpenCL, this can be due to nested vector
8346  // initialization. For GCC compatibility, missing trailing elements
8347  // should be initialized with zeroes.
8348  unsigned CountInits = 0, CountElts = 0;
8349  while (CountElts < NumElements) {
8350  // Handle nested vector initialization.
8351  if (CountInits < NumInits
8352  && E->getInit(CountInits)->getType()->isVectorType()) {
8353  APValue v;
8354  if (!EvaluateVector(E->getInit(CountInits), v, Info))
8355  return Error(E);
8356  unsigned vlen = v.getVectorLength();
8357  for (unsigned j = 0; j < vlen; j++)
8358  Elements.push_back(v.getVectorElt(j));
8359  CountElts += vlen;
8360  } else if (EltTy->isIntegerType()) {
8361  llvm::APSInt sInt(32);
8362  if (CountInits < NumInits) {
8363  if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
8364  return false;
8365  } else // trailing integer zero.
8366  sInt = Info.Ctx.MakeIntValue(0, EltTy);
8367  Elements.push_back(APValue(sInt));
8368  CountElts++;
8369  } else {
8370  llvm::APFloat f(0.0);
8371  if (CountInits < NumInits) {
8372  if (!EvaluateFloat(E->getInit(CountInits), f, Info))
8373  return false;
8374  } else // trailing float zero.
8375  f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8376  Elements.push_back(APValue(f));
8377  CountElts++;
8378  }
8379  CountInits++;
8380  }
8381  return Success(Elements, E);
8382 }
8383 
8384 bool
8385 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
8386  const VectorType *VT = E->getType()->getAs<VectorType>();
8387  QualType EltTy = VT->getElementType();
8388  APValue ZeroElement;
8389  if (EltTy->isIntegerType())
8390  ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8391  else
8392  ZeroElement =
8393  APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8394 
8395  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
8396  return Success(Elements, E);
8397 }
8398 
8399 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8400  VisitIgnoredValue(E->getSubExpr());
8401  return ZeroInitialization(E);
8402 }
8403 
8404 //===----------------------------------------------------------------------===//
8405 // Array Evaluation
8406 //===----------------------------------------------------------------------===//
8407 
8408 namespace {
8409  class ArrayExprEvaluator
8410  : public ExprEvaluatorBase<ArrayExprEvaluator> {
8411  const LValue &This;
8412  APValue &Result;
8413  public:
8414 
8415  ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8416  : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
8417 
8418  bool Success(const APValue &V, const Expr *E) {
8419  assert(V.isArray() && "expected array");
8420  Result = V;
8421  return true;
8422  }
8423 
8424  bool ZeroInitialization(const Expr *E) {
8425  const ConstantArrayType *CAT =
8426  Info.Ctx.getAsConstantArrayType(E->getType());
8427  if (!CAT)
8428  return Error(E);
8429 
8430  Result = APValue(APValue::UninitArray(), 0,
8431  CAT->getSize().getZExtValue());
8432  if (!Result.hasArrayFiller()) return true;
8433 
8434  // Zero-initialize all elements.
8435  LValue Subobject = This;
8436  Subobject.addArray(Info, E, CAT);
8438  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
8439  }
8440 
8441  bool VisitCallExpr(const CallExpr *E) {
8442  return handleCallExpr(E, Result, &This);
8443  }
8444  bool VisitInitListExpr(const InitListExpr *E);
8445  bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
8446  bool VisitCXXConstructExpr(const CXXConstructExpr *E);
8447  bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8448  const LValue &Subobject,
8449  APValue *Value, QualType Type);
8450  bool VisitStringLiteral(const StringLiteral *E) {
8451  expandStringLiteral(Info, E, Result);
8452  return true;
8453  }
8454  };
8455 } // end anonymous namespace
8456 
8457 static bool EvaluateArray(const Expr *E, const LValue &This,
8458  APValue &Result, EvalInfo &Info) {
8459  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
8460  return ArrayExprEvaluator(Info, This, Result).Visit(E);
8461 }
8462 
8463 // Return true iff the given array filler may depend on the element index.
8464 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8465  // For now, just whitelist non-class value-initialization and initialization
8466  // lists comprised of them.
8467  if (isa<ImplicitValueInitExpr>(FillerExpr))
8468  return false;
8469  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8470  for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8471  if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8472  return true;
8473  }
8474  return false;
8475  }
8476  return true;
8477 }
8478 
8479 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8480  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8481  if (!CAT)
8482  return Error(E);
8483 
8484  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8485  // an appropriately-typed string literal enclosed in braces.
8486  if (E->isStringLiteralInit())
8487  return Visit(E->getInit(0));
8488 
8489  bool Success = true;
8490 
8491  assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8492  "zero-initialized array shouldn't have any initialized elts");
8493  APValue Filler;
8494  if (Result.isArray() && Result.hasArrayFiller())
8495  Filler = Result.getArrayFiller();
8496 
8497  unsigned NumEltsToInit = E->getNumInits();
8498  unsigned NumElts = CAT->getSize().getZExtValue();
8499  const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8500 
8501  // If the initializer might depend on the array index, run it for each
8502  // array element.
8503  if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8504  NumEltsToInit = NumElts;
8505 
8506  LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8507  << NumEltsToInit << ".\n");
8508 
8509  Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8510 
8511  // If the array was previously zero-initialized, preserve the
8512  // zero-initialized values.
8513  if (Filler.hasValue()) {
8514  for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8515  Result.getArrayInitializedElt(I) = Filler;
8516  if (Result.hasArrayFiller())
8517  Result.getArrayFiller() = Filler;
8518  }
8519 
8520  LValue Subobject = This;
8521  Subobject.addArray(Info, E, CAT);
8522  for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8523  const Expr *Init =
8524  Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8525  if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8526  Info, Subobject, Init) ||
8527  !HandleLValueArrayAdjustment(Info, Init, Subobject,
8528  CAT->getElementType(), 1)) {
8529  if (!Info.noteFailure())
8530  return false;
8531  Success = false;
8532  }
8533  }
8534 
8535  if (!Result.hasArrayFiller())
8536  return Success;
8537 
8538  // If we get here, we have a trivial filler, which we can just evaluate
8539  // once and splat over the rest of the array elements.
8540  assert(FillerExpr && "no array filler for incomplete init list");
8541  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8542  FillerExpr) && Success;
8543 }
8544 
8545 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8546  if (E->getCommonExpr() &&
8547  !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8548  Info, E->getCommonExpr()->getSourceExpr()))
8549  return false;
8550 
8551  auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8552 
8553  uint64_t Elements = CAT->getSize().getZExtValue();
8554  Result = APValue(APValue::UninitArray(), Elements, Elements);
8555 
8556  LValue Subobject = This;
8557  Subobject.addArray(Info, E, CAT);
8558 
8559  bool Success = true;
8560  for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8561  if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8562  Info, Subobject, E->getSubExpr()) ||
8563  !HandleLValueArrayAdjustment(Info, E, Subobject,
8564  CAT->getElementType(), 1)) {
8565  if (!Info.noteFailure())
8566  return false;
8567  Success = false;
8568  }
8569  }
8570 
8571  return Success;
8572 }
8573 
8574 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8575  return VisitCXXConstructExpr(E, This, &Result, E->getType());
8576 }
8577 
8578 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8579  const LValue &Subobject,
8580  APValue *Value,
8581  QualType Type) {
8582  bool HadZeroInit = Value->hasValue();
8583 
8584  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8585  unsigned N = CAT->getSize().getZExtValue();
8586 
8587  // Preserve the array filler if we had prior zero-initialization.
8588  APValue Filler =
8589  HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8590  : APValue();
8591 
8592  *Value = APValue(APValue::UninitArray(), N, N);
8593 
8594  if (HadZeroInit)
8595  for (unsigned I = 0; I != N; ++I)
8596  Value->getArrayInitializedElt(I) = Filler;
8597 
8598  // Initialize the elements.
8599  LValue ArrayElt = Subobject;
8600  ArrayElt.addArray(Info, E, CAT);
8601  for (unsigned I = 0; I != N; ++I)
8602  if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8603  CAT->getElementType()) ||
8604  !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8605  CAT->getElementType(), 1))
8606  return false;
8607 
8608  return true;
8609  }
8610 
8611  if (!Type->isRecordType())
8612  return Error(E);
8613 
8614  return RecordExprEvaluator(Info, Subobject, *Value)
8615  .VisitCXXConstructExpr(E, Type);
8616 }
8617 
8618 //===----------------------------------------------------------------------===//
8619 // Integer Evaluation
8620 //
8621 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8622 // types and back in constant folding. Integer values are thus represented
8623 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8624 //===----------------------------------------------------------------------===//
8625 
8626 namespace {
8627 class IntExprEvaluator
8628  : public ExprEvaluatorBase<IntExprEvaluator> {
8629  APValue &Result;
8630 public:
8631  IntExprEvaluator(EvalInfo &info, APValue &result)
8632  : ExprEvaluatorBaseTy(info), Result(result) {}
8633 
8634  bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8635  assert(E->getType()->isIntegralOrEnumerationType() &&
8636  "Invalid evaluation result.");
8637  assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8638  "Invalid evaluation result.");
8639  assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8640  "Invalid evaluation result.");
8641  Result = APValue(SI);
8642  return true;
8643  }
8644  bool Success(const llvm::APSInt &SI, const Expr *E) {
8645  return Success(SI, E, Result);
8646  }
8647 
8648  bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8649  assert(E->getType()->isIntegralOrEnumerationType() &&
8650  "Invalid evaluation result.");
8651  assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8652  "Invalid evaluation result.");
8653  Result = APValue(APSInt(I));
8654  Result.getInt().setIsUnsigned(
8656  return true;
8657  }
8658  bool Success(const llvm::APInt &I, const Expr *E) {
8659  return Success(I, E, Result);
8660  }
8661 
8662  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8663  assert(E->getType()->isIntegralOrEnumerationType() &&
8664  "Invalid evaluation result.");
8665  Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8666  return true;
8667  }
8668  bool Success(uint64_t Value, const Expr *E) {
8669  return Success(Value, E, Result);
8670  }
8671 
8672  bool Success(CharUnits Size, const Expr *E) {
8673  return Success(Size.getQuantity(), E);
8674  }
8675 
8676  bool Success(const APValue &V, const Expr *E) {
8677  if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
8678  Result = V;
8679  return true;
8680  }
8681  return Success(V.getInt(), E);
8682  }
8683 
8684  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8685 
8686  //===--------------------------------------------------------------------===//
8687  // Visitor Methods
8688  //===--------------------------------------------------------------------===//
8689 
8690  bool VisitConstantExpr(const ConstantExpr *E);
8691 
8692  bool VisitIntegerLiteral(const IntegerLiteral *E) {
8693  return Success(E->getValue(), E);
8694  }
8695  bool VisitCharacterLiteral(const CharacterLiteral *E) {
8696  return Success(E->getValue(), E);
8697  }
8698 
8699  bool CheckReferencedDecl(const Expr *E, const Decl *D);
8700  bool VisitDeclRefExpr(const DeclRefExpr *E) {
8701  if (CheckReferencedDecl(E, E->getDecl()))
8702  return true;
8703 
8704  return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8705  }
8706  bool VisitMemberExpr(const MemberExpr *E) {
8707  if (CheckReferencedDecl(E, E->getMemberDecl())) {
8708  VisitIgnoredBaseExpression(E->getBase());
8709  return true;
8710  }
8711 
8712  return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8713  }
8714 
8715  bool VisitCallExpr(const CallExpr *E);
8716  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8717  bool VisitBinaryOperator(const BinaryOperator *E);
8718  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8719  bool VisitUnaryOperator(const UnaryOperator *E);
8720 
8721  bool VisitCastExpr(const CastExpr* E);
8722  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8723 
8724  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8725  return Success(E->getValue(), E);
8726  }
8727 
8728  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8729  return Success(E->getValue(), E);
8730  }
8731 
8732  bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8733  if (Info.ArrayInitIndex == uint64_t(-1)) {
8734  // We were asked to evaluate this subexpression independent of the
8735  // enclosing ArrayInitLoopExpr. We can't do that.
8736  Info.FFDiag(E);
8737  return false;
8738  }
8739  return Success(Info.ArrayInitIndex, E);
8740  }
8741 
8742  // Note, GNU defines __null as an integer, not a pointer.
8743  bool VisitGNUNullExpr(const GNUNullExpr *E) {
8744  return ZeroInitialization(E);
8745  }
8746 
8747  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8748  return Success(E->getValue(), E);
8749  }
8750 
8751  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8752  return Success(E->getValue(), E);
8753  }
8754 
8755  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8756  return Success(E->getValue(), E);
8757  }
8758 
8759  bool VisitUnaryReal(const UnaryOperator *E);
8760  bool VisitUnaryImag(const UnaryOperator *E);
8761 
8762  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8763  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8764  bool VisitSourceLocExpr(const SourceLocExpr *E);
8765  // FIXME: Missing: array subscript of vector, member of vector
8766 };
8767 
8768 class FixedPointExprEvaluator
8769  : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8770  APValue &Result;
8771 
8772  public:
8773  FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8774  : ExprEvaluatorBaseTy(info), Result(result) {}
8775 
8776  bool Success(const llvm::APInt &I, const Expr *E) {
8777  return Success(
8778  APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8779  }
8780 
8781  bool Success(uint64_t Value, const Expr *E) {
8782  return Success(
8783  APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8784  }
8785 
8786  bool Success(const APValue &V, const Expr *E) {
8787  return Success(V.getFixedPoint(), E);
8788  }
8789 
8790  bool Success(const APFixedPoint &V, const Expr *E) {
8791  assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8792  assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8793  "Invalid evaluation result.");
8794  Result = APValue(V);
8795  return true;
8796  }
8797 
8798  //===--------------------------------------------------------------------===//
8799  // Visitor Methods
8800  //===--------------------------------------------------------------------===//
8801 
8802  bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8803  return Success(E->getValue(), E);
8804  }
8805 
8806  bool VisitCastExpr(const CastExpr *E);
8807  bool VisitUnaryOperator(const UnaryOperator *E);
8808  bool VisitBinaryOperator(const BinaryOperator *E);
8809 };
8810 } // end anonymous namespace
8811 
8812 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8813 /// produce either the integer value or a pointer.
8814 ///
8815 /// GCC has a heinous extension which folds casts between pointer types and
8816 /// pointer-sized integral types. We support this by allowing the evaluation of
8817 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8818 /// Some simple arithmetic on such values is supported (they are treated much
8819 /// like char*).
8820 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8821  EvalInfo &Info) {
8822  assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8823  return IntExprEvaluator(Info, Result).Visit(E);
8824 }
8825 
8826 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8827  APValue Val;
8828  if (!EvaluateIntegerOrLValue(E, Val, Info))
8829  return false;
8830  if (!Val.isInt()) {
8831  // FIXME: It would be better to produce the diagnostic for casting
8832  // a pointer to an integer.
8833  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8834  return false;
8835  }
8836  Result = Val.getInt();
8837  return true;
8838 }
8839 
8840 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8841  APValue Evaluated = E->EvaluateInContext(
8842  Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8843  return Success(Evaluated, E);
8844 }
8845 
8846 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8847  EvalInfo &Info) {
8848  if (E->getType()->isFixedPointType()) {
8849  APValue Val;
8850  if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8851  return false;
8852  if (!Val.isFixedPoint())
8853  return false;
8854 
8855  Result = Val.getFixedPoint();
8856  return true;
8857  }
8858  return false;
8859 }
8860 
8861 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8862  EvalInfo &Info) {
8863  if (E->getType()->isIntegerType()) {
8864  auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8865  APSInt Val;
8866  if (!EvaluateInteger(E, Val, Info))
8867  return false;
8868  Result = APFixedPoint(Val, FXSema);
8869  return true;
8870  } else if (E->getType()->isFixedPointType()) {
8871  return EvaluateFixedPoint(E, Result, Info);
8872  }
8873  return false;
8874 }
8875 
8876 /// Check whether the given declaration can be directly converted to an integral
8877 /// rvalue. If not, no diagnostic is produced; there are other things we can
8878 /// try.
8879 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8880  // Enums are integer constant exprs.
8881  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8882  // Check for signedness/width mismatches between E type and ECD value.
8883  bool SameSign = (ECD->getInitVal().isSigned()
8885  bool SameWidth = (ECD->getInitVal().getBitWidth()
8886  == Info.Ctx.getIntWidth(E->getType()));
8887  if (SameSign && SameWidth)
8888  return Success(ECD->getInitVal(), E);
8889  else {
8890  // Get rid of mismatch (otherwise Success assertions will fail)
8891  // by computing a new value matching the type of E.
8892  llvm::APSInt Val = ECD->getInitVal();
8893  if (!SameSign)
8894  Val.setIsSigned(!ECD->getInitVal().isSigned());
8895  if (!SameWidth)
8896  Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8897  return Success(Val, E);
8898  }
8899  }
8900  return false;
8901 }
8902 
8903 /// Values returned by __builtin_classify_type, chosen to match the values
8904 /// produced by GCC's builtin.
8905 enum class GCCTypeClass {
8906  None = -1,
8907  Void = 0,
8908  Integer = 1,
8909  // GCC reserves 2 for character types, but instead classifies them as
8910  // integers.
8911  Enum = 3,
8912  Bool = 4,
8913  Pointer = 5,
8914  // GCC reserves 6 for references, but appears to never use it (because
8915  // expressions never have reference type, presumably).
8916  PointerToDataMember = 7,
8917  RealFloat = 8,
8918  Complex = 9,
8919  // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8920  // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8921  // GCC claims to reserve 11 for pointers to member functions, but *actually*
8922  // uses 12 for that purpose, same as for a class or struct. Maybe it
8923  // internally implements a pointer to member as a struct? Who knows.
8924  PointerToMemberFunction = 12, // Not a bug, see above.
8925  ClassOrStruct = 12,
8926  Union = 13,
8927  // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8928  // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8929  // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8930  // literals.
8931 };
8932 
8933 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8934 /// as GCC.
8935 static GCCTypeClass
8937  assert(!T->isDependentType() && "unexpected dependent type");
8938 
8939  QualType CanTy = T.getCanonicalType();
8940  const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8941 
8942  switch (CanTy->getTypeClass()) {
8943 #define TYPE(ID, BASE)
8944 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8945 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8947 #include "clang/AST/TypeNodes.def"
8948  case Type::Auto:
8949  case Type::DeducedTemplateSpecialization:
8950  llvm_unreachable("unexpected non-canonical or dependent type");
8951 
8952  case Type::Builtin:
8953  switch (BT->getKind()) {
8954 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8955 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8956  case BuiltinType::ID: return GCCTypeClass::Integer;
8957 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8958  case BuiltinType::ID: return GCCTypeClass::RealFloat;
8959 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8960  case BuiltinType::ID: break;
8961 #include "clang/AST/BuiltinTypes.def"
8962  case BuiltinType::Void:
8963  return GCCTypeClass::Void;
8964 
8965  case BuiltinType::Bool:
8966  return GCCTypeClass::Bool;
8967 
8968  case BuiltinType::Char_U:
8969  case BuiltinType::UChar:
8970  case BuiltinType::WChar_U:
8971  case BuiltinType::Char8:
8972  case BuiltinType::Char16:
8973  case BuiltinType::Char32:
8974  case BuiltinType::UShort:
8975  case BuiltinType::UInt:
8976  case BuiltinType::ULong:
8977  case BuiltinType::ULongLong:
8978  case BuiltinType::UInt128:
8979  return GCCTypeClass::Integer;
8980 
8981  case BuiltinType::UShortAccum:
8982  case BuiltinType::UAccum:
8983  case BuiltinType::ULongAccum:
8984  case BuiltinType::UShortFract:
8985  case BuiltinType::UFract:
8986  case BuiltinType::ULongFract:
8987  case BuiltinType::SatUShortAccum:
8988  case BuiltinType::SatUAccum:
8989  case BuiltinType::SatULongAccum:
8990  case BuiltinType::SatUShortFract:
8991  case BuiltinType::SatUFract:
8992  case BuiltinType::SatULongFract:
8993  return GCCTypeClass::None;
8994 
8995  case BuiltinType::NullPtr:
8996 
8997  case BuiltinType::ObjCId:
8998  case BuiltinType::ObjCClass:
8999  case BuiltinType::ObjCSel:
9000 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9001  case BuiltinType::Id:
9002 #include "clang/Basic/OpenCLImageTypes.def"
9003 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9004  case BuiltinType::Id:
9005 #include "clang/Basic/OpenCLExtensionTypes.def"
9006  case BuiltinType::OCLSampler:
9007  case BuiltinType::OCLEvent:
9008  case BuiltinType::OCLClkEvent:
9009  case BuiltinType::OCLQueue:
9010  case BuiltinType::OCLReserveID:
9011  return GCCTypeClass::None;
9012 
9013  case BuiltinType::Dependent:
9014  llvm_unreachable("unexpected dependent type");
9015  };
9016  llvm_unreachable("unexpected placeholder type");
9017 
9018  case Type::Enum:
9019  return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
9020 
9021  case Type::Pointer:
9022  case Type::ConstantArray:
9023  case Type::VariableArray:
9024  case Type::IncompleteArray:
9025  case Type::FunctionNoProto:
9026  case Type::FunctionProto:
9027  return GCCTypeClass::Pointer;
9028 
9029  case Type::MemberPointer:
9030  return CanTy->isMemberDataPointerType()
9033 
9034  case Type::Complex:
9035  return GCCTypeClass::Complex;
9036 
9037  case Type::Record:
9038  return CanTy->isUnionType() ? GCCTypeClass::Union
9040 
9041  case Type::Atomic:
9042  // GCC classifies _Atomic T the same as T.
9044  CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9045 
9046  case Type::BlockPointer:
9047  case Type::Vector:
9048  case Type::ExtVector:
9049  case Type::ObjCObject:
9050  case Type::ObjCInterface:
9051  case Type::ObjCObjectPointer:
9052  case Type::Pipe:
9053  // GCC classifies vectors as None. We follow its lead and classify all
9054  // other types that don't fit into the regular classification the same way.
9055  return GCCTypeClass::None;
9056 
9057  case Type::LValueReference:
9058  case Type::RValueReference:
9059  llvm_unreachable("invalid type for expression");
9060  }
9061 
9062  llvm_unreachable("unexpected type class");
9063 }
9064 
9065 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9066 /// as GCC.
9067 static GCCTypeClass
9069  // If no argument was supplied, default to None. This isn't
9070  // ideal, however it is what gcc does.
9071  if (E->getNumArgs() == 0)
9072  return GCCTypeClass::None;
9073 
9074  // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9075  // being an ICE, but still folds it to a constant using the type of the first
9076  // argument.
9077  return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9078 }
9079 
9080 /// EvaluateBuiltinConstantPForLValue - Determine the result of
9081 /// __builtin_constant_p when applied to the given pointer.
9082 ///
9083 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
9084 /// or it points to the first character of a string literal.
9086  APValue::LValueBase Base = LV.getLValueBase();
9087  if (Base.isNull()) {
9088  // A null base is acceptable.
9089  return true;
9090  } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9091  if (!isa<StringLiteral>(E))
9092  return false;
9093  return LV.getLValueOffset().isZero();
9094  } else if (Base.is<TypeInfoLValue>()) {
9095  // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9096  // evaluate to true.
9097  return true;
9098  } else {
9099  // Any other base is not constant enough for GCC.
9100  return false;
9101  }
9102 }
9103 
9104 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9105 /// GCC as we can manage.
9106 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9107  // This evaluation is not permitted to have side-effects, so evaluate it in
9108  // a speculative evaluation context.
9109  SpeculativeEvaluationRAII SpeculativeEval(Info);
9110 
9111  // Constant-folding is always enabled for the operand of __builtin_constant_p
9112  // (even when the enclosing evaluation context otherwise requires a strict
9113  // language-specific constant expression).
9114  FoldConstant Fold(Info, true);
9115 
9116  QualType ArgType = Arg->getType();
9117 
9118  // __builtin_constant_p always has one operand. The rules which gcc follows
9119  // are not precisely documented, but are as follows:
9120  //
9121  // - If the operand is of integral, floating, complex or enumeration type,
9122  // and can be folded to a known value of that type, it returns 1.
9123  // - If the operand can be folded to a pointer to the first character
9124  // of a string literal (or such a pointer cast to an integral type)
9125  // or to a null pointer or an integer cast to a pointer, it returns 1.
9126  //
9127  // Otherwise, it returns 0.
9128  //
9129  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9130  // its support for this did not work prior to GCC 9 and is not yet well
9131  // understood.
9132  if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9133  ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9134  ArgType->isNullPtrType()) {
9135  APValue V;
9136  if (!::EvaluateAsRValue(Info, Arg, V)) {
9137  Fold.keepDiagnostics();
9138  return false;
9139  }
9140 
9141  // For a pointer (possibly cast to integer), there are special rules.
9142  if (V.getKind() == APValue::LValue)
9144 
9145  // Otherwise, any constant value is good enough.
9146  return V.hasValue();
9147  }
9148 
9149  // Anything else isn't considered to be sufficiently constant.
9150  return false;
9151 }
9152 
9153 /// Retrieves the "underlying object type" of the given expression,
9154 /// as used by __builtin_object_size.
9156  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9157  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9158  return VD->getType();
9159  } else if (const Expr *E = B.get<const Expr*>()) {
9160  if (isa<CompoundLiteralExpr>(E))
9161  return E->getType();
9162  } else if (B.is<TypeInfoLValue>()) {
9163  return B.getTypeInfoType();
9164  }
9165 
9166  return QualType();
9167 }
9168 
9169 /// A more selective version of E->IgnoreParenCasts for
9170 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9171 /// to change the type of E.
9172 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9173 ///
9174 /// Always returns an RValue with a pointer representation.
9175 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9176  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9177 
9178  auto *NoParens = E->IgnoreParens();
9179  auto *Cast = dyn_cast<CastExpr>(NoParens);
9180  if (Cast == nullptr)
9181  return NoParens;
9182 
9183  // We only conservatively allow a few kinds of casts, because this code is
9184  // inherently a simple solution that seeks to support the common case.
9185  auto CastKind = Cast->getCastKind();
9186  if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9187  CastKind != CK_AddressSpaceConversion)
9188  return NoParens;
9189 
9190  auto *SubExpr = Cast->getSubExpr();
9191  if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9192  return NoParens;
9193  return ignorePointerCastsAndParens(SubExpr);
9194 }
9195 
9196 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9197 /// record layout. e.g.
9198 /// struct { struct { int a, b; } fst, snd; } obj;
9199 /// obj.fst // no
9200 /// obj.snd // yes
9201 /// obj.fst.a // no
9202 /// obj.fst.b // no
9203 /// obj.snd.a // no
9204 /// obj.snd.b // yes
9205 ///
9206 /// Please note: this function is specialized for how __builtin_object_size
9207 /// views "objects".
9208 ///
9209 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9210 /// correct result, it will always return true.
9211 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9212  assert(!LVal.Designator.Invalid);
9213 
9214  auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9215  const RecordDecl *Parent = FD->getParent();
9216  Invalid = Parent->isInvalidDecl();
9217  if (Invalid || Parent->isUnion())
9218  return true;
9219  const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9220  return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9221  };
9222 
9223  auto &Base = LVal.getLValueBase();
9224  if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9225  if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9226  bool Invalid;
9227  if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9228  return Invalid;
9229  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9230  for (auto *FD : IFD->chain()) {
9231  bool Invalid;
9232  if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9233  return Invalid;
9234  }
9235  }
9236  }
9237 
9238  unsigned I = 0;
9239  QualType BaseType = getType(Base);
9240  if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9241  // If we don't know the array bound, conservatively assume we're looking at
9242  // the final array element.
9243  ++I;
9244  if (BaseType->isIncompleteArrayType())
9245  BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9246  else
9247  BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9248  }
9249 
9250  for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9251  const auto &Entry = LVal.Designator.Entries[I];
9252  if (BaseType->isArrayType()) {
9253  // Because __builtin_object_size treats arrays as objects, we can ignore
9254  // the index iff this is the last array in the Designator.
9255  if (I + 1 == E)
9256  return true;
9257  const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9258  uint64_t Index = Entry.getAsArrayIndex();
9259  if (Index + 1 != CAT->getSize())
9260  return false;
9261  BaseType = CAT->getElementType();
9262  } else if (BaseType->isAnyComplexType()) {
9263  const auto *CT = BaseType->castAs<ComplexType>();
9264  uint64_t Index = Entry.getAsArrayIndex();
9265  if (Index != 1)
9266  return false;
9267  BaseType = CT->getElementType();
9268  } else if (auto *FD = getAsField(Entry)) {
9269  bool Invalid;
9270  if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9271  return Invalid;
9272  BaseType = FD->getType();
9273  } else {
9274  assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9275  return false;
9276  }
9277  }
9278  return true;
9279 }
9280 
9281 /// Tests to see if the LValue has a user-specified designator (that isn't
9282 /// necessarily valid). Note that this always returns 'true' if the LValue has
9283 /// an unsized array as its first designator entry, because there's currently no
9284 /// way to tell if the user typed *foo or foo[0].
9285 static bool refersToCompleteObject(const LValue &LVal) {
9286  if (LVal.Designator.Invalid)
9287  return false;
9288 
9289  if (!LVal.Designator.Entries.empty())
9290  return LVal.Designator.isMostDerivedAnUnsizedArray();
9291 
9292  if (!LVal.InvalidBase)
9293  return true;
9294 
9295  // If `E` is a MemberExpr, then the first part of the designator is hiding in
9296  // the LValueBase.
9297  const auto *E = LVal.Base.dyn_cast<const Expr *>();
9298  return !E || !isa<MemberExpr>(E);
9299 }
9300 
9301 /// Attempts to detect a user writing into a piece of memory that's impossible
9302 /// to figure out the size of by just using types.
9303 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9304  const SubobjectDesignator &Designator = LVal.Designator;
9305  // Notes:
9306  // - Users can only write off of the end when we have an invalid base. Invalid
9307  // bases imply we don't know where the memory came from.
9308  // - We used to be a bit more aggressive here; we'd only be conservative if
9309  // the array at the end was flexible, or if it had 0 or 1 elements. This
9310  // broke some common standard library extensions (PR30346), but was
9311  // otherwise seemingly fine. It may be useful to reintroduce this behavior
9312  // with some sort of whitelist. OTOH, it seems that GCC is always
9313  // conservative with the last element in structs (if it's an array), so our
9314  // current behavior is more compatible than a whitelisting approach would
9315  // be.
9316  return LVal.InvalidBase &&
9317  Designator.Entries.size() == Designator.MostDerivedPathLength &&
9318  Designator.MostDerivedIsArrayElement &&
9319  isDesignatorAtObjectEnd(Ctx, LVal);
9320 }
9321 
9322 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9323 /// Fails if the conversion would cause loss of precision.
9324 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9325  CharUnits &Result) {
9327  if (Int.ugt(CharUnitsMax))
9328  return false;
9329  Result = CharUnits::fromQuantity(Int.getZExtValue());
9330  return true;
9331 }
9332 
9333 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9334 /// determine how many bytes exist from the beginning of the object to either
9335 /// the end of the current subobject, or the end of the object itself, depending
9336 /// on what the LValue looks like + the value of Type.
9337 ///
9338 /// If this returns false, the value of Result is undefined.
9339 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9340  unsigned Type, const LValue &LVal,
9341  CharUnits &EndOffset) {
9342  bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9343 
9344  auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9345  if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9346  return false;
9347  return HandleSizeof(Info, ExprLoc, Ty, Result);
9348  };
9349 
9350  // We want to evaluate the size of the entire object. This is a valid fallback
9351  // for when Type=1 and the designator is invalid, because we're asked for an
9352  // upper-bound.
9353  if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9354  // Type=3 wants a lower bound, so we can't fall back to this.
9355  if (Type == 3 && !DetermineForCompleteObject)
9356  return false;
9357 
9358  llvm::APInt APEndOffset;
9359  if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9360  getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9361  return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9362 
9363  if (LVal.InvalidBase)
9364  return false;
9365 
9366  QualType BaseTy = getObjectType(LVal.getLValueBase());
9367  return CheckedHandleSizeof(BaseTy, EndOffset);
9368  }
9369 
9370  // We want to evaluate the size of a subobject.
9371  const SubobjectDesignator &Designator = LVal.Designator;
9372 
9373  // The following is a moderately common idiom in C:
9374  //
9375  // struct Foo { int a; char c[1]; };
9376  // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9377  // strcpy(&F->c[0], Bar);
9378  //
9379  // In order to not break too much legacy code, we need to support it.
9380  if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9381  // If we can resolve this to an alloc_size call, we can hand that back,
9382  // because we know for certain how many bytes there are to write to.
9383  llvm::APInt APEndOffset;
9384  if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9385  getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9386  return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9387 
9388  // If we cannot determine the size of the initial allocation, then we can't
9389  // given an accurate upper-bound. However, we are still able to give
9390  // conservative lower-bounds for Type=3.
9391  if (Type == 1)
9392  return false;
9393  }
9394 
9395  CharUnits BytesPerElem;
9396  if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9397  return false;
9398 
9399  // According to the GCC documentation, we want the size of the subobject
9400  // denoted by the pointer. But that's not quite right -- what we actually
9401  // want is the size of the immediately-enclosing array, if there is one.
9402  int64_t ElemsRemaining;
9403  if (Designator.MostDerivedIsArrayElement &&
9404  Designator.Entries.size() == Designator.MostDerivedPathLength) {
9405  uint64_t ArraySize = Designator.getMostDerivedArraySize();
9406  uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9407  ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9408  } else {
9409  ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9410  }
9411 
9412  EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9413  return true;
9414 }
9415 
9416 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9417 /// returns true and stores the result in @p Size.
9418 ///
9419 /// If @p WasError is non-null, this will report whether the failure to evaluate
9420 /// is to be treated as an Error in IntExprEvaluator.
9421 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9422  EvalInfo &Info, uint64_t &Size) {
9423  // Determine the denoted object.
9424  LValue LVal;
9425  {
9426  // The operand of __builtin_object_size is never evaluated for side-effects.
9427  // If there are any, but we can determine the pointed-to object anyway, then
9428  // ignore the side-effects.
9429  SpeculativeEvaluationRAII SpeculativeEval(Info);
9430  IgnoreSideEffectsRAII Fold(Info);
9431 
9432  if (E->isGLValue()) {
9433  // It's possible for us to be given GLValues if we're called via
9434  // Expr::tryEvaluateObjectSize.
9435  APValue RVal;
9436  if (!EvaluateAsRValue(Info, E, RVal))
9437  return false;
9438  LVal.setFrom(Info.Ctx, RVal);
9439  } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9440  /*InvalidBaseOK=*/true))
9441  return false;
9442  }
9443 
9444  // If we point to before the start of the object, there are no accessible
9445  // bytes.
9446  if (LVal.getLValueOffset().isNegative()) {
9447  Size = 0;
9448  return true;
9449  }
9450 
9451  CharUnits EndOffset;
9452  if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9453  return false;
9454 
9455  // If we've fallen outside of the end offset, just pretend there's nothing to
9456  // write to/read from.
9457  if (EndOffset <= LVal.getLValueOffset())
9458  Size = 0;
9459  else
9460  Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9461  return true;
9462 }
9463 
9464 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9465  llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9466  if (E->getResultAPValueKind() != APValue::None)
9467  return Success(E->getAPValueResult(), E);
9468  return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9469 }
9470 
9471 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9472  if (unsigned BuiltinOp = E->getBuiltinCallee())
9473  return VisitBuiltinCallExpr(E, BuiltinOp);
9474 
9475  return ExprEvaluatorBaseTy::VisitCallExpr(E);
9476 }
9477 
9478 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9479  unsigned BuiltinOp) {
9480  switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9481  default:
9482  return ExprEvaluatorBaseTy::VisitCallExpr(E);
9483 
9484  case Builtin::BI__builtin_dynamic_object_size:
9485  case Builtin::BI__builtin_object_size: {
9486  // The type was checked when we built the expression.
9487  unsigned Type =
9488  E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9489  assert(Type <= 3 && "unexpected type");
9490 
9491  uint64_t Size;
9492  if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9493  return Success(Size, E);
9494 
9495  if (E->getArg(0)->HasSideEffects(Info.Ctx))
9496  return Success((Type & 2) ? 0 : -1, E);
9497 
9498  // Expression had no side effects, but we couldn't statically determine the
9499  // size of the referenced object.
9500  switch (Info.EvalMode) {
9501  case EvalInfo::EM_ConstantExpression:
9502  case EvalInfo::EM_PotentialConstantExpression:
9503  case EvalInfo::EM_ConstantFold:
9504  case EvalInfo::EM_EvaluateForOverflow:
9505  case EvalInfo::EM_IgnoreSideEffects:
9506  // Leave it to IR generation.
9507  return Error(E);
9508  case EvalInfo::EM_ConstantExpressionUnevaluated:
9509  case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
9510  // Reduce it to a constant now.
9511  return Success((Type & 2) ? 0 : -1, E);
9512  }
9513 
9514  llvm_unreachable("unexpected EvalMode");
9515  }
9516 
9517  case Builtin::BI__builtin_os_log_format_buffer_size: {
9519  analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9520  return Success(Layout.size().getQuantity(), E);
9521  }
9522 
9523  case Builtin::BI__builtin_bswap16:
9524  case Builtin::BI__builtin_bswap32:
9525  case Builtin::BI__builtin_bswap64: {
9526  APSInt Val;
9527  if (!EvaluateInteger(E->getArg(0), Val, Info))
9528  return false;
9529 
9530  return Success(Val.byteSwap(), E);
9531  }
9532 
9533  case Builtin::BI__builtin_classify_type:
9534  return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9535 
9536  case Builtin::BI__builtin_clrsb:
9537  case Builtin::BI__builtin_clrsbl:
9538  case Builtin::BI__builtin_clrsbll: {
9539  APSInt Val;
9540  if (!EvaluateInteger(E->getArg(0), Val, Info))
9541  return false;
9542 
9543  return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9544  }
9545 
9546  case Builtin::BI__builtin_clz:
9547  case Builtin::BI__builtin_clzl:
9548  case Builtin::BI__builtin_clzll:
9549  case Builtin::BI__builtin_clzs: {
9550  APSInt Val;
9551  if (!EvaluateInteger(E->getArg(0), Val, Info))
9552  return false;
9553  if (!Val)
9554  return Error(E);
9555 
9556  return Success(Val.countLeadingZeros(), E);
9557  }
9558 
9559  case Builtin::BI__builtin_constant_p: {
9560  const Expr *Arg = E->getArg(0);
9561  if (EvaluateBuiltinConstantP(Info, Arg))
9562  return Success(true, E);
9563  if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9564  // Outside a constant context, eagerly evaluate to false in the presence
9565  // of side-effects in order to avoid -Wunsequenced false-positives in
9566  // a branch on __builtin_constant_p(expr).
9567  return Success(false, E);
9568  }
9569  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9570  return false;
9571  }
9572 
9573  case Builtin::BI__builtin_is_constant_evaluated:
9574  return Success(Info.InConstantContext, E);
9575 
9576  case Builtin::BI__builtin_ctz:
9577  case Builtin::BI__builtin_ctzl:
9578  case Builtin::BI__builtin_ctzll:
9579  case Builtin::BI__builtin_ctzs: {
9580  APSInt Val;
9581  if (!EvaluateInteger(E->getArg(0), Val, Info))
9582  return false;
9583  if (!Val)
9584  return Error(E);
9585 
9586  return Success(Val.countTrailingZeros(), E);
9587  }
9588 
9589  case Builtin::BI__builtin_eh_return_data_regno: {
9590  int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9591  Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9592  return Success(Operand, E);
9593  }
9594 
9595  case Builtin::BI__builtin_expect:
9596  return Visit(E->getArg(0));
9597 
9598  case Builtin::BI__builtin_ffs:
9599  case Builtin::BI__builtin_ffsl:
9600  case Builtin::BI__builtin_ffsll: {
9601  APSInt Val;
9602  if (!EvaluateInteger(E->getArg(0), Val, Info))
9603  return false;
9604 
9605  unsigned N = Val.countTrailingZeros();
9606  return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9607  }
9608 
9609  case Builtin::BI__builtin_fpclassify: {
9610  APFloat Val(0.0);
9611  if (!EvaluateFloat(E->getArg(5), Val, Info))
9612  return false;
9613  unsigned Arg;
9614  switch (Val.getCategory()) {
9615  case APFloat::fcNaN: Arg = 0; break;
9616  case APFloat::fcInfinity: Arg = 1; break;
9617  case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9618  case APFloat::fcZero: Arg = 4; break;
9619  }
9620  return Visit(E->getArg(Arg));
9621  }
9622 
9623  case Builtin::BI__builtin_isinf_sign: {
9624  APFloat Val(0.0);
9625  return EvaluateFloat(E->getArg(0), Val, Info) &&
9626  Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9627  }
9628 
9629  case Builtin::BI__builtin_isinf: {
9630  APFloat Val(0.0);
9631  return EvaluateFloat(E->getArg(0), Val, Info) &&
9632  Success(Val.isInfinity() ? 1 : 0, E);
9633  }
9634 
9635  case Builtin::BI__builtin_isfinite: {
9636  APFloat Val(0.0);
9637  return EvaluateFloat(E->getArg(0), Val, Info) &&
9638  Success(Val.isFinite() ? 1 : 0, E);
9639  }
9640 
9641  case Builtin::BI__builtin_isnan: {
9642  APFloat Val(0.0);
9643  return EvaluateFloat(E->getArg(0), Val, Info) &&
9644  Success(Val.isNaN() ? 1 : 0, E);
9645  }
9646 
9647  case Builtin::BI__builtin_isnormal: {
9648  APFloat Val(0.0);
9649  return EvaluateFloat(E->getArg(0), Val, Info) &&
9650  Success(Val.isNormal() ? 1 : 0, E);
9651  }
9652 
9653  case Builtin::BI__builtin_parity:
9654  case Builtin::BI__builtin_parityl:
9655  case Builtin::BI__builtin_parityll: {
9656  APSInt Val;
9657  if (!EvaluateInteger(E->getArg(0), Val, Info))
9658  return false;
9659 
9660  return Success(Val.countPopulation() % 2, E);
9661  }
9662 
9663  case Builtin::BI__builtin_popcount:
9664  case Builtin::BI__builtin_popcountl:
9665  case Builtin::BI__builtin_popcountll: {
9666  APSInt Val;
9667  if (!EvaluateInteger(E->getArg(0), Val, Info))
9668  return false;
9669 
9670  return Success(Val.countPopulation(), E);
9671  }
9672 
9673  case Builtin::BIstrlen:
9674  case Builtin::BIwcslen:
9675  // A call to strlen is not a constant expression.
9676  if (Info.getLangOpts().CPlusPlus11)
9677  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9678  << /*isConstexpr*/0 << /*isConstructor*/0
9679  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9680  else
9681  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9682  LLVM_FALLTHROUGH;
9683  case Builtin::BI__builtin_strlen:
9684  case Builtin::BI__builtin_wcslen: {
9685  // As an extension, we support __builtin_strlen() as a constant expression,
9686  // and support folding strlen() to a constant.
9687  LValue String;
9688  if (!EvaluatePointer(E->getArg(0), String, Info))
9689  return false;
9690 
9691  QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9692 
9693  // Fast path: if it's a string literal, search the string value.
9694  if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9695  String.getLValueBase().dyn_cast<const Expr *>())) {
9696  // The string literal may have embedded null characters. Find the first
9697  // one and truncate there.
9698  StringRef Str = S->getBytes();
9699  int64_t Off = String.Offset.getQuantity();
9700  if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9701  S->getCharByteWidth() == 1 &&
9702  // FIXME: Add fast-path for wchar_t too.
9703  Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9704  Str = Str.substr(Off);
9705 
9706  StringRef::size_type Pos = Str.find(0);
9707  if (Pos != StringRef::npos)
9708  Str = Str.substr(0, Pos);
9709 
9710  return Success(Str.size(), E);
9711  }
9712 
9713  // Fall through to slow path to issue appropriate diagnostic.
9714  }
9715 
9716  // Slow path: scan the bytes of the string looking for the terminating 0.
9717  for (uint64_t Strlen = 0; /**/; ++Strlen) {
9718  APValue Char;
9719  if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9720  !Char.isInt())
9721  return false;
9722  if (!Char.getInt())
9723  return Success(Strlen, E);
9724  if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9725  return false;
9726  }
9727  }
9728 
9729  case Builtin::BIstrcmp:
9730  case Builtin::BIwcscmp:
9731  case Builtin::BIstrncmp:
9732  case Builtin::BIwcsncmp:
9733  case Builtin::BImemcmp:
9734  case Builtin::BIbcmp:
9735  case Builtin::BIwmemcmp:
9736  // A call to strlen is not a constant expression.
9737  if (Info.getLangOpts().CPlusPlus11)
9738  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9739  << /*isConstexpr*/0 << /*isConstructor*/0
9740  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9741  else
9742  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9743  LLVM_FALLTHROUGH;
9744  case Builtin::BI__builtin_strcmp:
9745  case Builtin::BI__builtin_wcscmp:
9746  case Builtin::BI__builtin_strncmp:
9747  case Builtin::BI__builtin_wcsncmp:
9748  case Builtin::BI__builtin_memcmp:
9749  case Builtin::BI__builtin_bcmp:
9750  case Builtin::BI__builtin_wmemcmp: {
9751  LValue String1, String2;
9752  if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9753  !EvaluatePointer(E->getArg(1), String2, Info))
9754  return false;
9755 
9756  uint64_t MaxLength = uint64_t(-1);
9757  if (BuiltinOp != Builtin::BIstrcmp &&
9758  BuiltinOp != Builtin::BIwcscmp &&
9759  BuiltinOp != Builtin::BI__builtin_strcmp &&
9760  BuiltinOp != Builtin::BI__builtin_wcscmp) {
9761  APSInt N;
9762  if (!EvaluateInteger(E->getArg(2), N, Info))
9763  return false;
9764  MaxLength = N.getExtValue();
9765  }
9766 
9767  // Empty substrings compare equal by definition.
9768  if (MaxLength == 0u)
9769  return Success(0, E);
9770 
9771  if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9772  !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9773  String1.Designator.Invalid || String2.Designator.Invalid)
9774  return false;
9775 
9776  QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9777  QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9778 
9779  bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9780  BuiltinOp == Builtin::BIbcmp ||
9781  BuiltinOp == Builtin::BI__builtin_memcmp ||
9782  BuiltinOp == Builtin::BI__builtin_bcmp;
9783 
9784  assert(IsRawByte ||
9785  (Info.Ctx.hasSameUnqualifiedType(
9786  CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9787  Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9788 
9789  const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9790  return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9791  handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9792  Char1.isInt() && Char2.isInt();
9793  };
9794  const auto &AdvanceElems = [&] {
9795  return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9796  HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9797  };
9798 
9799  if (IsRawByte) {
9800  uint64_t BytesRemaining = MaxLength;
9801  // Pointers to const void may point to objects of incomplete type.
9802  if (CharTy1->isIncompleteType()) {
9803  Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9804  return false;
9805  }
9806  if (CharTy2->isIncompleteType()) {
9807  Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9808  return false;
9809  }
9810  uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9811  CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9812  // Give up on comparing between elements with disparate widths.
9813  if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9814  return false;
9815  uint64_t BytesPerElement = CharTy1Size.getQuantity();
9816  assert(BytesRemaining && "BytesRemaining should not be zero: the "
9817  "following loop considers at least one element");
9818  while (true) {
9819  APValue Char1, Char2;
9820  if (!ReadCurElems(Char1, Char2))
9821  return false;
9822  // We have compatible in-memory widths, but a possible type and
9823  // (for `bool`) internal representation mismatch.
9824  // Assuming two's complement representation, including 0 for `false` and
9825  // 1 for `true`, we can check an appropriate number of elements for
9826  // equality even if they are not byte-sized.
9827  APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9828  APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9829  if (Char1InMem.ne(Char2InMem)) {
9830  // If the elements are byte-sized, then we can produce a three-way
9831  // comparison result in a straightforward manner.
9832  if (BytesPerElement == 1u) {
9833  // memcmp always compares unsigned chars.
9834  return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9835  }
9836  // The result is byte-order sensitive, and we have multibyte elements.
9837  // FIXME: We can compare the remaining bytes in the correct order.
9838  return false;
9839  }
9840  if (!AdvanceElems())
9841  return false;
9842  if (BytesRemaining <= BytesPerElement)
9843  break;
9844  BytesRemaining -= BytesPerElement;
9845  }
9846  // Enough elements are equal to account for the memcmp limit.
9847  return Success(0, E);
9848  }
9849 
9850  bool StopAtNull =
9851  (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9852  BuiltinOp != Builtin::BIwmemcmp &&
9853  BuiltinOp != Builtin::BI__builtin_memcmp &&
9854  BuiltinOp != Builtin::BI__builtin_bcmp &&
9855  BuiltinOp != Builtin::BI__builtin_wmemcmp);
9856  bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9857  BuiltinOp == Builtin::BIwcsncmp ||
9858  BuiltinOp == Builtin::BIwmemcmp ||
9859  BuiltinOp == Builtin::BI__builtin_wcscmp ||
9860  BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9861  BuiltinOp == Builtin::BI__builtin_wmemcmp;
9862 
9863  for (; MaxLength; --MaxLength) {
9864  APValue Char1, Char2;
9865  if (!ReadCurElems(Char1, Char2))
9866  return false;
9867  if (Char1.getInt() != Char2.getInt()) {
9868  if (IsWide) // wmemcmp compares with wchar_t signedness.
9869  return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9870  // memcmp always compares unsigned chars.
9871  return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9872  }
9873  if (StopAtNull && !Char1.getInt())
9874  return Success(0, E);
9875  assert(!(StopAtNull && !Char2.getInt()));
9876  if (!AdvanceElems())
9877  return false;
9878  }
9879  // We hit the strncmp / memcmp limit.
9880  return Success(0, E);
9881  }
9882 
9883  case Builtin::BI__atomic_always_lock_free:
9884  case Builtin::BI__atomic_is_lock_free:
9885  case Builtin::BI__c11_atomic_is_lock_free: {
9886  APSInt SizeVal;
9887  if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9888  return false;
9889 
9890  // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9891  // of two less than the maximum inline atomic width, we know it is
9892  // lock-free. If the size isn't a power of two, or greater than the
9893  // maximum alignment where we promote atomics, we know it is not lock-free
9894  // (at least not in the sense of atomic_is_lock_free). Otherwise,
9895  // the answer can only be determined at runtime; for example, 16-byte
9896  // atomics have lock-free implementations on some, but not all,
9897  // x86-64 processors.
9898 
9899  // Check power-of-two.
9900  CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9901  if (Size.isPowerOfTwo()) {
9902  // Check against inlining width.
9903  unsigned InlineWidthBits =
9904  Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9905  if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9906  if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9907  Size == CharUnits::One() ||
9908  E->getArg(1)->isNullPointerConstant(Info.Ctx,
9910  // OK, we will inline appropriately-aligned operations of this size,
9911  // and _Atomic(T) is appropriately-aligned.
9912  return Success(1, E);
9913 
9914  QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9915  castAs<PointerType>()->getPointeeType();
9916  if (!PointeeType->isIncompleteType() &&
9917  Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9918  // OK, we will inline operations on this object.
9919  return Success(1, E);
9920  }
9921  }
9922  }
9923 
9924  return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9925  Success(0, E) : Error(E);
9926  }
9927  case Builtin::BIomp_is_initial_device:
9928  // We can decide statically which value the runtime would return if called.
9929  return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9930  case Builtin::BI__builtin_add_overflow:
9931  case Builtin::BI__builtin_sub_overflow:
9932  case Builtin::BI__builtin_mul_overflow:
9933  case Builtin::BI__builtin_sadd_overflow:
9934  case Builtin::BI__builtin_uadd_overflow:
9935  case Builtin::BI__builtin_uaddl_overflow:
9936  case Builtin::BI__builtin_uaddll_overflow:
9937  case Builtin::BI__builtin_usub_overflow:
9938  case Builtin::BI__builtin_usubl_overflow:
9939  case Builtin::BI__builtin_usubll_overflow:
9940  case Builtin::BI__builtin_umul_overflow:
9941  case Builtin::BI__builtin_umull_overflow:
9942  case Builtin::BI__builtin_umulll_overflow:
9943  case Builtin::BI__builtin_saddl_overflow:
9944  case Builtin::BI__builtin_saddll_overflow:
9945  case Builtin::BI__builtin_ssub_overflow:
9946  case Builtin::BI__builtin_ssubl_overflow:
9947  case Builtin::BI__builtin_ssubll_overflow:
9948  case Builtin::BI__builtin_smul_overflow:
9949  case Builtin::BI__builtin_smull_overflow:
9950  case Builtin::BI__builtin_smulll_overflow: {
9951  LValue ResultLValue;
9952  APSInt LHS, RHS;
9953 
9954  QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9955  if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9956  !EvaluateInteger(E->getArg(1), RHS, Info) ||
9957  !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9958  return false;
9959 
9960  APSInt Result;
9961  bool DidOverflow = false;
9962 
9963  // If the types don't have to match, enlarge all 3 to the largest of them.
9964  if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9965  BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9966  BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9967  bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9968  ResultType->isSignedIntegerOrEnumerationType();
9969  bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9970  ResultType->isSignedIntegerOrEnumerationType();
9971  uint64_t LHSSize = LHS.getBitWidth();
9972  uint64_t RHSSize = RHS.getBitWidth();
9973  uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9974  uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9975 
9976  // Add an additional bit if the signedness isn't uniformly agreed to. We
9977  // could do this ONLY if there is a signed and an unsigned that both have
9978  // MaxBits, but the code to check that is pretty nasty. The issue will be
9979  // caught in the shrink-to-result later anyway.
9980  if (IsSigned && !AllSigned)
9981  ++MaxBits;
9982 
9983  LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9984  RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9985  Result = APSInt(MaxBits, !IsSigned);
9986  }
9987 
9988  // Find largest int.
9989  switch (BuiltinOp) {
9990  default:
9991  llvm_unreachable("Invalid value for BuiltinOp");
9992  case Builtin::BI__builtin_add_overflow:
9993  case Builtin::BI__builtin_sadd_overflow:
9994  case Builtin::BI__builtin_saddl_overflow:
9995  case Builtin::BI__builtin_saddll_overflow:
9996  case Builtin::BI__builtin_uadd_overflow:
9997  case Builtin::BI__builtin_uaddl_overflow:
9998  case Builtin::BI__builtin_uaddll_overflow:
9999  Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10000  : LHS.uadd_ov(RHS, DidOverflow);
10001  break;
10002  case Builtin::BI__builtin_sub_overflow:
10003  case Builtin::BI__builtin_ssub_overflow:
10004  case Builtin::BI__builtin_ssubl_overflow:
10005  case Builtin::BI__builtin_ssubll_overflow:
10006  case Builtin::BI__builtin_usub_overflow:
10007  case Builtin::BI__builtin_usubl_overflow:
10008  case Builtin::BI__builtin_usubll_overflow:
10009  Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10010  : LHS.usub_ov(RHS, DidOverflow);
10011  break;
10012  case Builtin::BI__builtin_mul_overflow:
10013  case Builtin::BI__builtin_smul_overflow:
10014  case Builtin::BI__builtin_smull_overflow:
10015  case Builtin::BI__builtin_smulll_overflow:
10016  case Builtin::BI__builtin_umul_overflow:
10017  case Builtin::BI__builtin_umull_overflow:
10018  case Builtin::BI__builtin_umulll_overflow:
10019  Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10020  : LHS.umul_ov(RHS, DidOverflow);
10021  break;
10022  }
10023 
10024  // In the case where multiple sizes are allowed, truncate and see if
10025  // the values are the same.
10026  if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10027  BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10028  BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10029  // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10030  // since it will give us the behavior of a TruncOrSelf in the case where
10031  // its parameter <= its size. We previously set Result to be at least the
10032  // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10033  // will work exactly like TruncOrSelf.
10034  APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10035  Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10036 
10037  if (!APSInt::isSameValue(Temp, Result))
10038  DidOverflow = true;
10039  Result = Temp;
10040  }
10041 
10042  APValue APV{Result};
10043  if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10044  return false;
10045  return Success(DidOverflow, E);
10046  }
10047  }
10048 }
10049 
10050 /// Determine whether this is a pointer past the end of the complete
10051 /// object referred to by the lvalue.
10053  const LValue &LV) {
10054  // A null pointer can be viewed as being "past the end" but we don't
10055  // choose to look at it that way here.
10056  if (!LV.getLValueBase())
10057  return false;
10058 
10059  // If the designator is valid and refers to a subobject, we're not pointing
10060  // past the end.
10061  if (!LV.getLValueDesignator().Invalid &&
10062  !LV.getLValueDesignator().isOnePastTheEnd())
10063  return false;
10064 
10065  // A pointer to an incomplete type might be past-the-end if the type's size is
10066  // zero. We cannot tell because the type is incomplete.
10067  QualType Ty = getType(LV.getLValueBase());
10068  if (Ty->isIncompleteType())
10069  return true;
10070 
10071  // We're a past-the-end pointer if we point to the byte after the object,
10072  // no matter what our type or path is.
10073  auto Size = Ctx.getTypeSizeInChars(Ty);
10074  return LV.getLValueOffset() == Size;
10075 }
10076 
10077 namespace {
10078 
10079 /// Data recursive integer evaluator of certain binary operators.
10080 ///
10081 /// We use a data recursive algorithm for binary operators so that we are able
10082 /// to handle extreme cases of chained binary operators without causing stack
10083 /// overflow.
10084 class DataRecursiveIntBinOpEvaluator {
10085  struct EvalResult {
10086  APValue Val;
10087  bool Failed;
10088 
10089  EvalResult() : Failed(false) { }
10090 
10091  void swap(EvalResult &RHS) {
10092  Val.swap(RHS.Val);
10093  Failed = RHS.Failed;
10094  RHS.Failed = false;
10095  }
10096  };
10097 
10098  struct Job {
10099  const Expr *E;
10100  EvalResult LHSResult; // meaningful only for binary operator expression.
10101  enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10102 
10103  Job() = default;
10104  Job(Job &&) = default;
10105 
10106  void startSpeculativeEval(EvalInfo &Info) {
10107  SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10108  }
10109 
10110  private:
10111  SpeculativeEvaluationRAII SpecEvalRAII;
10112  };
10113 
10114  SmallVector<Job, 16> Queue;
10115 
10116  IntExprEvaluator &IntEval;
10117  EvalInfo &Info;
10118  APValue &FinalResult;
10119 
10120 public:
10121  DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10122  : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10123 
10124  /// True if \param E is a binary operator that we are going to handle
10125  /// data recursively.
10126  /// We handle binary operators that are comma, logical, or that have operands
10127  /// with integral or enumeration type.
10128  static bool shouldEnqueue(const BinaryOperator *E) {
10129  return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10130  (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10133  }
10134 
10135  bool Traverse(const BinaryOperator *E) {
10136  enqueue(E);
10137  EvalResult PrevResult;
10138  while (!Queue.empty())
10139  process(PrevResult);
10140 
10141  if (PrevResult.Failed) return false;
10142 
10143  FinalResult.swap(PrevResult.Val);
10144  return true;
10145  }
10146 
10147 private:
10148  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10149  return IntEval.Success(Value, E, Result);
10150  }
10151  bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10152  return IntEval.Success(Value, E, Result);
10153  }
10154  bool Error(const Expr *E) {
10155  return IntEval.Error(E);
10156  }
10157  bool Error(const Expr *E, diag::kind D) {
10158  return IntEval.Error(E, D);
10159  }
10160 
10161  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10162  return Info.CCEDiag(E, D);
10163  }
10164 
10165  // Returns true if visiting the RHS is necessary, false otherwise.
10166  bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10167  bool &SuppressRHSDiags);
10168 
10169  bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10170  const BinaryOperator *E, APValue &Result);
10171 
10172  void EvaluateExpr(const Expr *E, EvalResult &Result) {
10173  Result.Failed = !Evaluate(Result.Val, Info, E);
10174  if (Result.Failed)
10175  Result.Val = APValue();
10176  }
10177 
10178  void process(EvalResult &Result);
10179 
10180  void enqueue(const Expr *E) {
10181  E = E->IgnoreParens();
10182  Queue.resize(Queue.size()+1);
10183  Queue.back().E = E;
10184  Queue.back().Kind = Job::AnyExprKind;
10185  }
10186 };
10187 
10188 }
10189 
10190 bool DataRecursiveIntBinOpEvaluator::
10191  VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10192  bool &SuppressRHSDiags) {
10193  if (E->getOpcode() == BO_Comma) {
10194  // Ignore LHS but note if we could not evaluate it.
10195  if (LHSResult.Failed)
10196  return Info.noteSideEffect();
10197  return true;
10198  }
10199 
10200  if (E->isLogicalOp()) {
10201  bool LHSAsBool;
10202  if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10203  // We were able to evaluate the LHS, see if we can get away with not
10204  // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10205  if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10206  Success(LHSAsBool, E, LHSResult.Val);
10207  return false; // Ignore RHS
10208  }
10209  } else {
10210  LHSResult.Failed = true;
10211 
10212  // Since we weren't able to evaluate the left hand side, it
10213  // might have had side effects.
10214  if (!Info.noteSideEffect())
10215  return false;
10216 
10217  // We can't evaluate the LHS; however, sometimes the result
10218  // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10219  // Don't ignore RHS and suppress diagnostics from this arm.
10220  SuppressRHSDiags = true;
10221  }
10222 
10223  return true;
10224  }
10225 
10226  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10228 
10229  if (LHSResult.Failed && !Info.noteFailure())
10230  return false; // Ignore RHS;
10231 
10232  return true;
10233 }
10234 
10235 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10236  bool IsSub) {
10237  // Compute the new offset in the appropriate width, wrapping at 64 bits.
10238  // FIXME: When compiling for a 32-bit target, we should use 32-bit
10239  // offsets.
10240  assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10241  CharUnits &Offset = LVal.getLValueOffset();
10242  uint64_t Offset64 = Offset.getQuantity();
10243  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10244  Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10245  : Offset64 + Index64);
10246 }
10247 
10248 bool DataRecursiveIntBinOpEvaluator::
10249  VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10250  const BinaryOperator *E, APValue &Result) {
10251  if (E->getOpcode() == BO_Comma) {
10252  if (RHSResult.Failed)
10253  return false;
10254  Result = RHSResult.Val;
10255  return true;
10256  }
10257 
10258  if (E->isLogicalOp()) {
10259  bool lhsResult, rhsResult;
10260  bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10261  bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10262 
10263  if (LHSIsOK) {
10264  if (RHSIsOK) {
10265  if (E->getOpcode() == BO_LOr)
10266  return Success(lhsResult || rhsResult, E, Result);
10267  else
10268  return Success(lhsResult && rhsResult, E, Result);
10269  }
10270  } else {
10271  if (RHSIsOK) {
10272  // We can't evaluate the LHS; however, sometimes the result
10273  // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10274  if (rhsResult == (E->getOpcode() == BO_LOr))
10275  return Success(rhsResult, E, Result);
10276  }
10277  }
10278 
10279  return false;
10280  }
10281 
10282  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10284 
10285  if (LHSResult.Failed || RHSResult.Failed)
10286  return false;
10287 
10288  const APValue &LHSVal = LHSResult.Val;
10289  const APValue &RHSVal = RHSResult.Val;
10290 
10291  // Handle cases like (unsigned long)&a + 4.
10292  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10293  Result = LHSVal;
10294  addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10295  return true;
10296  }
10297 
10298  // Handle cases like 4 + (unsigned long)&a
10299  if (E->getOpcode() == BO_Add &&
10300  RHSVal.isLValue() && LHSVal.isInt()) {
10301  Result = RHSVal;
10302  addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10303  return true;
10304  }
10305 
10306  if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10307  // Handle (intptr_t)&&A - (intptr_t)&&B.
10308  if (!LHSVal.getLValueOffset().isZero() ||
10309  !RHSVal.getLValueOffset().isZero())
10310  return false;
10311  const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10312  const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10313  if (!LHSExpr || !RHSExpr)
10314  return false;
10315  const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10316  const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10317  if (!LHSAddrExpr || !RHSAddrExpr)
10318  return false;
10319  // Make sure both labels come from the same function.
10320  if (LHSAddrExpr->getLabel()->getDeclContext() !=
10321  RHSAddrExpr->getLabel()->getDeclContext())
10322  return false;
10323  Result = APValue(LHSAddrExpr, RHSAddrExpr);
10324  return true;
10325  }
10326 
10327  // All the remaining cases expect both operands to be an integer
10328  if (!LHSVal.isInt() || !RHSVal.isInt())
10329  return Error(E);
10330 
10331  // Set up the width and signedness manually, in case it can't be deduced
10332  // from the operation we're performing.
10333  // FIXME: Don't do this in the cases where we can deduce it.
10334  APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10336  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10337  RHSVal.getInt(), Value))
10338  return false;
10339  return Success(Value, E, Result);
10340 }
10341 
10342 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10343  Job &job = Queue.back();
10344 
10345  switch (job.Kind) {
10346  case Job::AnyExprKind: {
10347  if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10348  if (shouldEnqueue(Bop)) {
10349  job.Kind = Job::BinOpKind;
10350  enqueue(Bop->getLHS());
10351  return;
10352  }
10353  }
10354 
10355  EvaluateExpr(job.E, Result);
10356  Queue.pop_back();
10357  return;
10358  }
10359 
10360  case Job::BinOpKind: {
10361  const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10362  bool SuppressRHSDiags = false;
10363  if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10364  Queue.pop_back();
10365  return;
10366  }
10367  if (SuppressRHSDiags)
10368  job.startSpeculativeEval(Info);
10369  job.LHSResult.swap(Result);
10370  job.Kind = Job::BinOpVisitedLHSKind;
10371  enqueue(Bop->getRHS());
10372  return;
10373  }
10374 
10375  case Job::BinOpVisitedLHSKind: {
10376  const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10377  EvalResult RHS;
10378  RHS.swap(Result);
10379  Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10380  Queue.pop_back();
10381  return;
10382  }
10383  }
10384 
10385  llvm_unreachable("Invalid Job::Kind!");
10386 }
10387 
10388 namespace {
10389 /// Used when we determine that we should fail, but can keep evaluating prior to
10390 /// noting that we had a failure.
10391 class DelayedNoteFailureRAII {
10392  EvalInfo &Info;
10393  bool NoteFailure;
10394 
10395 public:
10396  DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10397  : Info(Info), NoteFailure(NoteFailure) {}
10398  ~DelayedNoteFailureRAII() {
10399  if (NoteFailure) {
10400  bool ContinueAfterFailure = Info.noteFailure();
10401  (void)ContinueAfterFailure;
10402  assert(ContinueAfterFailure &&
10403  "Shouldn't have kept evaluating on failure.");
10404  }
10405  }
10406 };
10407 }
10408 
10409 template <class SuccessCB, class AfterCB>
10410 static bool
10412  SuccessCB &&Success, AfterCB &&DoAfter) {
10413  assert(E->isComparisonOp() && "expected comparison operator");
10414  assert((E->getOpcode() == BO_Cmp ||
10416  "unsupported binary expression evaluation");
10417  auto Error = [&](const Expr *E) {
10418  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10419  return false;
10420  };
10421 
10422  using CCR = ComparisonCategoryResult;
10423  bool IsRelational = E->isRelationalOp();
10424  bool IsEquality = E->isEqualityOp();
10425  if (E->getOpcode() == BO_Cmp) {
10426  const ComparisonCategoryInfo &CmpInfo =
10427  Info.Ctx.CompCategories.getInfoForType(E->getType());
10428  IsRelational = CmpInfo.isOrdered();
10429  IsEquality = CmpInfo.isEquality();
10430  }
10431 
10432  QualType LHSTy = E->getLHS()->getType();
10433  QualType RHSTy = E->getRHS()->getType();
10434 
10435  if (LHSTy->isIntegralOrEnumerationType() &&
10436  RHSTy->isIntegralOrEnumerationType()) {
10437  APSInt LHS, RHS;
10438  bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10439  if (!LHSOK && !Info.noteFailure())
10440  return false;
10441  if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10442  return false;
10443  if (LHS < RHS)
10444  return Success(CCR::Less, E);
10445  if (LHS > RHS)
10446  return Success(CCR::Greater, E);
10447  return Success(CCR::Equal, E);
10448  }
10449 
10450  if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10451  APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10452  APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10453 
10454  bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10455  if (!LHSOK && !Info.noteFailure())
10456  return false;
10457  if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10458  return false;
10459  if (LHSFX < RHSFX)
10460  return Success(CCR::Less, E);
10461  if (LHSFX > RHSFX)
10462  return Success(CCR::Greater, E);
10463  return Success(CCR::Equal, E);
10464  }
10465 
10466  if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10467  ComplexValue LHS, RHS;
10468  bool LHSOK;
10469  if (E->isAssignmentOp()) {
10470  LValue LV;
10471  EvaluateLValue(E->getLHS(), LV, Info);
10472  LHSOK = false;
10473  } else if (LHSTy->isRealFloatingType()) {
10474  LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10475  if (LHSOK) {
10476  LHS.makeComplexFloat();
10477  LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10478  }
10479  } else {
10480  LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10481  }
10482  if (!LHSOK && !Info.noteFailure())
10483  return false;
10484 
10485  if (E->getRHS()->getType()->isRealFloatingType()) {
10486  if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10487  return false;
10488  RHS.makeComplexFloat();
10489  RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10490  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10491  return false;
10492 
10493  if (LHS.isComplexFloat()) {
10494  APFloat::cmpResult CR_r =
10495  LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10496  APFloat::cmpResult CR_i =
10497  LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10498  bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10499  return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10500  } else {
10501  assert(IsEquality && "invalid complex comparison");
10502  bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10503  LHS.getComplexIntImag() == RHS.getComplexIntImag();
10504  return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10505  }
10506  }
10507 
10508  if (LHSTy->isRealFloatingType() &&
10509  RHSTy->isRealFloatingType()) {
10510  APFloat RHS(0.0), LHS(0.0);
10511 
10512  bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10513  if (!LHSOK && !Info.noteFailure())
10514  return false;
10515 
10516  if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10517  return false;
10518 
10519  assert(E->isComparisonOp() && "Invalid binary operator!");
10520  auto GetCmpRes = [&]() {
10521  switch (LHS.compare(RHS)) {
10522  case APFloat::cmpEqual:
10523  return CCR::Equal;
10524  case APFloat::cmpLessThan:
10525  return CCR::Less;
10526  case APFloat::cmpGreaterThan:
10527  return CCR::Greater;
10528  case APFloat::cmpUnordered:
10529  return CCR::Unordered;
10530  }
10531  llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10532  };
10533  return Success(GetCmpRes(), E);
10534  }
10535 
10536  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10537  LValue LHSValue, RHSValue;
10538 
10539  bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10540  if (!LHSOK && !Info.noteFailure())
10541  return false;
10542 
10543  if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10544  return false;
10545 
10546  // Reject differing bases from the normal codepath; we special-case
10547  // comparisons to null.
10548  if (!HasSameBase(LHSValue, RHSValue)) {
10549  // Inequalities and subtractions between unrelated pointers have
10550  // unspecified or undefined behavior.
10551  if (!IsEquality)
10552  return Error(E);
10553  // A constant address may compare equal to the address of a symbol.
10554  // The one exception is that address of an object cannot compare equal
10555  // to a null pointer constant.
10556  if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10557  (!RHSValue.Base && !RHSValue.Offset.isZero()))
10558  return Error(E);
10559  // It's implementation-defined whether distinct literals will have
10560  // distinct addresses. In clang, the result of such a comparison is
10561  // unspecified, so it is not a constant expression. However, we do know
10562  // that the address of a literal will be non-null.
10563  if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10564  LHSValue.Base && RHSValue.Base)
10565  return Error(E);
10566  // We can't tell whether weak symbols will end up pointing to the same
10567  // object.
10568  if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10569  return Error(E);
10570  // We can't compare the address of the start of one object with the
10571  // past-the-end address of another object, per C++ DR1652.
10572  if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10573  isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10574  (RHSValue.Base && RHSValue.Offset.isZero() &&
10575  isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10576  return Error(E);
10577  // We can't tell whether an object is at the same address as another
10578  // zero sized object.
10579  if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10580  (LHSValue.Base && isZeroSized(RHSValue)))
10581  return Error(E);
10582  return Success(CCR::Nonequal, E);
10583  }
10584 
10585  const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10586  const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10587 
10588  SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10589  SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10590 
10591  // C++11 [expr.rel]p3:
10592  // Pointers to void (after pointer conversions) can be compared, with a
10593  // result defined as follows: If both pointers represent the same
10594  // address or are both the null pointer value, the result is true if the
10595  // operator is <= or >= and false otherwise; otherwise the result is
10596  // unspecified.
10597  // We interpret this as applying to pointers to *cv* void.
10598  if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10599  Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10600 
10601  // C++11 [expr.rel]p2:
10602  // - If two pointers point to non-static data members of the same object,
10603  // or to subobjects or array elements fo such members, recursively, the
10604  // pointer to the later declared member compares greater provided the
10605  // two members have the same access control and provided their class is
10606  // not a union.
10607  // [...]
10608  // - Otherwise pointer comparisons are unspecified.
10609  if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10610  bool WasArrayIndex;
10611  unsigned Mismatch = FindDesignatorMismatch(
10612  getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10613  // At the point where the designators diverge, the comparison has a
10614  // specified value if:
10615  // - we are comparing array indices
10616  // - we are comparing fields of a union, or fields with the same access
10617  // Otherwise, the result is unspecified and thus the comparison is not a
10618  // constant expression.
10619  if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10620  Mismatch < RHSDesignator.Entries.size()) {
10621  const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10622  const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10623  if (!LF && !RF)
10624  Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10625  else if (!LF)
10626  Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10627  << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10628  << RF->getParent() << RF;
10629  else if (!RF)
10630  Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10631  << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10632  << LF->getParent() << LF;
10633  else if (!LF->getParent()->isUnion() &&
10634  LF->getAccess() != RF->getAccess())
10635  Info.CCEDiag(E,
10636  diag::note_constexpr_pointer_comparison_differing_access)
10637  << LF << LF->getAccess() << RF << RF->getAccess()
10638  << LF->getParent();
10639  }
10640  }
10641 
10642  // The comparison here must be unsigned, and performed with the same
10643  // width as the pointer.
10644  unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10645  uint64_t CompareLHS = LHSOffset.getQuantity();
10646  uint64_t CompareRHS = RHSOffset.getQuantity();
10647  assert(PtrSize <= 64 && "Unexpected pointer width");
10648  uint64_t Mask = ~0ULL >> (64 - PtrSize);
10649  CompareLHS &= Mask;
10650  CompareRHS &= Mask;
10651 
10652  // If there is a base and this is a relational operator, we can only
10653  // compare pointers within the object in question; otherwise, the result
10654  // depends on where the object is located in memory.
10655  if (!LHSValue.Base.isNull() && IsRelational) {
10656  QualType BaseTy = getType(LHSValue.Base);
10657  if (BaseTy->isIncompleteType())
10658  return Error(E);
10659  CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10660  uint64_t OffsetLimit = Size.getQuantity();
10661  if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10662  return Error(E);
10663  }
10664 
10665  if (CompareLHS < CompareRHS)
10666  return Success(CCR::Less, E);
10667  if (CompareLHS > CompareRHS)
10668  return Success(CCR::Greater, E);
10669  return Success(CCR::Equal, E);
10670  }
10671 
10672  if (LHSTy->isMemberPointerType()) {
10673  assert(IsEquality && "unexpected member pointer operation");
10674  assert(RHSTy->isMemberPointerType() && "invalid comparison");
10675 
10676  MemberPtr LHSValue, RHSValue;
10677 
10678  bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10679  if (!LHSOK && !Info.noteFailure())
10680  return false;
10681 
10682  if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10683  return false;
10684 
10685  // C++11 [expr.eq]p2:
10686  // If both operands are null, they compare equal. Otherwise if only one is
10687  // null, they compare unequal.
10688  if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10689  bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10690  return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10691  }
10692 
10693  // Otherwise if either is a pointer to a virtual member function, the
10694  // result is unspecified.
10695  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10696  if (MD->isVirtual())
10697  Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10698  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10699  if (MD->isVirtual())
10700  Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10701 
10702  // Otherwise they compare equal if and only if they would refer to the
10703  // same member of the same most derived object or the same subobject if
10704  // they were dereferenced with a hypothetical object of the associated
10705  // class type.
10706  bool Equal = LHSValue == RHSValue;
10707  return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10708  }
10709 
10710  if (LHSTy->isNullPtrType()) {
10711  assert(E->isComparisonOp() && "unexpected nullptr operation");
10712  assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10713  // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10714  // are compared, the result is true of the operator is <=, >= or ==, and
10715  // false otherwise.
10716  return Success(CCR::Equal, E);
10717  }
10718 
10719  return DoAfter();
10720 }
10721 
10722 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10723  if (!CheckLiteralType(Info, E))
10724  return false;
10725 
10726  auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10727  const BinaryOperator *E) {
10728  // Evaluation succeeded. Lookup the information for the comparison category
10729  // type and fetch the VarDecl for the result.
10730  const ComparisonCategoryInfo &CmpInfo =
10731  Info.Ctx.CompCategories.getInfoForType(E->getType());
10732  const VarDecl *VD =
10733  CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10734  // Check and evaluate the result as a constant expression.
10735  LValue LV;
10736  LV.set(VD);
10737  if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10738  return false;
10739  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10740  };
10741  return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10742  return ExprEvaluatorBaseTy::VisitBinCmp(E);
10743  });
10744 }
10745 
10746 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10747  // We don't call noteFailure immediately because the assignment happens after
10748  // we evaluate LHS and RHS.
10749  if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10750  return Error(E);
10751 
10752  DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10753  if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10754  return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10755 
10756  assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10758  "DataRecursiveIntBinOpEvaluator should have handled integral types");
10759 
10760  if (E->isComparisonOp()) {
10761  // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10762  // comparisons and then translating the result.
10763  auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10764  const BinaryOperator *E) {
10765  using CCR = ComparisonCategoryResult;
10766  bool IsEqual = ResKind == CCR::Equal,
10767  IsLess = ResKind == CCR::Less,
10768  IsGreater = ResKind == CCR::Greater;
10769  auto Op = E->getOpcode();
10770  switch (Op) {
10771  default:
10772  llvm_unreachable("unsupported binary operator");
10773  case BO_EQ:
10774  case BO_NE:
10775  return Success(IsEqual == (Op == BO_EQ), E);
10776  case BO_LT: return Success(IsLess, E);
10777  case BO_GT: return Success(IsGreater, E);
10778  case BO_LE: return Success(IsEqual || IsLess, E);
10779  case BO_GE: return Success(IsEqual || IsGreater, E);
10780  }
10781  };
10782  return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10783  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10784  });
10785  }
10786 
10787  QualType LHSTy = E->getLHS()->getType();
10788  QualType RHSTy = E->getRHS()->getType();
10789 
10790  if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10791  E->getOpcode() == BO_Sub) {
10792  LValue LHSValue, RHSValue;
10793 
10794  bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10795  if (!LHSOK && !Info.noteFailure())
10796  return false;
10797 
10798  if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10799  return false;
10800 
10801  // Reject differing bases from the normal codepath; we special-case
10802  // comparisons to null.
10803  if (!HasSameBase(LHSValue, RHSValue)) {
10804  // Handle &&A - &&B.
10805  if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10806  return Error(E);
10807  const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10808  const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10809  if (!LHSExpr || !RHSExpr)
10810  return Error(E);
10811  const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10812  const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10813  if (!LHSAddrExpr || !RHSAddrExpr)
10814  return Error(E);
10815  // Make sure both labels come from the same function.
10816  if (LHSAddrExpr->getLabel()->getDeclContext() !=
10817  RHSAddrExpr->getLabel()->getDeclContext())
10818  return Error(E);
10819  return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10820  }
10821  const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10822  const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10823 
10824  SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10825  SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10826 
10827  // C++11 [expr.add]p6:
10828  // Unless both pointers point to elements of the same array object, or
10829  // one past the last element of the array object, the behavior is
10830  // undefined.
10831  if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10832  !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10833  RHSDesignator))
10834  Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10835 
10836  QualType Type = E->getLHS()->getType();
10837  QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10838 
10839  CharUnits ElementSize;
10840  if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10841  return false;
10842 
10843  // As an extension, a type may have zero size (empty struct or union in
10844  // C, array of zero length). Pointer subtraction in such cases has
10845  // undefined behavior, so is not constant.
10846  if (ElementSize.isZero()) {
10847  Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10848  << ElementType;
10849  return false;
10850  }
10851 
10852  // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10853  // and produce incorrect results when it overflows. Such behavior
10854  // appears to be non-conforming, but is common, so perhaps we should
10855  // assume the standard intended for such cases to be undefined behavior
10856  // and check for them.
10857 
10858  // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10859  // overflow in the final conversion to ptrdiff_t.
10860  APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10861  APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10862  APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10863  false);
10864  APSInt TrueResult = (LHS - RHS) / ElemSize;
10865  APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10866 
10867  if (Result.extend(65) != TrueResult &&
10868  !HandleOverflow(Info, E, TrueResult, E->getType()))
10869  return false;
10870  return Success(Result, E);
10871  }
10872 
10873  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10874 }
10875 
10876 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10877 /// a result as the expression's type.
10878 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10879  const UnaryExprOrTypeTraitExpr *E) {
10880  switch(E->getKind()) {
10881  case UETT_PreferredAlignOf:
10882  case UETT_AlignOf: {
10883  if (E->isArgumentType())
10884  return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10885  E);
10886  else
10887  return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10888  E);
10889  }
10890 
10891  case UETT_VecStep: {
10892  QualType Ty = E->getTypeOfArgument();
10893 
10894  if (Ty->isVectorType()) {
10895  unsigned n = Ty->castAs<VectorType>()->getNumElements();
10896 
10897  // The vec_step built-in functions that take a 3-component
10898  // vector return 4. (OpenCL 1.1 spec 6.11.12)
10899  if (n == 3)
10900  n = 4;
10901 
10902  return Success(n, E);
10903  } else
10904  return Success(1, E);
10905  }
10906 
10907  case UETT_SizeOf: {
10908  QualType SrcTy = E->getTypeOfArgument();
10909  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10910  // the result is the size of the referenced type."
10911  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10912  SrcTy = Ref->getPointeeType();
10913 
10914  CharUnits Sizeof;
10915  if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10916  return false;
10917  return Success(Sizeof, E);
10918  }
10920  assert(E->isArgumentType());
10921  return Success(
10922  Info.Ctx.toCharUnitsFromBits(
10923  Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10924  .getQuantity(),
10925  E);
10926  }
10927 
10928  llvm_unreachable("unknown expr/type trait");
10929 }
10930 
10931 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10932  CharUnits Result;
10933  unsigned n = OOE->getNumComponents();
10934  if (n == 0)
10935  return Error(OOE);
10936  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10937  for (unsigned i = 0; i != n; ++i) {
10938  OffsetOfNode ON = OOE->getComponent(i);
10939  switch (ON.getKind()) {
10940  case OffsetOfNode::Array: {
10941  const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10942  APSInt IdxResult;
10943  if (!EvaluateInteger(Idx, IdxResult, Info))
10944  return false;
10945  const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10946  if (!AT)
10947  return Error(OOE);
10948  CurrentType = AT->getElementType();
10949  CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10950  Result += IdxResult.getSExtValue() * ElementSize;
10951  break;
10952  }
10953 
10954  case OffsetOfNode::Field: {
10955  FieldDecl *MemberDecl = ON.getField();
10956  const RecordType *RT = CurrentType->getAs<RecordType>();
10957  if (!RT)
10958  return Error(OOE);
10959  RecordDecl *RD = RT->getDecl();
10960  if (RD->isInvalidDecl()) return false;
10961  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10962  unsigned i = MemberDecl->getFieldIndex();
10963  assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10964  Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10965  CurrentType = MemberDecl->getType().getNonReferenceType();
10966  break;
10967  }
10968 
10970  llvm_unreachable("dependent __builtin_offsetof");
10971 
10972  case OffsetOfNode::Base: {
10973  CXXBaseSpecifier *BaseSpec = ON.getBase();
10974  if (BaseSpec->isVirtual())
10975  return Error(OOE);
10976 
10977  // Find the layout of the class whose base we are looking into.
10978  const RecordType *RT = CurrentType->getAs<RecordType>();
10979  if (!RT)
10980  return Error(OOE);
10981  RecordDecl *RD = RT->getDecl();
10982  if (RD->isInvalidDecl()) return false;
10983  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10984 
10985  // Find the base class itself.
10986  CurrentType = BaseSpec->getType();
10987  const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10988  if (!BaseRT)
10989  return Error(OOE);
10990 
10991  // Add the offset to the base.
10992  Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10993  break;
10994  }
10995  }
10996  }
10997  return Success(Result, OOE);
10998 }
10999 
11000 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11001  switch (E->getOpcode()) {
11002  default:
11003  // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11004  // See C99 6.6p3.
11005  return Error(E);
11006  case UO_Extension:
11007  // FIXME: Should extension allow i-c-e extension expressions in its scope?
11008  // If so, we could clear the diagnostic ID.
11009  return Visit(E->getSubExpr());
11010  case UO_Plus:
11011  // The result is just the value.
11012  return Visit(E->getSubExpr());
11013  case UO_Minus: {
11014  if (!Visit(E->getSubExpr()))
11015  return false;
11016  if (!Result.isInt()) return Error(E);
11017  const APSInt &Value = Result.getInt();
11018  if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11019  !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11020  E->getType()))
11021  return false;
11022  return Success(-Value, E);
11023  }
11024  case UO_Not: {
11025  if (!Visit(E->getSubExpr()))
11026  return false;
11027  if (!Result.isInt()) return Error(E);
11028  return Success(~Result.getInt(), E);
11029  }
11030  case UO_LNot: {
11031  bool bres;
11032  if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11033  return false;
11034  return Success(!bres, E);
11035  }
11036  }
11037 }
11038 
11039 /// HandleCast - This is used to evaluate implicit or explicit casts where the
11040 /// result type is integer.
11041 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11042  const Expr *SubExpr = E->getSubExpr();
11043  QualType DestType = E->getType();
11044  QualType SrcType = SubExpr->getType();
11045 
11046  switch (E->getCastKind()) {
11047  case CK_BaseToDerived:
11048  case CK_DerivedToBase:
11049  case CK_UncheckedDerivedToBase:
11050  case CK_Dynamic:
11051  case CK_ToUnion:
11052  case CK_ArrayToPointerDecay:
11053  case CK_FunctionToPointerDecay:
11054  case CK_NullToPointer:
11055  case CK_NullToMemberPointer:
11056  case CK_BaseToDerivedMemberPointer:
11057  case CK_DerivedToBaseMemberPointer:
11058  case CK_ReinterpretMemberPointer:
11059  case CK_ConstructorConversion:
11060  case CK_IntegralToPointer:
11061  case CK_ToVoid:
11062  case CK_VectorSplat:
11063  case CK_IntegralToFloating:
11064  case CK_FloatingCast:
11065  case CK_CPointerToObjCPointerCast:
11066  case CK_BlockPointerToObjCPointerCast:
11067  case CK_AnyPointerToBlockPointerCast:
11068  case CK_ObjCObjectLValueCast:
11069  case CK_FloatingRealToComplex:
11070  case CK_FloatingComplexToReal:
11071  case CK_FloatingComplexCast:
11072  case CK_FloatingComplexToIntegralComplex:
11073  case CK_IntegralRealToComplex:
11074  case CK_IntegralComplexCast:
11075  case CK_IntegralComplexToFloatingComplex:
11076  case CK_BuiltinFnToFnPtr:
11077  case CK_ZeroToOCLOpaqueType:
11078  case CK_NonAtomicToAtomic:
11079  case CK_AddressSpaceConversion:
11080  case CK_IntToOCLSampler:
11081  case CK_FixedPointCast:
11082  case CK_IntegralToFixedPoint:
11083  llvm_unreachable("invalid cast kind for integral value");
11084 
11085  case CK_BitCast:
11086  case CK_Dependent:
11087  case CK_LValueBitCast:
11088  case CK_ARCProduceObject:
11089  case CK_ARCConsumeObject:
11090  case CK_ARCReclaimReturnedObject:
11091  case CK_ARCExtendBlockObject:
11092  case CK_CopyAndAutoreleaseBlockObject:
11093  return Error(E);
11094 
11095  case CK_UserDefinedConversion:
11096  case CK_LValueToRValue:
11097  case CK_AtomicToNonAtomic:
11098  case CK_NoOp:
11099  case CK_LValueToRValueBitCast:
11100  return ExprEvaluatorBaseTy::VisitCastExpr(E);
11101 
11102  case CK_MemberPointerToBoolean:
11103  case CK_PointerToBoolean:
11104  case CK_IntegralToBoolean:
11105  case CK_FloatingToBoolean:
11106  case CK_BooleanToSignedIntegral:
11107  case CK_FloatingComplexToBoolean:
11108  case CK_IntegralComplexToBoolean: {
11109  bool BoolResult;
11110  if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11111  return false;
11112  uint64_t IntResult = BoolResult;
11113  if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11114  IntResult = (uint64_t)-1;
11115  return Success(IntResult, E);
11116  }
11117 
11118  case CK_FixedPointToIntegral: {
11119  APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11120  if (!EvaluateFixedPoint(SubExpr, Src, Info))
11121  return false;
11122  bool Overflowed;
11123  llvm::APSInt Result = Src.convertToInt(
11124  Info.Ctx.getIntWidth(DestType),
11125  DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11126  if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11127  return false;
11128  return Success(Result, E);
11129  }
11130 
11131  case CK_FixedPointToBoolean: {
11132  // Unsigned padding does not affect this.
11133  APValue Val;
11134  if (!Evaluate(Val, Info, SubExpr))
11135  return false;
11136  return Success(Val.getFixedPoint().getBoolValue(), E);
11137  }
11138 
11139  case CK_IntegralCast: {
11140  if (!Visit(SubExpr))
11141  return false;
11142 
11143  if (!Result.isInt()) {
11144  // Allow casts of address-of-label differences if they are no-ops
11145  // or narrowing. (The narrowing case isn't actually guaranteed to
11146  // be constant-evaluatable except in some narrow cases which are hard
11147  // to detect here. We let it through on the assumption the user knows
11148  // what they are doing.)
11149  if (Result.isAddrLabelDiff())
11150  return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11151  // Only allow casts of lvalues if they are lossless.
11152  return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11153  }
11154 
11155  return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11156  Result.getInt()), E);
11157  }
11158 
11159  case CK_PointerToIntegral: {
11160  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11161 
11162  LValue LV;
11163  if (!EvaluatePointer(SubExpr, LV, Info))
11164  return false;
11165 
11166  if (LV.getLValueBase()) {
11167  // Only allow based lvalue casts if they are lossless.
11168  // FIXME: Allow a larger integer size than the pointer size, and allow
11169  // narrowing back down to pointer width in subsequent integral casts.
11170  // FIXME: Check integer type's active bits, not its type size.
11171  if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11172  return Error(E);
11173 
11174  LV.Designator.setInvalid();
11175  LV.moveInto(Result);
11176  return true;
11177  }
11178 
11179  APSInt AsInt;
11180  APValue V;
11181  LV.moveInto(V);
11182  if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11183  llvm_unreachable("Can't cast this!");
11184 
11185  return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11186  }
11187 
11188  case CK_IntegralComplexToReal: {
11189  ComplexValue C;
11190  if (!EvaluateComplex(SubExpr, C, Info))
11191  return false;
11192  return Success(C.getComplexIntReal(), E);
11193  }
11194 
11195  case CK_FloatingToIntegral: {
11196  APFloat F(0.0);
11197  if (!EvaluateFloat(SubExpr, F, Info))
11198  return false;
11199 
11200  APSInt Value;
11201  if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11202  return false;
11203  return Success(Value, E);
11204  }
11205  }
11206 
11207  llvm_unreachable("unknown cast resulting in integral value");
11208 }
11209 
11210 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11211  if (E->getSubExpr()->getType()->isAnyComplexType()) {
11212  ComplexValue LV;
11213  if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11214  return false;
11215  if (!LV.isComplexInt())
11216  return Error(E);
11217  return Success(LV.getComplexIntReal(), E);
11218  }
11219 
11220  return Visit(E->getSubExpr());
11221 }
11222 
11223 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11224  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11225  ComplexValue LV;
11226  if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11227  return false;
11228  if (!LV.isComplexInt())
11229  return Error(E);
11230  return Success(LV.getComplexIntImag(), E);
11231  }
11232 
11233  VisitIgnoredValue(E->getSubExpr());
11234  return Success(0, E);
11235 }
11236 
11237 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11238  return Success(E->getPackLength(), E);
11239 }
11240 
11241 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11242  return Success(E->getValue(), E);
11243 }
11244 
11245 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11246  switch (E->getOpcode()) {
11247  default:
11248  // Invalid unary operators
11249  return Error(E);
11250  case UO_Plus:
11251  // The result is just the value.
11252  return Visit(E->getSubExpr());
11253  case UO_Minus: {
11254  if (!Visit(E->getSubExpr())) return false;
11255  if (!Result.isFixedPoint())
11256  return Error(E);
11257  bool Overflowed;
11258  APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11259  if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11260  return false;
11261  return Success(Negated, E);
11262  }
11263  case UO_LNot: {
11264  bool bres;
11265  if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11266  return false;
11267  return Success(!bres, E);
11268  }
11269  }
11270 }
11271 
11272 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11273  const Expr *SubExpr = E->getSubExpr();
11274  QualType DestType = E->getType();
11275  assert(DestType->isFixedPointType() &&
11276  "Expected destination type to be a fixed point type");
11277  auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11278 
11279  switch (E->getCastKind()) {
11280  case CK_FixedPointCast: {
11281  APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11282  if (!EvaluateFixedPoint(SubExpr, Src, Info))
11283  return false;
11284  bool Overflowed;
11285  APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11286  if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11287  return false;
11288  return Success(Result, E);
11289  }
11290  case CK_IntegralToFixedPoint: {
11291  APSInt Src;
11292  if (!EvaluateInteger(SubExpr, Src, Info))
11293  return false;
11294 
11295  bool Overflowed;
11297  Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11298 
11299  if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11300  return false;
11301 
11302  return Success(IntResult, E);
11303  }
11304  case CK_NoOp:
11305  case CK_LValueToRValue:
11306  return ExprEvaluatorBaseTy::VisitCastExpr(E);
11307  default:
11308  return Error(E);
11309  }
11310 }
11311 
11312 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11313  const Expr *LHS = E->getLHS();
11314  const Expr *RHS = E->getRHS();
11315  FixedPointSemantics ResultFXSema =
11316  Info.Ctx.getFixedPointSemantics(E->getType());
11317 
11318  APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11319  if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11320  return false;
11321  APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11322  if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11323  return false;
11324 
11325  switch (E->getOpcode()) {
11326  case BO_Add: {
11327  bool AddOverflow, ConversionOverflow;
11328  APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11329  .convert(ResultFXSema, &ConversionOverflow);
11330  if ((AddOverflow || ConversionOverflow) &&
11331  !HandleOverflow(Info, E, Result, E->getType()))
11332  return false;
11333  return Success(Result, E);
11334  }
11335  default:
11336  return false;
11337  }
11338  llvm_unreachable("Should've exited before this");
11339 }
11340 
11341 //===----------------------------------------------------------------------===//
11342 // Float Evaluation
11343 //===----------------------------------------------------------------------===//
11344 
11345 namespace {
11346 class FloatExprEvaluator
11347  : public ExprEvaluatorBase<FloatExprEvaluator> {
11348  APFloat &Result;
11349 public:
11350  FloatExprEvaluator(EvalInfo &info, APFloat &result)
11351  : ExprEvaluatorBaseTy(info), Result(result) {}
11352 
11353  bool Success(const APValue &V, const Expr *e) {
11354  Result = V.getFloat();
11355  return true;
11356  }
11357 
11358  bool ZeroInitialization(const Expr *E) {
11359  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11360  return true;
11361  }
11362 
11363  bool VisitCallExpr(const CallExpr *E);
11364 
11365  bool VisitUnaryOperator(const UnaryOperator *E);
11366  bool VisitBinaryOperator(const BinaryOperator *E);
11367  bool VisitFloatingLiteral(const FloatingLiteral *E);
11368  bool VisitCastExpr(const CastExpr *E);
11369 
11370  bool VisitUnaryReal(const UnaryOperator *E);
11371  bool VisitUnaryImag(const UnaryOperator *E);
11372 
11373  // FIXME: Missing: array subscript of vector, member of vector
11374 };
11375 } // end anonymous namespace
11376 
11377 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11378  assert(E->isRValue() && E->getType()->isRealFloatingType());
11379  return FloatExprEvaluator(Info, Result).Visit(E);
11380 }
11381 
11382 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11383  QualType ResultTy,
11384  const Expr *Arg,
11385  bool SNaN,
11386  llvm::APFloat &Result) {
11387  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11388  if (!S) return false;
11389 
11390  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11391 
11392  llvm::APInt fill;
11393 
11394  // Treat empty strings as if they were zero.
11395  if (S->getString().empty())
11396  fill = llvm::APInt(32, 0);
11397  else if (S->getString().getAsInteger(0, fill))
11398  return false;
11399 
11400  if (Context.getTargetInfo().isNan2008()) {
11401  if (SNaN)
11402  Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11403  else
11404  Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11405  } else {
11406  // Prior to IEEE 754-2008, architectures were allowed to choose whether
11407  // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11408  // a different encoding to what became a standard in 2008, and for pre-
11409  // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11410  // sNaN. This is now known as "legacy NaN" encoding.
11411  if (SNaN)
11412  Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11413  else
11414  Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11415  }
11416 
11417  return true;
11418 }
11419 
11420 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11421  switch (E->getBuiltinCallee()) {
11422  default:
11423  return ExprEvaluatorBaseTy::VisitCallExpr(E);
11424 
11425  case Builtin::BI__builtin_huge_val:
11426  case Builtin::BI__builtin_huge_valf:
11427  case Builtin::BI__builtin_huge_vall:
11428  case Builtin::BI__builtin_huge_valf128:
11429  case Builtin::BI__builtin_inf:
11430  case Builtin::BI__builtin_inff:
11431  case Builtin::BI__builtin_infl:
11432  case Builtin::BI__builtin_inff128: {
11433  const llvm::fltSemantics &Sem =
11434  Info.Ctx.getFloatTypeSemantics(E->getType());
11435  Result = llvm::APFloat::getInf(Sem);
11436  return true;
11437  }
11438 
11439  case Builtin::BI__builtin_nans:
11440  case Builtin::BI__builtin_nansf:
11441  case Builtin::BI__builtin_nansl:
11442  case Builtin::BI__builtin_nansf128:
11443  if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11444  true, Result))
11445  return Error(E);
11446  return true;
11447 
11448  case Builtin::BI__builtin_nan:
11449  case Builtin::BI__builtin_nanf:
11450  case Builtin::BI__builtin_nanl:
11451  case Builtin::BI__builtin_nanf128:
11452  // If this is __builtin_nan() turn this into a nan, otherwise we
11453  // can't constant fold it.
11454  if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11455  false, Result))
11456  return Error(E);
11457  return true;
11458 
11459  case Builtin::BI__builtin_fabs:
11460  case Builtin::BI__builtin_fabsf:
11461  case Builtin::BI__builtin_fabsl:
11462  case Builtin::BI__builtin_fabsf128:
11463  if (!EvaluateFloat(E->getArg(0), Result, Info))
11464  return false;
11465 
11466  if (Result.isNegative())
11467  Result.changeSign();
11468  return true;
11469 
11470  // FIXME: Builtin::BI__builtin_powi
11471  // FIXME: Builtin::BI__builtin_powif
11472  // FIXME: Builtin::BI__builtin_powil
11473 
11474  case Builtin::BI__builtin_copysign:
11475  case Builtin::BI__builtin_copysignf:
11476  case Builtin::BI__builtin_copysignl:
11477  case Builtin::BI__builtin_copysignf128: {
11478  APFloat RHS(0.);
11479  if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11480  !EvaluateFloat(E->getArg(1), RHS, Info))
11481  return false;
11482  Result.copySign(RHS);
11483  return true;
11484  }
11485  }
11486 }
11487 
11488 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11489  if (E->getSubExpr()->getType()->isAnyComplexType()) {
11490  ComplexValue CV;
11491  if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11492  return false;
11493  Result = CV.FloatReal;
11494  return true;
11495  }
11496 
11497  return Visit(E->getSubExpr());
11498 }
11499 
11500 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11501  if (E->getSubExpr()->getType()->isAnyComplexType()) {
11502  ComplexValue CV;
11503  if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11504  return false;
11505  Result = CV.FloatImag;
11506  return true;
11507  }
11508 
11509  VisitIgnoredValue(E->getSubExpr());
11510  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11511  Result = llvm::APFloat::getZero(Sem);
11512  return true;
11513 }
11514 
11515 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11516  switch (E->getOpcode()) {
11517  default: return Error(E);
11518  case UO_Plus:
11519  return EvaluateFloat(E->getSubExpr(), Result, Info);
11520  case UO_Minus:
11521  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11522  return false;
11523  Result.changeSign();
11524  return true;
11525  }
11526 }
11527 
11528 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11529  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11530  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11531 
11532  APFloat RHS(0.0);
11533  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11534  if (!LHSOK && !Info.noteFailure())
11535  return false;
11536  return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11537  handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11538 }
11539 
11540 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11541  Result = E->getValue();
11542  return true;
11543 }
11544 
11545 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11546  const Expr* SubExpr = E->getSubExpr();
11547 
11548  switch (E->getCastKind()) {
11549  default:
11550  return ExprEvaluatorBaseTy::VisitCastExpr(E);
11551 
11552  case CK_IntegralToFloating: {
11553  APSInt IntResult;
11554  return EvaluateInteger(SubExpr, IntResult, Info) &&
11555  HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11556  E->getType(), Result);
11557  }
11558 
11559  case CK_FloatingCast: {
11560  if (!Visit(SubExpr))
11561  return false;
11562  return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11563  Result);
11564  }
11565 
11566  case CK_FloatingComplexToReal: {
11567  ComplexValue V;
11568  if (!EvaluateComplex(SubExpr, V, Info))
11569  return false;
11570  Result = V.getComplexFloatReal();
11571  return true;
11572  }
11573  }
11574 }
11575 
11576 //===----------------------------------------------------------------------===//
11577 // Complex Evaluation (for float and integer)
11578 //===----------------------------------------------------------------------===//
11579 
11580 namespace {
11581 class ComplexExprEvaluator
11582  : public ExprEvaluatorBase<ComplexExprEvaluator> {
11583  ComplexValue &Result;
11584 
11585 public:
11586  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11587  : ExprEvaluatorBaseTy(info), Result(Result) {}
11588 
11589  bool Success(const APValue &V, const Expr *e) {
11590  Result.setFrom(V);
11591  return true;
11592  }
11593 
11594  bool ZeroInitialization(const Expr *E);
11595 
11596  //===--------------------------------------------------------------------===//
11597  // Visitor Methods
11598  //===--------------------------------------------------------------------===//
11599 
11600  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11601  bool VisitCastExpr(const CastExpr *E);
11602  bool VisitBinaryOperator(const BinaryOperator *E);
11603  bool VisitUnaryOperator(const UnaryOperator *E);
11604  bool VisitInitListExpr(const InitListExpr *E);
11605 };
11606 } // end anonymous namespace
11607 
11608 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11609  EvalInfo &Info) {
11610  assert(E->isRValue() && E->getType()->isAnyComplexType());
11611  return ComplexExprEvaluator(Info, Result).Visit(E);
11612 }
11613 
11614 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11615  QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11616  if (ElemTy->isRealFloatingType()) {
11617  Result.makeComplexFloat();
11618  APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11619  Result.FloatReal = Zero;
11620  Result.FloatImag = Zero;
11621  } else {
11622  Result.makeComplexInt();
11623  APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11624  Result.IntReal = Zero;
11625  Result.IntImag = Zero;
11626  }
11627  return true;
11628 }
11629 
11630 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11631  const Expr* SubExpr = E->getSubExpr();
11632 
11633  if (SubExpr->getType()->isRealFloatingType()) {
11634  Result.makeComplexFloat();
11635  APFloat &Imag = Result.FloatImag;
11636  if (!EvaluateFloat(SubExpr, Imag, Info))
11637  return false;
11638 
11639  Result.FloatReal = APFloat(Imag.getSemantics());
11640  return true;
11641  } else {
11642  assert(SubExpr->getType()->isIntegerType() &&
11643  "Unexpected imaginary literal.");
11644 
11645  Result.makeComplexInt();
11646  APSInt &Imag = Result.IntImag;
11647  if (!EvaluateInteger(SubExpr, Imag, Info))
11648  return false;
11649 
11650  Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11651  return true;
11652  }
11653 }
11654 
11655 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11656 
11657  switch (E->getCastKind()) {
11658  case CK_BitCast:
11659  case CK_BaseToDerived:
11660  case CK_DerivedToBase:
11661  case CK_UncheckedDerivedToBase:
11662  case CK_Dynamic:
11663  case CK_ToUnion:
11664  case CK_ArrayToPointerDecay:
11665  case CK_FunctionToPointerDecay:
11666  case CK_NullToPointer:
11667  case CK_NullToMemberPointer:
11668  case CK_BaseToDerivedMemberPointer:
11669  case CK_DerivedToBaseMemberPointer:
11670  case CK_MemberPointerToBoolean:
11671  case CK_ReinterpretMemberPointer:
11672  case CK_ConstructorConversion:
11673  case CK_IntegralToPointer:
11674  case CK_PointerToIntegral:
11675  case CK_PointerToBoolean:
11676  case CK_ToVoid:
11677  case CK_VectorSplat:
11678  case CK_IntegralCast:
11679  case CK_BooleanToSignedIntegral:
11680  case CK_IntegralToBoolean:
11681  case CK_IntegralToFloating:
11682  case CK_FloatingToIntegral:
11683  case CK_FloatingToBoolean:
11684  case CK_FloatingCast:
11685  case CK_CPointerToObjCPointerCast:
11686  case CK_BlockPointerToObjCPointerCast:
11687  case CK_AnyPointerToBlockPointerCast:
11688  case CK_ObjCObjectLValueCast:
11689  case CK_FloatingComplexToReal:
11690  case CK_FloatingComplexToBoolean:
11691  case CK_IntegralComplexToReal:
11692  case CK_IntegralComplexToBoolean:
11693  case CK_ARCProduceObject:
11694  case CK_ARCConsumeObject:
11695  case CK_ARCReclaimReturnedObject:
11696  case CK_ARCExtendBlockObject:
11697  case CK_CopyAndAutoreleaseBlockObject:
11698  case CK_BuiltinFnToFnPtr:
11699  case CK_ZeroToOCLOpaqueType:
11700  case CK_NonAtomicToAtomic:
11701  case CK_AddressSpaceConversion:
11702  case CK_IntToOCLSampler:
11703  case CK_FixedPointCast:
11704  case CK_FixedPointToBoolean:
11705  case CK_FixedPointToIntegral:
11706  case CK_IntegralToFixedPoint:
11707  llvm_unreachable("invalid cast kind for complex value");
11708 
11709  case CK_LValueToRValue:
11710  case CK_AtomicToNonAtomic:
11711  case CK_NoOp:
11712  case CK_LValueToRValueBitCast:
11713  return ExprEvaluatorBaseTy::VisitCastExpr(E);
11714 
11715  case CK_Dependent:
11716  case CK_LValueBitCast:
11717  case CK_UserDefinedConversion:
11718  return Error(E);
11719 
11720  case CK_FloatingRealToComplex: {
11721  APFloat &Real = Result.FloatReal;
11722  if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11723  return false;
11724 
11725  Result.makeComplexFloat();
11726  Result.FloatImag = APFloat(Real.getSemantics());
11727  return true;
11728  }
11729 
11730  case CK_FloatingComplexCast: {
11731  if (!Visit(E->getSubExpr()))
11732  return false;
11733 
11734  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11735  QualType From
11736  = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11737 
11738  return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11739  HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11740  }
11741 
11742  case CK_FloatingComplexToIntegralComplex: {
11743  if (!Visit(E->getSubExpr()))
11744  return false;
11745 
11746  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11747  QualType From
11748  = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11749  Result.makeComplexInt();
11750  return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11751  To, Result.IntReal) &&
11752  HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11753  To, Result.IntImag);
11754  }
11755 
11756  case CK_IntegralRealToComplex: {
11757  APSInt &Real = Result.IntReal;
11758  if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11759  return false;
11760 
11761  Result.makeComplexInt();
11762  Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11763  return true;
11764  }
11765 
11766  case CK_IntegralComplexCast: {
11767  if (!Visit(E->getSubExpr()))
11768  return false;
11769 
11770  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11771  QualType From
11772  = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11773 
11774  Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11775  Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11776  return true;
11777  }
11778 
11779  case CK_IntegralComplexToFloatingComplex: {
11780  if (!Visit(E->getSubExpr()))
11781  return false;
11782 
11783  QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11784  QualType From
11785  = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11786  Result.makeComplexFloat();
11787  return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11788  To, Result.FloatReal) &&
11789  HandleIntToFloatCast(Info, E, From, Result.IntImag,
11790  To, Result.FloatImag);
11791  }
11792  }
11793 
11794  llvm_unreachable("unknown cast resulting in complex value");
11795 }
11796 
11797 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11798  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11799  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11800 
11801  // Track whether the LHS or RHS is real at the type system level. When this is
11802  // the case we can simplify our evaluation strategy.
11803  bool LHSReal = false, RHSReal = false;
11804 
11805  bool LHSOK;
11806  if (E->getLHS()->getType()->isRealFloatingType()) {
11807  LHSReal = true;
11808  APFloat &Real = Result.FloatReal;
11809  LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11810  if (LHSOK) {
11811  Result.makeComplexFloat();
11812  Result.FloatImag = APFloat(Real.getSemantics());
11813  }
11814  } else {
11815  LHSOK = Visit(E->getLHS());
11816  }
11817  if (!LHSOK && !Info.noteFailure())
11818  return false;
11819 
11820  ComplexValue RHS;
11821  if (E->getRHS()->getType()->isRealFloatingType()) {
11822  RHSReal = true;
11823  APFloat &Real = RHS.FloatReal;
11824  if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11825  return false;
11826  RHS.makeComplexFloat();
11827  RHS.FloatImag = APFloat(Real.getSemantics());
11828  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11829  return false;
11830 
11831  assert(!(LHSReal && RHSReal) &&
11832  "Cannot have both operands of a complex operation be real.");
11833  switch (E->getOpcode()) {
11834  default: return Error(E);
11835  case BO_Add:
11836  if (Result.isComplexFloat()) {
11837  Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11838  APFloat::rmNearestTiesToEven);
11839  if (LHSReal)
11840  Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11841  else if (!RHSReal)
11842  Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11843  APFloat::rmNearestTiesToEven);
11844  } else {
11845  Result.getComplexIntReal() += RHS.getComplexIntReal();
11846  Result.getComplexIntImag() += RHS.getComplexIntImag();
11847  }
11848  break;
11849  case BO_Sub:
11850  if (Result.isComplexFloat()) {
11851  Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11852  APFloat::rmNearestTiesToEven);
11853  if (LHSReal) {
11854  Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11855  Result.getComplexFloatImag().changeSign();
11856  } else if (!RHSReal) {
11857  Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11858  APFloat::rmNearestTiesToEven);
11859  }
11860  } else {
11861  Result.getComplexIntReal() -= RHS.getComplexIntReal();
11862  Result.getComplexIntImag() -= RHS.getComplexIntImag();
11863  }
11864  break;
11865  case BO_Mul:
11866  if (Result.isComplexFloat()) {
11867  // This is an implementation of complex multiplication according to the
11868  // constraints laid out in C11 Annex G. The implementation uses the
11869  // following naming scheme:
11870  // (a + ib) * (c + id)
11871  ComplexValue LHS = Result;
11872  APFloat &A = LHS.getComplexFloatReal();
11873  APFloat &B = LHS.getComplexFloatImag();
11874  APFloat &C = RHS.getComplexFloatReal();
11875  APFloat &D = RHS.getComplexFloatImag();
11876  APFloat &ResR = Result.getComplexFloatReal();
11877  APFloat &ResI = Result.getComplexFloatImag();
11878  if (LHSReal) {
11879  assert(!RHSReal && "Cannot have two real operands for a complex op!");
11880  ResR = A * C;
11881  ResI = A * D;
11882  } else if (RHSReal) {
11883  ResR = C * A;
11884  ResI = C * B;
11885  } else {
11886  // In the fully general case, we need to handle NaNs and infinities
11887  // robustly.
11888  APFloat AC = A * C;
11889  APFloat BD = B * D;
11890  APFloat AD = A * D;
11891  APFloat BC = B * C;
11892  ResR = AC - BD;
11893  ResI = AD + BC;
11894  if (ResR.isNaN() && ResI.isNaN()) {
11895  bool Recalc = false;
11896  if (A.isInfinity() || B.isInfinity()) {
11897  A = APFloat::copySign(
11898  APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11899  B = APFloat::copySign(
11900  APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11901  if (C.isNaN())
11902  C = APFloat::copySign(APFloat(C.getSemantics()), C);
11903  if (D.isNaN())
11904  D = APFloat::copySign(APFloat(D.getSemantics()), D);
11905  Recalc = true;
11906  }
11907  if (C.isInfinity() || D.isInfinity()) {
11908  C = APFloat::copySign(
11909  APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11910  D = APFloat::copySign(
11911  APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11912  if (A.isNaN())
11913  A = APFloat::copySign(APFloat(A.getSemantics()), A);
11914  if (B.isNaN())
11915  B = APFloat::copySign(APFloat(B.getSemantics()), B);
11916  Recalc = true;
11917  }
11918  if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11919  AD.isInfinity() || BC.isInfinity())) {
11920  if (A.isNaN())
11921  A = APFloat::copySign(APFloat(A.getSemantics()), A);
11922  if (B.isNaN())
11923  B = APFloat::copySign(APFloat(B.getSemantics()), B);
11924  if (C.isNaN())
11925  C = APFloat::copySign(APFloat(C.getSemantics()), C);
11926  if (D.isNaN())
11927  D = APFloat::copySign(APFloat(D.getSemantics()), D);
11928  Recalc = true;
11929  }
11930  if (Recalc) {
11931  ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11932  ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11933  }
11934  }
11935  }
11936  } else {
11937  ComplexValue LHS = Result;
11938  Result.getComplexIntReal() =
11939  (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11940  LHS.getComplexIntImag() * RHS.getComplexIntImag());
11941  Result.getComplexIntImag() =
11942  (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11943  LHS.getComplexIntImag() * RHS.getComplexIntReal());
11944  }
11945  break;
11946  case BO_Div:
11947  if (Result.isComplexFloat()) {
11948  // This is an implementation of complex division according to the
11949  // constraints laid out in C11 Annex G. The implementation uses the
11950  // following naming scheme:
11951  // (a + ib) / (c + id)
11952  ComplexValue LHS = Result;
11953  APFloat &A = LHS.getComplexFloatReal();
11954  APFloat &B = LHS.getComplexFloatImag();
11955  APFloat &C = RHS.getComplexFloatReal();
11956  APFloat &D = RHS.getComplexFloatImag();
11957  APFloat &ResR = Result.getComplexFloatReal();
11958  APFloat &ResI = Result.getComplexFloatImag();
11959  if (RHSReal) {
11960  ResR = A / C;
11961  ResI = B / C;
11962  } else {
11963  if (LHSReal) {
11964  // No real optimizations we can do here, stub out with zero.
11965  B = APFloat::getZero(A.getSemantics());
11966  }
11967  int DenomLogB = 0;
11968  APFloat MaxCD = maxnum(abs(C), abs(D));
11969  if (MaxCD.isFinite()) {
11970  DenomLogB = ilogb(MaxCD);
11971  C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11972  D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11973  }
11974  APFloat Denom = C * C + D * D;
11975  ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11976  APFloat::rmNearestTiesToEven);
11977  ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11978  APFloat::rmNearestTiesToEven);
11979  if (ResR.isNaN() && ResI.isNaN()) {
11980  if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11981  ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11982  ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11983  } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11984  D.isFinite()) {
11985  A = APFloat::copySign(
11986  APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11987  B = APFloat::copySign(
11988  APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11989  ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11990  ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11991  } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11992  C = APFloat::copySign(
11993  APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11994  D = APFloat::copySign(
11995  APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11996  ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11997  ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11998  }
11999  }
12000  }
12001  } else {
12002  if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12003  return Error(E, diag::note_expr_divide_by_zero);
12004 
12005  ComplexValue LHS = Result;
12006  APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12007  RHS.getComplexIntImag() * RHS.getComplexIntImag();
12008  Result.getComplexIntReal() =
12009  (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12010  LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12011  Result.getComplexIntImag() =
12012  (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12013  LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12014  }
12015  break;
12016  }
12017 
12018  return true;
12019 }
12020 
12021 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12022  // Get the operand value into 'Result'.
12023  if (!Visit(E->getSubExpr()))
12024  return false;
12025 
12026  switch (E->getOpcode()) {
12027  default:
12028  return Error(E);
12029  case UO_Extension:
12030  return true;
12031  case UO_Plus:
12032  // The result is always just the subexpr.
12033  return true;
12034  case UO_Minus:
12035  if (Result.isComplexFloat()) {
12036  Result.getComplexFloatReal().changeSign();
12037  Result.getComplexFloatImag().changeSign();
12038  }
12039  else {
12040  Result.getComplexIntReal() = -Result.getComplexIntReal();
12041  Result.getComplexIntImag() = -Result.getComplexIntImag();
12042  }
12043  return true;
12044  case UO_Not:
12045  if (Result.isComplexFloat())
12046  Result.getComplexFloatImag().changeSign();
12047  else
12048  Result.getComplexIntImag() = -Result.getComplexIntImag();
12049  return true;
12050  }
12051 }
12052 
12053 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12054  if (E->getNumInits() == 2) {
12055  if (E->getType()->isComplexType()) {
12056  Result.makeComplexFloat();
12057  if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12058  return false;
12059  if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12060  return false;
12061  } else {
12062  Result.makeComplexInt();
12063  if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12064  return false;
12065  if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12066  return false;
12067  }
12068  return true;
12069  }
12070  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12071 }
12072 
12073 //===----------------------------------------------------------------------===//
12074 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12075 // implicit conversion.
12076 //===----------------------------------------------------------------------===//
12077 
12078 namespace {
12079 class AtomicExprEvaluator :
12080  public ExprEvaluatorBase<AtomicExprEvaluator> {
12081  const LValue *This;
12082  APValue &Result;
12083 public:
12084  AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12085  : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12086 
12087  bool Success(const APValue &V, const Expr *E) {
12088  Result = V;
12089  return true;
12090  }
12091 
12092  bool ZeroInitialization(const Expr *E) {
12094  E->getType()->castAs<AtomicType>()->getValueType());
12095  // For atomic-qualified class (and array) types in C++, initialize the
12096  // _Atomic-wrapped subobject directly, in-place.
12097  return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12098  : Evaluate(Result, Info, &VIE);
12099  }
12100 
12101  bool VisitCastExpr(const CastExpr *E) {
12102  switch (E->getCastKind()) {
12103  default:
12104  return ExprEvaluatorBaseTy::VisitCastExpr(E);
12105  case CK_NonAtomicToAtomic:
12106  return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12107  : Evaluate(Result, Info, E->getSubExpr());
12108  }
12109  }
12110 };
12111 } // end anonymous namespace
12112 
12113 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12114  EvalInfo &Info) {
12115  assert(E->isRValue() && E->getType()->isAtomicType());
12116  return AtomicExprEvaluator(Info, This, Result).Visit(E);
12117 }
12118 
12119 //===----------------------------------------------------------------------===//
12120 // Void expression evaluation, primarily for a cast to void on the LHS of a
12121 // comma operator
12122 //===----------------------------------------------------------------------===//
12123 
12124 namespace {
12125 class VoidExprEvaluator
12126  : public ExprEvaluatorBase<VoidExprEvaluator> {
12127 public:
12128  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12129 
12130  bool Success(const APValue &V, const Expr *e) { return true; }
12131 
12132  bool ZeroInitialization(const Expr *E) { return true; }
12133 
12134  bool VisitCastExpr(const CastExpr *E) {
12135  switch (E->getCastKind()) {
12136  default:
12137  return ExprEvaluatorBaseTy::VisitCastExpr(E);
12138  case CK_ToVoid:
12139  VisitIgnoredValue(E->getSubExpr());
12140  return true;
12141  }
12142  }
12143 
12144  bool VisitCallExpr(const CallExpr *E) {
12145  switch (E->getBuiltinCallee()) {
12146  default:
12147  return ExprEvaluatorBaseTy::VisitCallExpr(E);
12148  case Builtin::BI__assume:
12149  case Builtin::BI__builtin_assume:
12150  // The argument is not evaluated!
12151  return true;
12152  }
12153  }
12154 };
12155 } // end anonymous namespace
12156 
12157 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12158  assert(E->isRValue() && E->getType()->isVoidType());
12159  return VoidExprEvaluator(Info).Visit(E);
12160 }
12161 
12162 //===----------------------------------------------------------------------===//
12163 // Top level Expr::EvaluateAsRValue method.
12164 //===----------------------------------------------------------------------===//
12165 
12166 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12167  // In C, function designators are not lvalues, but we evaluate them as if they
12168  // are.
12169  QualType T = E->getType();
12170  if (E->isGLValue() || T->isFunctionType()) {
12171  LValue LV;
12172  if (!EvaluateLValue(E, LV, Info))
12173  return false;
12174  LV.moveInto(Result);
12175  } else if (T->isVectorType()) {
12176  if (!EvaluateVector(E, Result, Info))
12177  return false;
12178  } else if (T->isIntegralOrEnumerationType()) {
12179  if (!IntExprEvaluator(Info, Result).Visit(E))
12180  return false;
12181  } else if (T->hasPointerRepresentation()) {
12182  LValue LV;
12183  if (!EvaluatePointer(E, LV, Info))
12184  return false;
12185  LV.moveInto(Result);
12186  } else if (T->isRealFloatingType()) {
12187  llvm::APFloat F(0.0);
12188  if (!EvaluateFloat(E, F, Info))
12189  return false;
12190  Result = APValue(F);
12191  } else if (T->isAnyComplexType()) {
12192  ComplexValue C;
12193  if (!EvaluateComplex(E, C, Info))
12194  return false;
12195  C.moveInto(Result);
12196  } else if (T->isFixedPointType()) {
12197  if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12198  } else if (T->isMemberPointerType()) {
12199  MemberPtr P;
12200  if (!EvaluateMemberPointer(E, P, Info))
12201  return false;
12202  P.moveInto(Result);
12203  return true;
12204  } else if (T->isArrayType()) {
12205  LValue LV;
12206  APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12207  if (!EvaluateArray(E, LV, Value, Info))
12208  return false;
12209  Result = Value;
12210  } else if (T->isRecordType()) {
12211  LValue LV;
12212  APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12213  if (!EvaluateRecord(E, LV, Value, Info))
12214  return false;
12215  Result = Value;
12216  } else if (T->isVoidType()) {
12217  if (!Info.getLangOpts().CPlusPlus11)
12218  Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12219  << E->getType();
12220  if (!EvaluateVoid(E, Info))
12221  return false;
12222  } else if (T->isAtomicType()) {
12223  QualType Unqual = T.getAtomicUnqualifiedType();
12224  if (Unqual->isArrayType() || Unqual->isRecordType()) {
12225  LValue LV;
12226  APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12227  if (!EvaluateAtomic(E, &LV, Value, Info))
12228  return false;
12229  } else {
12230  if (!EvaluateAtomic(E, nullptr, Result, Info))
12231  return false;
12232  }
12233  } else if (Info.getLangOpts().CPlusPlus11) {
12234  Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12235  return false;
12236  } else {
12237  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12238  return false;
12239  }
12240 
12241  return true;
12242 }
12243 
12244 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12245 /// cases, the in-place evaluation is essential, since later initializers for
12246 /// an object can indirectly refer to subobjects which were initialized earlier.
12247 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12248  const Expr *E, bool AllowNonLiteralTypes) {
12249  assert(!E->isValueDependent());
12250 
12251  if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12252  return false;
12253 
12254  if (E->isRValue()) {
12255  // Evaluate arrays and record types in-place, so that later initializers can
12256  // refer to earlier-initialized members of the object.
12257  QualType T = E->getType();
12258  if (T->isArrayType())
12259  return EvaluateArray(E, This, Result, Info);
12260  else if (T->isRecordType())
12261  return EvaluateRecord(E, This, Result, Info);
12262  else if (T->isAtomicType()) {
12263  QualType Unqual = T.getAtomicUnqualifiedType();
12264  if (Unqual->isArrayType() || Unqual->isRecordType())
12265  return EvaluateAtomic(E, &This, Result, Info);
12266  }
12267  }
12268 
12269  // For any other type, in-place evaluation is unimportant.
12270  return Evaluate(Result, Info, E);
12271 }
12272 
12273 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12274 /// lvalue-to-rvalue cast if it is an lvalue.
12275 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12276  if (E->getType().isNull())
12277  return false;
12278 
12279  if (!CheckLiteralType(Info, E))
12280  return false;
12281 
12282  if (!::Evaluate(Result, Info, E))
12283  return false;
12284 
12285  if (E->isGLValue()) {
12286  LValue LV;
12287  LV.setFrom(Info.Ctx, Result);
12288  if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12289  return false;
12290  }
12291 
12292  // Check this core constant expression is a constant expression.
12293  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12294 }
12295 
12296 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12297  const ASTContext &Ctx, bool &IsConst) {
12298  // Fast-path evaluations of integer literals, since we sometimes see files
12299  // containing vast quantities of these.
12300  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12301  Result.Val = APValue(APSInt(L->getValue(),
12302  L->getType()->isUnsignedIntegerType()));
12303  IsConst = true;
12304  return true;
12305  }
12306 
12307  // This case should be rare, but we need to check it before we check on
12308  // the type below.
12309  if (Exp->getType().isNull()) {
12310  IsConst = false;
12311  return true;
12312  }
12313 
12314  // FIXME: Evaluating values of large array and record types can cause
12315  // performance problems. Only do so in C++11 for now.
12316  if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12317  Exp->getType()->isRecordType()) &&
12318  !Ctx.getLangOpts().CPlusPlus11) {
12319  IsConst = false;
12320  return true;
12321  }
12322  return false;
12323 }
12324 
12326  Expr::SideEffectsKind SEK) {
12327  return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12329 }
12330 
12331 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12332  const ASTContext &Ctx, EvalInfo &Info) {
12333  bool IsConst;
12334  if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12335  return IsConst;
12336 
12337  return EvaluateAsRValue(Info, E, Result.Val);
12338 }
12339 
12341  const ASTContext &Ctx,
12342  Expr::SideEffectsKind AllowSideEffects,
12343  EvalInfo &Info) {
12344  if (!E->getType()->isIntegralOrEnumerationType())
12345  return false;
12346 
12347  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12348  !ExprResult.Val.isInt() ||
12349  hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12350  return false;
12351 
12352  return true;
12353 }
12354 
12356  const ASTContext &Ctx,
12357  Expr::SideEffectsKind AllowSideEffects,
12358  EvalInfo &Info) {
12359  if (!E->getType()->isFixedPointType())
12360  return false;
12361 
12362  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12363  return false;
12364 
12365  if (!ExprResult.Val.isFixedPoint() ||
12366  hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12367  return false;
12368 
12369  return true;
12370 }
12371 
12372 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12373 /// any crazy technique (that has nothing to do with language standards) that
12374 /// we want to. If this function returns true, it returns the folded constant
12375 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12376 /// will be applied to the result.
12378  bool InConstantContext) const {
12379  assert(!isValueDependent() &&
12380  "Expression evaluator can't be called on a dependent expression.");
12381  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12382  Info.InConstantContext = InConstantContext;
12383  return ::EvaluateAsRValue(this, Result, Ctx, Info);
12384 }
12385 
12386 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12387  bool InConstantContext) const {
12388  assert(!isValueDependent() &&
12389  "Expression evaluator can't be called on a dependent expression.");
12390  EvalResult Scratch;
12391  return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12392  HandleConversionToBool(Scratch.Val, Result);
12393 }
12394 
12395 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12396  SideEffectsKind AllowSideEffects,
12397  bool InConstantContext) const {
12398  assert(!isValueDependent() &&
12399  "Expression evaluator can't be called on a dependent expression.");
12400  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12401  Info.InConstantContext = InConstantContext;
12402  return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12403 }
12404 
12406  SideEffectsKind AllowSideEffects,
12407  bool InConstantContext) const {
12408  assert(!isValueDependent() &&
12409  "Expression evaluator can't be called on a dependent expression.");
12410  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12411  Info.InConstantContext = InConstantContext;
12412  return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12413 }
12414 
12415 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12416  SideEffectsKind AllowSideEffects,
12417  bool InConstantContext) const {
12418  assert(!isValueDependent() &&
12419  "Expression evaluator can't be called on a dependent expression.");
12420 
12421  if (!getType()->isRealFloatingType())
12422  return false;
12423 
12425  if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12426  !ExprResult.Val.isFloat() ||
12427  hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12428  return false;
12429 
12430  Result = ExprResult.Val.getFloat();
12431  return true;
12432 }
12433 
12435  bool InConstantContext) const {
12436  assert(!isValueDependent() &&
12437  "Expression evaluator can't be called on a dependent expression.");
12438 
12439  EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12440  Info.InConstantContext = InConstantContext;
12441  LValue LV;
12442  if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12443  !CheckLValueConstantExpression(Info, getExprLoc(),
12444  Ctx.getLValueReferenceType(getType()), LV,
12446  return false;
12447 
12448  LV.moveInto(Result.Val);
12449  return true;
12450 }
12451 
12453  const ASTContext &Ctx) const {
12454  assert(!isValueDependent() &&
12455  "Expression evaluator can't be called on a dependent expression.");
12456 
12457  EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12458  EvalInfo Info(Ctx, Result, EM);
12459  Info.InConstantContext = true;
12460 
12461  if (!::Evaluate(Result.Val, Info, this))
12462  return false;
12463 
12464  return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12465  Usage);
12466 }
12467 
12469  const VarDecl *VD,
12470  SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12471  assert(!isValueDependent() &&
12472  "Expression evaluator can't be called on a dependent expression.");
12473 
12474  // FIXME: Evaluating initializers for large array and record types can cause
12475  // performance problems. Only do so in C++11 for now.
12476  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12477  !Ctx.getLangOpts().CPlusPlus11)
12478  return false;
12479 
12480  Expr::EvalStatus EStatus;
12481  EStatus.Diag = &Notes;
12482 
12483  EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12484  ? EvalInfo::EM_ConstantExpression
12485  : EvalInfo::EM_ConstantFold);
12486  InitInfo.setEvaluatingDecl(VD, Value);
12487  InitInfo.InConstantContext = true;
12488 
12489  LValue LVal;
12490  LVal.set(VD);
12491 
12492  // C++11 [basic.start.init]p2:
12493  // Variables with static storage duration or thread storage duration shall be
12494  // zero-initialized before any other initialization takes place.
12495  // This behavior is not present in C.
12496  if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12497  !VD->getType()->isReferenceType()) {
12498  ImplicitValueInitExpr VIE(VD->getType());
12499  if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12500  /*AllowNonLiteralTypes=*/true))
12501  return false;
12502  }
12503 
12504  if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12505  /*AllowNonLiteralTypes=*/true) ||
12506  EStatus.HasSideEffects)
12507  return false;
12508 
12509  return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12510  Value);
12511 }
12512 
12513 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12514 /// constant folded, but discard the result.
12515 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12516  assert(!isValueDependent() &&
12517  "Expression evaluator can't be called on a dependent expression.");
12518 
12520  return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12521  !hasUnacceptableSideEffect(Result, SEK);
12522 }
12523 
12526  assert(!isValueDependent() &&
12527  "Expression evaluator can't be called on a dependent expression.");
12528 
12529  EvalResult EVResult;
12530  EVResult.Diag = Diag;
12531  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12532  Info.InConstantContext = true;
12533 
12534  bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12535  (void)Result;
12536  assert(Result && "Could not evaluate expression");
12537  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12538 
12539  return EVResult.Val.getInt();
12540 }
12541 
12544  assert(!isValueDependent() &&
12545  "Expression evaluator can't be called on a dependent expression.");
12546 
12547  EvalResult EVResult;
12548  EVResult.Diag = Diag;
12549  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12550  Info.InConstantContext = true;
12551 
12552  bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12553  (void)Result;
12554  assert(Result && "Could not evaluate expression");
12555  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12556 
12557  return EVResult.Val.getInt();
12558 }
12559 
12560 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12561  assert(!isValueDependent() &&
12562  "Expression evaluator can't be called on a dependent expression.");
12563 
12564  bool IsConst;
12565  EvalResult EVResult;
12566  if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12567  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12568  (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12569  }
12570 }
12571 
12573  assert(Val.isLValue());
12574  return IsGlobalLValue(Val.getLValueBase());
12575 }
12576 
12577 
12578 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12579 /// an integer constant expression.
12580 
12581 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12582 /// comma, etc
12583 
12584 // CheckICE - This function does the fundamental ICE checking: the returned
12585 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12586 // and a (possibly null) SourceLocation indicating the location of the problem.
12587 //
12588 // Note that to reduce code duplication, this helper does no evaluation
12589 // itself; the caller checks whether the expression is evaluatable, and
12590 // in the rare cases where CheckICE actually cares about the evaluated
12591 // value, it calls into Evaluate.
12592 
12593 namespace {
12594 
12595 enum ICEKind {
12596  /// This expression is an ICE.
12597  IK_ICE,
12598  /// This expression is not an ICE, but if it isn't evaluated, it's
12599  /// a legal subexpression for an ICE. This return value is used to handle
12600  /// the comma operator in C99 mode, and non-constant subexpressions.
12601  IK_ICEIfUnevaluated,
12602  /// This expression is not an ICE, and is not a legal subexpression for one.
12603  IK_NotICE
12604 };
12605 
12606 struct ICEDiag {
12607  ICEKind Kind;
12608  SourceLocation Loc;
12609 
12610  ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12611 };
12612 
12613 }
12614 
12615 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12616 
12617 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12618 
12619 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12620  Expr::EvalResult EVResult;
12621  Expr::EvalStatus Status;
12622  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12623 
12624  Info.InConstantContext = true;
12625  if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12626  !EVResult.Val.isInt())
12627  return ICEDiag(IK_NotICE, E->getBeginLoc());
12628 
12629  return NoDiag();
12630 }
12631 
12632 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12633  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12634  if (!E->getType()->isIntegralOrEnumerationType())
12635  return ICEDiag(IK_NotICE, E->getBeginLoc());
12636 
12637  switch (E->getStmtClass()) {
12638 #define ABSTRACT_STMT(Node)
12639 #define STMT(Node, Base) case Expr::Node##Class:
12640 #define EXPR(Node, Base)
12641 #include "clang/AST/StmtNodes.inc"
12642  case Expr::PredefinedExprClass:
12643  case Expr::FloatingLiteralClass:
12644  case Expr::ImaginaryLiteralClass:
12645  case Expr::StringLiteralClass:
12646  case Expr::ArraySubscriptExprClass:
12647  case Expr::OMPArraySectionExprClass:
12648  case Expr::MemberExprClass:
12649  case Expr::CompoundAssignOperatorClass:
12650  case Expr::CompoundLiteralExprClass:
12651  case Expr::ExtVectorElementExprClass:
12652  case Expr::DesignatedInitExprClass:
12653  case Expr::ArrayInitLoopExprClass:
12654  case Expr::ArrayInitIndexExprClass:
12655  case Expr::NoInitExprClass:
12656  case Expr::DesignatedInitUpdateExprClass:
12657  case Expr::ImplicitValueInitExprClass:
12658  case Expr::ParenListExprClass:
12659  case Expr::VAArgExprClass:
12660  case Expr::AddrLabelExprClass:
12661  case Expr::StmtExprClass:
12662  case Expr::CXXMemberCallExprClass:
12663  case Expr::CUDAKernelCallExprClass:
12664  case Expr::CXXDynamicCastExprClass:
12665  case Expr::CXXTypeidExprClass:
12666  case Expr::CXXUuidofExprClass:
12667  case Expr::MSPropertyRefExprClass:
12668  case Expr::MSPropertySubscriptExprClass:
12669  case Expr::CXXNullPtrLiteralExprClass:
12670  case Expr::UserDefinedLiteralClass:
12671  case Expr::CXXThisExprClass:
12672  case Expr::CXXThrowExprClass:
12673  case Expr::CXXNewExprClass:
12674  case Expr::CXXDeleteExprClass:
12675  case Expr::CXXPseudoDestructorExprClass:
12676  case Expr::UnresolvedLookupExprClass:
12677  case Expr::TypoExprClass:
12678  case Expr::DependentScopeDeclRefExprClass:
12679  case Expr::CXXConstructExprClass:
12680  case Expr::CXXInheritedCtorInitExprClass:
12681  case Expr::CXXStdInitializerListExprClass:
12682  case Expr::CXXBindTemporaryExprClass:
12683  case Expr::ExprWithCleanupsClass:
12684  case Expr::CXXTemporaryObjectExprClass:
12685  case Expr::CXXUnresolvedConstructExprClass:
12686  case Expr::CXXDependentScopeMemberExprClass:
12687  case Expr::UnresolvedMemberExprClass:
12688  case Expr::ObjCStringLiteralClass:
12689  case Expr::ObjCBoxedExprClass:
12690  case Expr::ObjCArrayLiteralClass:
12691  case Expr::ObjCDictionaryLiteralClass:
12692  case Expr::ObjCEncodeExprClass:
12693  case Expr::ObjCMessageExprClass:
12694  case Expr::ObjCSelectorExprClass:
12695  case Expr::ObjCProtocolExprClass:
12696  case Expr::ObjCIvarRefExprClass:
12697  case Expr::ObjCPropertyRefExprClass:
12698  case Expr::ObjCSubscriptRefExprClass:
12699  case Expr::ObjCIsaExprClass:
12700  case Expr::ObjCAvailabilityCheckExprClass:
12701  case Expr::ShuffleVectorExprClass:
12702  case Expr::ConvertVectorExprClass:
12703  case Expr::BlockExprClass:
12704  case Expr::NoStmtClass:
12705  case Expr::OpaqueValueExprClass:
12706  case Expr::PackExpansionExprClass:
12707  case Expr::SubstNonTypeTemplateParmPackExprClass:
12708  case Expr::FunctionParmPackExprClass:
12709  case Expr::AsTypeExprClass:
12710  case Expr::ObjCIndirectCopyRestoreExprClass:
12711  case Expr::MaterializeTemporaryExprClass:
12712  case Expr::PseudoObjectExprClass:
12713  case Expr::AtomicExprClass:
12714  case Expr::LambdaExprClass:
12715  case Expr::CXXFoldExprClass:
12716  case Expr::CoawaitExprClass:
12717  case Expr::DependentCoawaitExprClass:
12718  case Expr::CoyieldExprClass:
12719  return ICEDiag(IK_NotICE, E->getBeginLoc());
12720 
12721  case Expr::InitListExprClass: {
12722  // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12723  // form "T x = { a };" is equivalent to "T x = a;".
12724  // Unless we're initializing a reference, T is a scalar as it is known to be
12725  // of integral or enumeration type.
12726  if (E->isRValue())
12727  if (cast<InitListExpr>(E)->getNumInits() == 1)
12728  return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12729  return ICEDiag(IK_NotICE, E->getBeginLoc());
12730  }
12731 
12732  case Expr::SizeOfPackExprClass:
12733  case Expr::GNUNullExprClass:
12734  case Expr::SourceLocExprClass:
12735  return NoDiag();
12736 
12737  case Expr::SubstNonTypeTemplateParmExprClass:
12738  return
12739  CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12740 
12741  case Expr::ConstantExprClass:
12742  return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12743 
12744  case Expr::ParenExprClass:
12745  return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12746  case Expr::GenericSelectionExprClass:
12747  return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12748  case Expr::IntegerLiteralClass:
12749  case Expr::FixedPointLiteralClass:
12750  case Expr::CharacterLiteralClass:
12751  case Expr::ObjCBoolLiteralExprClass:
12752  case Expr::CXXBoolLiteralExprClass:
12753  case Expr::CXXScalarValueInitExprClass:
12754  case Expr::TypeTraitExprClass:
12755  case Expr::ArrayTypeTraitExprClass:
12756  case Expr::ExpressionTraitExprClass:
12757  case Expr::CXXNoexceptExprClass:
12758  return NoDiag();
12759  case Expr::CallExprClass:
12760  case Expr::CXXOperatorCallExprClass: {
12761  // C99 6.6/3 allows function calls within unevaluated subexpressions of
12762  // constant expressions, but they can never be ICEs because an ICE cannot
12763  // contain an operand of (pointer to) function type.
12764  const CallExpr *CE = cast<CallExpr>(E);
12765  if (CE->getBuiltinCallee())
12766  return CheckEvalInICE(E, Ctx);
12767  return ICEDiag(IK_NotICE, E->getBeginLoc());
12768  }
12769  case Expr::DeclRefExprClass: {
12770  if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12771  return NoDiag();
12772  const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12773  if (Ctx.getLangOpts().CPlusPlus &&
12774  D && IsConstNonVolatile(D->getType())) {
12775  // Parameter variables are never constants. Without this check,
12776  // getAnyInitializer() can find a default argument, which leads
12777  // to chaos.
12778  if (isa<ParmVarDecl>(D))
12779  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12780 
12781  // C++ 7.1.5.1p2
12782  // A variable of non-volatile const-qualified integral or enumeration
12783  // type initialized by an ICE can be used in ICEs.
12784  if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12785  if (!Dcl->getType()->isIntegralOrEnumerationType())
12786  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12787 
12788  const VarDecl *VD;
12789  // Look for a declaration of this variable that has an initializer, and
12790  // check whether it is an ICE.
12791  if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12792  return NoDiag();
12793  else
12794  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12795  }
12796  }
12797  return ICEDiag(IK_NotICE, E->getBeginLoc());
12798  }
12799  case Expr::UnaryOperatorClass: {
12800  const UnaryOperator *Exp = cast<UnaryOperator>(E);
12801  switch (Exp->getOpcode()) {
12802  case UO_PostInc:
12803  case UO_PostDec:
12804  case UO_PreInc:
12805  case UO_PreDec:
12806  case UO_AddrOf:
12807  case UO_Deref:
12808  case UO_Coawait:
12809  // C99 6.6/3 allows increment and decrement within unevaluated
12810  // subexpressions of constant expressions, but they can never be ICEs
12811  // because an ICE cannot contain an lvalue operand.
12812  return ICEDiag(IK_NotICE, E->getBeginLoc());
12813  case UO_Extension:
12814  case UO_LNot:
12815  case UO_Plus:
12816  case UO_Minus:
12817  case UO_Not:
12818  case UO_Real:
12819  case UO_Imag:
12820  return CheckICE(Exp->getSubExpr(), Ctx);
12821  }
12822  llvm_unreachable("invalid unary operator class");
12823  }
12824  case Expr::OffsetOfExprClass: {
12825  // Note that per C99, offsetof must be an ICE. And AFAIK, using
12826  // EvaluateAsRValue matches the proposed gcc behavior for cases like
12827  // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12828  // compliance: we should warn earlier for offsetof expressions with
12829  // array subscripts that aren't ICEs, and if the array subscripts
12830  // are ICEs, the value of the offsetof must be an integer constant.
12831  return CheckEvalInICE(E, Ctx);
12832  }
12833  case Expr::UnaryExprOrTypeTraitExprClass: {
12834  const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12835  if ((Exp->getKind() == UETT_SizeOf) &&
12837  return ICEDiag(IK_NotICE, E->getBeginLoc());
12838  return NoDiag();
12839  }
12840  case Expr::BinaryOperatorClass: {
12841  const BinaryOperator *Exp = cast<BinaryOperator>(E);
12842  switch (Exp->getOpcode()) {
12843  case BO_PtrMemD:
12844  case BO_PtrMemI:
12845  case BO_Assign:
12846  case BO_MulAssign:
12847  case BO_DivAssign:
12848  case BO_RemAssign:
12849  case BO_AddAssign:
12850  case BO_SubAssign:
12851  case BO_ShlAssign:
12852  case BO_ShrAssign:
12853  case BO_AndAssign:
12854  case BO_XorAssign:
12855  case BO_OrAssign:
12856  // C99 6.6/3 allows assignments within unevaluated subexpressions of
12857  // constant expressions, but they can never be ICEs because an ICE cannot
12858  // contain an lvalue operand.
12859  return ICEDiag(IK_NotICE, E->getBeginLoc());
12860 
12861  case BO_Mul:
12862  case BO_Div:
12863  case BO_Rem:
12864  case BO_Add:
12865  case BO_Sub:
12866  case BO_Shl:
12867  case BO_Shr:
12868  case BO_LT:
12869  case BO_GT:
12870  case BO_LE:
12871  case BO_GE:
12872  case BO_EQ:
12873  case BO_NE:
12874  case BO_And:
12875  case BO_Xor:
12876  case BO_Or:
12877  case BO_Comma:
12878  case BO_Cmp: {
12879  ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12880  ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12881  if (Exp->getOpcode() == BO_Div ||
12882  Exp->getOpcode() == BO_Rem) {
12883  // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12884  // we don't evaluate one.
12885  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12886  llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12887  if (REval == 0)
12888  return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12889  if (REval.isSigned() && REval.isAllOnesValue()) {
12890  llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12891  if (LEval.isMinSignedValue())
12892  return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12893  }
12894  }
12895  }
12896  if (Exp->getOpcode() == BO_Comma) {
12897  if (Ctx.getLangOpts().C99) {
12898  // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12899  // if it isn't evaluated.
12900  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12901  return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12902  } else {
12903  // In both C89 and C++, commas in ICEs are illegal.
12904  return ICEDiag(IK_NotICE, E->getBeginLoc());
12905  }
12906  }
12907  return Worst(LHSResult, RHSResult);
12908  }
12909  case BO_LAnd:
12910  case BO_LOr: {
12911  ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12912  ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12913  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12914  // Rare case where the RHS has a comma "side-effect"; we need
12915  // to actually check the condition to see whether the side
12916  // with the comma is evaluated.
12917  if ((Exp->getOpcode() == BO_LAnd) !=
12918  (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12919  return RHSResult;
12920  return NoDiag();
12921  }
12922 
12923  return Worst(LHSResult, RHSResult);
12924  }
12925  }
12926  llvm_unreachable("invalid binary operator kind");
12927  }
12928  case Expr::ImplicitCastExprClass:
12929  case Expr::CStyleCastExprClass:
12930  case Expr::CXXFunctionalCastExprClass:
12931  case Expr::CXXStaticCastExprClass:
12932  case Expr::CXXReinterpretCastExprClass:
12933  case Expr::CXXConstCastExprClass:
12934  case Expr::ObjCBridgedCastExprClass: {
12935  const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12936  if (isa<ExplicitCastExpr>(E)) {
12937  if (const FloatingLiteral *FL
12938  = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12939  unsigned DestWidth = Ctx.getIntWidth(E->getType());
12940  bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12941  APSInt IgnoredVal(DestWidth, !DestSigned);
12942  bool Ignored;
12943  // If the value does not fit in the destination type, the behavior is
12944  // undefined, so we are not required to treat it as a constant
12945  // expression.
12946  if (FL->getValue().convertToInteger(IgnoredVal,
12947  llvm::APFloat::rmTowardZero,
12948  &Ignored) & APFloat::opInvalidOp)
12949  return ICEDiag(IK_NotICE, E->getBeginLoc());
12950  return NoDiag();
12951  }
12952  }
12953  switch (cast<CastExpr>(E)->getCastKind()) {
12954  case CK_LValueToRValue:
12955  case CK_AtomicToNonAtomic:
12956  case CK_NonAtomicToAtomic:
12957  case CK_NoOp:
12958  case CK_IntegralToBoolean:
12959  case CK_IntegralCast:
12960  return CheckICE(SubExpr, Ctx);
12961  default:
12962  return ICEDiag(IK_NotICE, E->getBeginLoc());
12963  }
12964  }
12965  case Expr::BinaryConditionalOperatorClass: {
12966  const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12967  ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12968  if (CommonResult.Kind == IK_NotICE) return CommonResult;
12969  ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12970  if (FalseResult.Kind == IK_NotICE) return FalseResult;
12971  if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12972  if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12973  Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12974  return FalseResult;
12975  }
12976  case Expr::ConditionalOperatorClass: {
12977  const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12978  // If the condition (ignoring parens) is a __builtin_constant_p call,
12979  // then only the true side is actually considered in an integer constant
12980  // expression, and it is fully evaluated. This is an important GNU
12981  // extension. See GCC PR38377 for discussion.
12982  if (const CallExpr *CallCE
12983  = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12984  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12985  return CheckEvalInICE(E, Ctx);
12986  ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12987  if (CondResult.Kind == IK_NotICE)
12988  return CondResult;
12989 
12990  ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12991  ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12992 
12993  if (TrueResult.Kind == IK_NotICE)
12994  return TrueResult;
12995  if (FalseResult.Kind == IK_NotICE)
12996  return FalseResult;
12997  if (CondResult.Kind == IK_ICEIfUnevaluated)
12998  return CondResult;
12999  if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
13000  return NoDiag();
13001  // Rare case where the diagnostics depend on which side is evaluated
13002  // Note that if we get here, CondResult is 0, and at least one of
13003  // TrueResult and FalseResult is non-zero.
13004  if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
13005  return FalseResult;
13006  return TrueResult;
13007  }
13008  case Expr::CXXDefaultArgExprClass:
13009  return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
13010  case Expr::CXXDefaultInitExprClass:
13011  return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
13012  case Expr::ChooseExprClass: {
13013  return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
13014  }
13015  case Expr::BuiltinBitCastExprClass: {
13016  if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13017  return ICEDiag(IK_NotICE, E->getBeginLoc());
13018  return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13019  }
13020  }
13021 
13022  llvm_unreachable("Invalid StmtClass!");
13023 }
13024 
13025 /// Evaluate an expression as a C++11 integral constant expression.
13027  const Expr *E,
13028  llvm::APSInt *Value,
13029  SourceLocation *Loc) {
13031  if (Loc) *Loc = E->getExprLoc();
13032  return false;
13033  }
13034 
13035  APValue Result;
13036  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13037  return false;
13038 
13039  if (!Result.isInt()) {
13040  if (Loc) *Loc = E->getExprLoc();
13041  return false;
13042  }
13043 
13044  if (Value) *Value = Result.getInt();
13045  return true;
13046 }
13047 
13049  SourceLocation *Loc) const {
13050  assert(!isValueDependent() &&
13051  "Expression evaluator can't be called on a dependent expression.");
13052 
13053  if (Ctx.getLangOpts().CPlusPlus11)
13054  return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13055 
13056  ICEDiag D = CheckICE(this, Ctx);
13057  if (D.Kind != IK_ICE) {
13058  if (Loc) *Loc = D.Loc;
13059  return false;
13060  }
13061  return true;
13062 }
13063 
13064 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13065  SourceLocation *Loc, bool isEvaluated) const {
13066  assert(!isValueDependent() &&
13067  "Expression evaluator can't be called on a dependent expression.");
13068 
13069  if (Ctx.getLangOpts().CPlusPlus11)
13070  return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13071 
13072  if (!isIntegerConstantExpr(Ctx, Loc))
13073  return false;
13074 
13075  // The only possible side-effects here are due to UB discovered in the
13076  // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13077  // required to treat the expression as an ICE, so we produce the folded
13078  // value.
13080  Expr::EvalStatus Status;
13081  EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13082  Info.InConstantContext = true;
13083 
13084  if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13085  llvm_unreachable("ICE cannot be evaluated!");
13086 
13087  Value = ExprResult.Val.getInt();
13088  return true;
13089 }
13090 
13092  assert(!isValueDependent() &&
13093  "Expression evaluator can't be called on a dependent expression.");
13094 
13095  return CheckICE(this, Ctx).Kind == IK_ICE;
13096 }
13097 
13099  SourceLocation *Loc) const {
13100  assert(!isValueDependent() &&
13101  "Expression evaluator can't be called on a dependent expression.");
13102 
13103  // We support this checking in C++98 mode in order to diagnose compatibility
13104  // issues.
13105  assert(Ctx.getLangOpts().CPlusPlus);
13106 
13107  // Build evaluation settings.
13108  Expr::EvalStatus Status;
13110  Status.Diag = &Diags;
13111  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13112 
13113  APValue Scratch;
13114  bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13115 
13116  if (!Diags.empty()) {
13117  IsConstExpr = false;
13118  if (Loc) *Loc = Diags[0].first;
13119  } else if (!IsConstExpr) {
13120  // FIXME: This shouldn't happen.
13121  if (Loc) *Loc = getExprLoc();
13122  }
13123 
13124  return IsConstExpr;
13125 }
13126 
13128  const FunctionDecl *Callee,
13129  ArrayRef<const Expr*> Args,
13130  const Expr *This) const {
13131  assert(!isValueDependent() &&
13132  "Expression evaluator can't be called on a dependent expression.");
13133 
13134  Expr::EvalStatus Status;
13135  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13136  Info.InConstantContext = true;
13137 
13138  LValue ThisVal;
13139  const LValue *ThisPtr = nullptr;
13140  if (This) {
13141 #ifndef NDEBUG
13142  auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13143  assert(MD && "Don't provide `this` for non-methods.");
13144  assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13145 #endif
13146  if (EvaluateObjectArgument(Info, This, ThisVal))
13147  ThisPtr = &ThisVal;
13148  if (Info.EvalStatus.HasSideEffects)
13149  return false;
13150  }
13151 
13152  ArgVector ArgValues(Args.size());
13153  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13154  I != E; ++I) {
13155  if ((*I)->isValueDependent() ||
13156  !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13157  // If evaluation fails, throw away the argument entirely.
13158  ArgValues[I - Args.begin()] = APValue();
13159  if (Info.EvalStatus.HasSideEffects)
13160  return false;
13161  }
13162 
13163  // Build fake call to Callee.
13164  CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13165  ArgValues.data());
13166  return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13167 }
13168 
13171  PartialDiagnosticAt> &Diags) {
13172  // FIXME: It would be useful to check constexpr function templates, but at the
13173  // moment the constant expression evaluator cannot cope with the non-rigorous
13174  // ASTs which we build for dependent expressions.
13175  if (FD->isDependentContext())
13176  return true;
13177 
13178  Expr::EvalStatus Status;
13179  Status.Diag = &Diags;
13180 
13181  EvalInfo Info(FD->getASTContext(), Status,
13182  EvalInfo::EM_PotentialConstantExpression);
13183  Info.InConstantContext = true;
13184 
13185  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13186  const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13187 
13188  // Fabricate an arbitrary expression on the stack and pretend that it
13189  // is a temporary being used as the 'this' pointer.
13190  LValue This;
13191  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13192  This.set({&VIE, Info.CurrentCall->Index});
13193 
13194  ArrayRef<const Expr*> Args;
13195 
13196  APValue Scratch;
13197  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13198  // Evaluate the call as a constant initializer, to allow the construction
13199  // of objects of non-literal types.
13200  Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13201  HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13202  } else {
13203  SourceLocation Loc = FD->getLocation();
13204  HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13205  Args, FD->getBody(), Info, Scratch, nullptr);
13206  }
13207 
13208  return Diags.empty();
13209 }
13210 
13212  const FunctionDecl *FD,
13214  PartialDiagnosticAt> &Diags) {
13215  assert(!E->isValueDependent() &&
13216  "Expression evaluator can't be called on a dependent expression.");
13217 
13218  Expr::EvalStatus Status;
13219  Status.Diag = &Diags;
13220 
13221  EvalInfo Info(FD->getASTContext(), Status,
13222  EvalInfo::EM_PotentialConstantExpressionUnevaluated);
13223  Info.InConstantContext = true;
13224 
13225  // Fabricate a call stack frame to give the arguments a plausible cover story.
13226  ArrayRef<const Expr*> Args;
13227  ArgVector ArgValues(0);
13228  bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13229  (void)Success;
13230  assert(Success &&
13231  "Failed to set up arguments for potential constant evaluation");
13232  CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13233 
13234  APValue ResultScratch;
13235  Evaluate(ResultScratch, Info, E);
13236  return Diags.empty();
13237 }
13238 
13239 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13240  unsigned Type) const {
13241  if (!getType()->isPointerType())
13242  return false;
13243 
13244  Expr::EvalStatus Status;
13245  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13246  return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
13247 }
Expr * getInc()
Definition: Stmt.h:2417
const Expr * getSubExpr() const
Definition: Expr.h:933
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4475
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, llvm::Type *BaseLVType, CharUnits BaseLVAlignment, llvm::Value *Addr)
static bool HandleConstructorCall(const Expr *E, const LValue &This, APValue *ArgValues, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
Defines the clang::ASTContext interface.
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5555
bool path_empty() const
Definition: Expr.h:3191
static APFixedPoint getFromIntValue(const llvm::APSInt &Value, const FixedPointSemantics &DstFXSema, bool *Overflow=nullptr)
Create an APFixedPoint with a value equal to that of the provided integer, and in the same semantics ...
Definition: FixedPoint.cpp:250
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:592
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition: Expr.h:4139
Represents a function declaration or definition.
Definition: Decl.h:1748
bool getValue() const
Definition: ExprObjC.h:97
bool getValue() const
Definition: ExprCXX.h:2576
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6690
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2663
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
body_iterator body_end()
Definition: Stmt.h:1345
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool IsGlobalLValue(APValue::LValueBase B)
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2569
A (possibly-)qualified type.
Definition: Type.h:643
uint64_t getValue() const
Definition: ExprCXX.h:2666
Static storage duration.
Definition: Specifiers.h:309
base_class_range bases()
Definition: DeclCXX.h:825
bool isArrayType() const
Definition: Type.h:6440
bool isMemberPointerType() const
Definition: Type.h:6422
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2890
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:3542
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2673
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:4034
SourceLocation getExprLoc() const
Definition: Expr.h:3436
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1931
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:819
bool getBoolValue() const
Definition: FixedPoint.h:118
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr *> &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:76
bool operator==(CanQual< T > x, CanQual< U > y)
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:192
Expr * getCond()
Definition: Stmt.h:2249
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2533
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition: Expr.h:5388
CompoundStmt * getSubStmt()
Definition: Expr.h:3938
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4419
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2660
unsigned getCallIndex() const
Definition: APValue.cpp:53
Kind getKind() const
Definition: Type.h:2450
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1812
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2819
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1968
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:2328
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:840
The fixed point semantics work similarly to llvm::fltSemantics.
Definition: FixedPoint.h:33
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:812
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2108
bool isRecordType() const
Definition: Type.h:6464
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
Expr * getBase() const
Definition: Expr.h:2884
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
__DEVICE__ long long abs(long long __n)
llvm::APFloat getValue() const
Definition: Expr.h:1567
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5044
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2166
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:245
ConstExprUsage
Indicates how the constant expression will be used.
Definition: Expr.h:686
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic, and whose semantics are that of the sole contained initializer)?
Definition: Expr.cpp:2280
Opcode getOpcode() const
Definition: Expr.h:3440
StringRef P
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:3950
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1964
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6333
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result)
Extract the designated sub-object of an rvalue.
static ObjectUnderConstruction getTombstoneKey()
const DiagnosticBuilder & operator<<(const DiagnosticBuilder &DB, const Attr *At)
Definition: Attr.h:335
static unsigned getHashValue(const ObjectUnderConstruction &Object)
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2796
The base class of the type hierarchy.
Definition: Type.h:1433
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called...
Definition: ExprCXX.h:1442
bool isVector() const
Definition: APValue.h:323
DiagnosticsEngine & getDiagnostics() const
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsConstNonVolatile(QualType T)
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
unsigned getWidth() const
Definition: FixedPoint.h:111
bool hasValue() const
Definition: APValue.h:315
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2844
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1331
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent...
Definition: ExprCXX.h:2621
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:115
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:425
QualType withConst() const
Definition: Type.h:815
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue...
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6053
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:22
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a fixed point va...
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1209
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2298
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2574
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4325
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
APFixedPoint add(const APFixedPoint &Other, bool *Overflow=nullptr) const
Definition: FixedPoint.cpp:152
bool isIndeterminate() const
Definition: APValue.h:314
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC&#39;s builtin...
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, Expr::ConstExprUsage Usage)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
QualType getElementType() const
Definition: Type.h:2879
const Expr * getSubExpr() const
Definition: Expr.h:1644
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2463
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2300
static bool EvaluateDecl(EvalInfo &Info, const Decl *D)
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3190
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1915
This file provides some common utility functions for processing Lambda related AST Constructs...
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
Represents a variable declaration or definition.
Definition: Decl.h:812
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:264
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue.
QualType getReturnType() const
Definition: Decl.h:2329
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3048
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
APFloat & getComplexFloatReal()
Definition: APValue.h:382
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition: Expr.h:5006
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6851
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:6782
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6925
unsigned PathLength
The corresponding path length in the lvalue.
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:727
static APValue IndeterminateValue()
Definition: APValue.h:290
bool field_empty() const
Definition: Decl.h:3849
QualType getTypeInfoType() const
Definition: APValue.cpp:61
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:624
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const CallExpr *Call, llvm::APInt &Result)
Attempts to compute the number of bytes available at the pointer returned by a function with the allo...
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stmt * getThen()
Definition: Stmt.h:1899
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
CXXMethodDecl * getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find if RD declares a function that overrides this function, and if so, return it.
Definition: DeclCXX.cpp:1960
bool isAddrLabelDiff() const
Definition: APValue.h:328
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition: ExprCXX.h:1557
bool isStatic() const
Definition: DeclCXX.cpp:1938
Expr * getExprOperand() const
Definition: ExprCXX.h:730
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3212
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3531
Represents a parameter to a function.
Definition: Decl.h:1564
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
long i
Definition: xmmintrin.h:1456
The collection of all-type qualifiers we support.
Definition: Type.h:137
bool isVariableArrayType() const
Definition: Type.h:6452
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition: ExprCXX.cpp:1206
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:712
static bool HasSameBase(const LValue &A, const LValue &B)
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:772
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
Represents a struct/union/class.
Definition: Decl.h:3626
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1332
Stmt * getBody()
Definition: Stmt.h:2353
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4366
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size)
Get the size of the given type in char units.
Expr * getFalseExpr() const
Definition: Expr.h:3746
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:2807
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2197
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(), or __builtin_FILE().
Definition: Expr.h:4263
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
bool isFileScope() const
Definition: Expr.h:3078
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:106
field_range fields() const
Definition: Decl.h:3841
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:263
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that&#39;s impossible to figure out the size of ...
Represents a member of a struct/union/class.
Definition: Decl.h:2607
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition: Expr.h:3472
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition: CharUnits.h:128
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2191
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4178
bool isReferenceType() const
Definition: Type.h:6396
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2811
Stmt *const * const_body_iterator
Definition: Stmt.h:1352
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1103
unsigned getArraySize() const
Definition: APValue.h:446
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6610
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:240
__DEVICE__ int max(int __a, int __b)
Expr * getSubExpr()
Definition: Expr.h:3173
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:37
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:738
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
unsigned getCharByteWidth() const
Definition: Expr.h:1794
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
bool isFloat() const
Definition: APValue.h:318
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6747
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
static bool isRelationalOp(Opcode Opc)
Definition: Expr.h:3489
static bool IsWeakLValue(const LValue &Value)
bool isGLValue() const
Definition: Expr.h:261
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
Describes an C or C++ initializer list.
Definition: Expr.h:4371
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:673
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. ...
BinaryOperatorKind
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2685
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:567
ForStmt - This represents a &#39;for (init;cond;inc)&#39; stmt.
Definition: Stmt.h:2384
unsigned getLength() const
Definition: Expr.h:1793
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3492
static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, llvm::APInt &Res)
bool isDelegatingConstructor() const
Determine whether this constructor is a delegating constructor.
Definition: DeclCXX.h:2726
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2808
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1409
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn&#39;t necessarily valid)...
static void hash_combine(std::size_t &seed, const T &v)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:582
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal)
Perform an lvalue-to-rvalue conversion on the given glvalue.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2236
#define CHAR_BIT
Definition: limits.h:63
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6902
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr *> Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition: ExprCXX.h:1872
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:2880
path_iterator path_begin()
Definition: Expr.h:3193
Stmt * getBody()
Definition: Stmt.h:2418
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue...
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool isRecordType(QualType T)
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3405
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6212
Stmt * getInit()
Definition: Stmt.h:2397
bool isComplexFloat() const
Definition: APValue.h:321
bool isFixedPoint() const
Definition: APValue.h:319
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
CXXForRangeStmt - This represents C++0x [stmt.ranged]&#39;s ranged for statement, represented as &#39;for (ra...
Definition: StmtCXX.h:134
bool isComplexInt() const
Definition: APValue.h:320
bool isArrow() const
Definition: Expr.h:2991
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1386
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2947
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:50
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6142
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:730
field_iterator field_begin() const
Definition: Decl.cpp:4301
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3907
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1166
CaseStmt - Represent a case statement.
Definition: Stmt.h:1478
static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, UnaryExprOrTypeTrait ExprKind)
Expr * getCond()
Definition: Stmt.h:2416
bool isInt() const
Definition: APValue.h:317
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3121
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
base_class_iterator bases_begin()
Definition: DeclCXX.h:832
Helper class for OffsetOfExpr.
Definition: Expr.h:2133
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static void expandArray(APValue &Array, unsigned Index)
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1727
bool isInstance() const
Definition: DeclCXX.h:2140
#define UINT_MAX
Definition: limits.h:56
bool isEquality() const
True iff the comparison category is an equality comparison.
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition: OSLog.cpp:180
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition: Stmt.cpp:913
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base)
APSInt & getComplexIntReal()
Definition: APValue.h:366
A binding in a decomposition declaration.
Definition: DeclCXX.h:3931
Stmt * getBody()
Definition: Stmt.h:2089
bool hasConst() const
Definition: Type.h:254
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2670
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1111
Stmt * getInit()
Definition: Stmt.h:1955
static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result)
ConstructionPhase
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2926
Represents the this expression in C++.
Definition: ExprCXX.h:1006
const CXXRecordDecl * Type
The dynamic class type of the object.
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1216
APValue & getVectorElt(unsigned I)
Definition: APValue.h:410
The APFixedPoint class works similarly to APInt/APSInt in that it is a functional replacement for a s...
Definition: FixedPoint.h:95
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1803
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type&#39;s static member function that is used for the result ...
Definition: DeclCXX.cpp:2307
static bool EvaluateArgs(ArrayRef< const Expr *> Args, ArgVector &ArgValues, EvalInfo &Info, const FunctionDecl *Callee)
EvaluateArgs - Evaluate the arguments to a function call.
NodeId Parent
Definition: ASTDiff.cpp:191
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3331
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3703
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1640
StringRef getString() const
Definition: Expr.h:1764
static GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:57
static bool handleCompoundAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1310
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1636
unsigned getVersion() const
Definition: APValue.cpp:57
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:481
bool isUnion() const
Definition: APValue.h:326
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1403
bool hasLValuePath() const
Definition: APValue.cpp:722
QualType getComputationLHSType() const
Definition: Expr.h:3648
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
CastKind
CastKind - The kind of operation required for a conversion.
APValue & getArrayFiller()
Definition: APValue.h:434
Specifies that the expression should never be value-dependent.
Definition: Expr.h:729
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2342
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, APValue *&Result, const LValue *LVal)
Try to evaluate the initializer for a variable declaration.
BaseOrMemberType getAsBaseOrMember() const
Definition: APValue.h:166
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:178
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:948
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:558
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2659
unsigned Offset
Definition: Format.cpp:1713
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getValue() const
Definition: Expr.h:1534
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3319
bool hasArrayFiller() const
Definition: APValue.h:431
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1261
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:1958
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, Expr::ConstExprUsage Usage=Expr::EvaluateForCodeGen, SourceLocation SubobjectLoc=SourceLocation())
Check that this core constant expression value is a valid value for a constant expression.
Expr * getCond() const
Definition: Expr.h:3737
QualType getElementType() const
Definition: Type.h:2522
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4551
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:108
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2483
DeclStmt * getEndStmt()
Definition: StmtCXX.h:165
Allow any unmodeled side effect.
Definition: Expr.h:609
SourceLocation End
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:679
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist ...
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:2048
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:151
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2207
static bool HandleConversionToBool(const APValue &Val, bool &Result)
void EvaluateForOverflow(const ASTContext &Ctx) const
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1035
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition: APValue.cpp:45
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to...
Definition: Type.cpp:1621
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition: ExprCXX.h:4074
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6916
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
#define V(N, I)
Definition: ASTContext.h:2907
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5541
Expr * getCallee()
Definition: Expr.h:2634
unsigned getNumInits() const
Definition: Expr.h:4401
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3552
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5011
llvm::hash_code hash_value(const clang::SanitizerMask &Arg)
Definition: Sanitizers.cpp:51
bool isNullPtrType() const
Definition: Type.h:6668
field_iterator field_end() const
Definition: Decl.h:3844
QualType getArgumentType() const
Definition: Expr.h:2379
#define bool
Definition: stdbool.h:15
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, Expr::ConstExprUsage Usage)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
Stmt * getBody()
Definition: Stmt.h:2261
DeclContext * getDeclContext()
Definition: DeclBase.h:438
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1779
Expr * getRHS()
Definition: Stmt.h:1579
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
bool isAnyComplexType() const
Definition: Type.h:6472
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:62
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2279
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:3997
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:186
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2652
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
void removeLocalConst()
Definition: Type.h:6236
void removeLocalVolatile()
Definition: Type.h:6244
Defines the clang::TypeLoc interface and its subclasses.
int Depth
Definition: ASTDiff.cpp:190
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2467
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1875
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2187
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
QualType getType() const
Definition: Expr.h:137
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2175
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function&#39;s definition might be usable in a constant exp...
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2405
static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:689
APValue & getStructField(unsigned i)
Definition: APValue.h:463
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue&#39;s path to t...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4369
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
Definition: ThreadSafety.h:69
static bool IsStringLiteralCall(const CallExpr *E)
Should this call expression be treated as a string literal?
QualType getRecordType(const RecordDecl *Decl) const
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2146
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2016
Represents a GCC generic vector type.
Definition: Type.h:3200
bool isNullPointer() const
Definition: APValue.cpp:743
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:76
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4115
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1082
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2286
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:607
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6791
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2312
Expr * getCond()
Definition: Stmt.h:1887
ValueDecl * getDecl()
Definition: Expr.h:1217
APSInt & getComplexIntImag()
Definition: APValue.h:374
The result type of a method or function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2040
const Expr * getSubExpr() const
Definition: Expr.h:1980
bool isUnionType() const
Definition: Type.cpp:475
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
bool getValue() const
Definition: ExprCXX.h:566
do v
Definition: arm_acle.h:64
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits, and check for overflow in the original type (if that type was not an unsigned type).
const FieldDecl * getUnionField() const
Definition: APValue.h:474
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1632
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6175
DoStmt - This represents a &#39;do/while&#39; stmt.
Definition: Stmt.h:2328
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1462
APValue getAPValueResult() const
Definition: Expr.cpp:345
SideEffectsKind
Definition: Expr.h:605
bool isVoidPointerType() const
Definition: Type.cpp:469
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6201
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
RecordDecl * getDecl() const
Definition: Type.h:4448
void toString(llvm::SmallVectorImpl< char > &Str) const
Definition: FixedPoint.cpp:176
static APValue & createTemporary(const KeyTy *Key, bool IsLifetimeExtended, LValue &LV, CallStackFrame &Frame)
A helper function to create a temporary and set an LValue.
APValue & getStructBase(unsigned i)
Definition: APValue.h:459
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:190
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable&#39;s initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2363
bool getValue() const
Definition: ExprCXX.h:3890
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:354
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1045
static ICEDiag Worst(ICEDiag A, ICEDiag B)
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:423
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:84
Kind
A field in a dependent type, known only by its name.
Definition: Expr.h:2142
QualType getCanonicalType() const
Definition: Type.h:6181
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1522
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
unsigned path_size() const
Definition: Expr.h:3192
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
static Optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
const LValueBase getLValueBase() const
Definition: APValue.cpp:707
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:980
bool isOrdered() const
True iff the comparison category is a relational comparison.
EvalStmtResult
bool isExpressibleAsConstantInitializer() const
Definition: ExprObjC.h:151
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3658
Encodes a location in the source.
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:820
body_range body()
Definition: Stmt.h:1343
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2023
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4464
static ICEDiag NoDiag()
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6258
Expr * getSubExpr() const
Definition: Expr.h:2046
CastKind getCastKind() const
Definition: Expr.h:3167
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2330
APValue & getUnionValue()
Definition: APValue.h:478
Expr * getLHS()
Definition: Stmt.h:1567
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:4727
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
Stmt * getElse()
Definition: Stmt.h:1908
QualType getElementType() const
Definition: Type.h:3235
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1203
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4019
static bool IsLiteralLValue(const LValue &Value)
APFloat & getFloat()
Definition: APValue.h:350
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2114
Expr * getCond()
Definition: Stmt.h:2077
static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, ArrayRef< const Expr *> Args, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition: Expr.h:2059
#define ilogb(__x)
Definition: tgmath.h:851
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2312
bool isMemberPointer() const
Definition: APValue.h:327
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1891
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2373
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1371
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition: Expr.cpp:2167
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue&#39;s Designator is at the end of the LValue&#39;s record layout...
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:258
bool isLValue() const
Definition: APValue.h:322
TypeClass getTypeClass() const
Definition: Type.h:1839
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:100
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3528
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:459
Expr * getSubExpr()
Definition: ExprObjC.h:142
An expression trait intrinsic.
Definition: ExprCXX.h:2691
EnumDecl * getDecl() const
Definition: Type.h:4471
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:976
bool isVectorType() const
Definition: Type.h:6476
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3922
Represents the current source location and context used to determine the value of the source location...
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:124
bool isArgumentType() const
Definition: Expr.h:2378
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4465
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:779
Defines the fixed point number interface.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
const Expr * getInitializer() const
Definition: Expr.h:3074
Expr * getLHS() const
Definition: Expr.h:3445
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3625
CXXConstructorDecl * getConstructor() const
Definition: DeclCXX.h:2561
Represents a C11 generic selection.
Definition: Expr.h:5196
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:550
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
Represents an element in a path from a derived class to a base class.
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3878
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:3819
bool isStringType() const
Definition: Expr.h:4288
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3835
bool isTypeOperand() const
Definition: ExprCXX.h:713
Dataflow Directional Tag Classes.
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class...
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1385
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1032
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1873
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:580
static bool isZeroSized(const LValue &Value)
bool isImplicit() const
Definition: ExprCXX.h:1027
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:359
bool isAbsent() const
Definition: APValue.h:313
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2858
AccessSpecifier getAccess() const
Definition: DeclBase.h:473
const Expr * getInit() const
Definition: Decl.h:1219
A decomposition declaration.
Definition: DeclCXX.h:3988
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:396
StmtClass getStmtClass() const
Definition: Stmt.h:1087
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2237
const Expr * getExpr() const
Definition: ExprCXX.h:1150
bool isBooleanType() const
Definition: Type.h:6760
unsigned getArrayInitializedElts() const
Definition: APValue.h:442
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2788
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1395
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
bool toIntegralConstant(APSInt &Result, QualType SrcTy, const ASTContext &Ctx) const
Try to convert this value to an integral constant.
Definition: APValue.cpp:687
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3308
body_iterator body_begin()
Definition: Stmt.h:1344
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:786
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2048
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This)
Check that the pointee of the &#39;this&#39; pointer in a member function call is either within its lifetime ...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2942
llvm::APInt getValue() const
Definition: Expr.h:1400
LabelDecl * getLabel() const
Definition: Expr.h:3900
static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
path_iterator path_end()
Definition: Expr.h:3194
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:3864
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:2017
bool isStringLiteralInit() const
Definition: Expr.cpp:2266
bool isArray() const
Definition: APValue.h:324
unsigned getIntWidth(QualType T) const
bool isIncompleteArrayType() const
Definition: Type.h:6448
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:553
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4438
Complex values, per C99 6.2.5p11.
Definition: Type.h:2509
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6.7.5p3.
Definition: Type.cpp:2052
bool body_empty() const
Definition: Stmt.h:1337
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2384
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2432
bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, const ASTContext &Ctx) const
Evaluate an expression that is required to be a constant expression.
static bool hasFields(const CXXRecordDecl *RD)
Determine if a class has any fields that might need to be copied by a trivial copy or move operation...
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1384
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6677
bool isStruct() const
Definition: APValue.h:325
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:407
T * getAttr() const
Definition: DeclBase.h:538
An implicit indirection through a C++ base class, when the field found is in a base class...
Definition: Expr.h:2145
const llvm::APInt & getSize() const
Definition: Type.h:2922
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
bool isAtomicType() const
Definition: Type.h:6501
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
bool isFunctionType() const
Definition: Type.h:6380
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
Stmt * getInit()
Definition: Stmt.h:2098
CXXBasePath & front()
Opcode getOpcode() const
Definition: Expr.h:2041
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3481
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1482
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2705
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
decl_range decls()
Definition: Stmt.h:1251
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
APFixedPoint convert(const FixedPointSemantics &DstSema, bool *Overflow=nullptr) const
Definition: FixedPoint.cpp:18
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:76
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2079
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2062
DeclStmt * getRangeStmt()
Definition: StmtCXX.h:161
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2075
unsigned getConstexprBacktraceLimit() const
Retrieve the maximum number of constexpr evaluation notes to emit along with a given diagnostic...
Definition: Diagnostic.h:581
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:524
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1188
A template argument list.
Definition: DeclTemplate.h:214
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class...
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1453
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition: DeclCXX.h:1369
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
Expr * getCond()
Definition: Stmt.h:2346
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:875
ValueKind getKind() const
Definition: APValue.h:311
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2807
ActionResult< Expr * > ExprResult
Definition: Ownership.h:263
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6222
bool hasUnaligned() const
Definition: Type.h:293
APFloat & getComplexFloatImag()
Definition: APValue.h:390
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
#define scalbn(__x, __y)
Definition: tgmath.h:1165
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
Expr * getTrueExpr() const
Definition: Expr.h:3741
Represents a loop initializing the elements of an array.
Definition: Expr.h:4989
bool isVoidType() const
Definition: Type.h:6643
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4098
static bool isReadByLvalueToRvalueConversion(QualType T)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3776
An index into an array.
Definition: Expr.h:2138
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6169
There is no such object (it&#39;s outside its lifetime).
Definition: APValue.h:82
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:2200
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
base_class_iterator bases_end()
Definition: DeclCXX.h:834
bool isRValue() const
Definition: Expr.h:259
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition: APValue.h:148
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:60
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2423
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:251
__DEVICE__ int min(int __a, int __b)
CheckSubobjectKind
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1681
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:487
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2516
AccessSpecifier Access
The access along this inheritance path.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3513
bool hasVolatile() const
Definition: Type.h:259
unsigned getNumElements() const
Definition: Type.h:3236
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:85
unsigned getNumComponents() const
Definition: Expr.h:2296
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2108
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression...
Definition: ExprCXX.h:1884
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1141
result[0]
Definition: emmintrin.h:120
bool isUnion() const
Definition: Decl.h:3285
Expr * getRHS() const
Definition: Expr.h:3447
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:36
SourceLocation getBeginLoc() const
Definition: Stmt.h:1467
bool isPointerType() const
Definition: Type.h:6384
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1257
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4483
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1104
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluted - Return true if this expression might be usable in a constant expr...
DeclStmt * getLoopVarStmt()
Definition: StmtCXX.h:168
QualType getType() const
Definition: Decl.h:647
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1479
bool isFloatingType() const
Definition: Type.cpp:1952
static bool isModification(AccessKinds AK)
static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
This represents a decl that may have a name.
Definition: Decl.h:248
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:554
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type, member-designator).
Definition: Expr.h:2237
APValue::ValueKind getResultAPValueKind() const
Definition: Expr.h:1020
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:909
Automatic storage duration (most local variables).
Definition: Specifiers.h:307
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.h:537
APSInt & getInt()
Definition: APValue.h:336
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr...
Definition: ExprCXX.cpp:61
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:3816
DeclStmt * getBeginStmt()
Definition: StmtCXX.h:162
bool isFunctionPointerType() const
Definition: Type.h:6408
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3495
Attempt to be ABI-compatible with code generated by Clang 7.0.x (SVN r338536).
const LangOptions & getLangOpts() const
Definition: ASTContext.h:710
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2904
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5079
APFixedPoint & getFixedPoint()
Definition: APValue.h:358
Attr - This represents one attribute.
Definition: Attr.h:43
static void describeCall(CallStackFrame *Frame, raw_ostream &Out)
Produce a string describing the given constexpr call.
SourceLocation getLocation() const
Definition: DeclBase.h:429
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2938
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the the correct result kind for this category.
CharUnits & getLValueOffset()
Definition: APValue.cpp:717
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
static ObjectUnderConstruction getEmptyKey()
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:291
unsigned getVectorLength() const
Definition: APValue.h:418