Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/ExprConstant.cpp
Line
Count
Source (jump to first uncovered line)
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 "Interp/Context.h"
36
#include "Interp/Frame.h"
37
#include "Interp/State.h"
38
#include "clang/AST/APValue.h"
39
#include "clang/AST/ASTContext.h"
40
#include "clang/AST/ASTDiagnostic.h"
41
#include "clang/AST/ASTLambda.h"
42
#include "clang/AST/Attr.h"
43
#include "clang/AST/CXXInheritance.h"
44
#include "clang/AST/CharUnits.h"
45
#include "clang/AST/CurrentSourceLocExprScope.h"
46
#include "clang/AST/Expr.h"
47
#include "clang/AST/OSLog.h"
48
#include "clang/AST/OptionalDiagnostic.h"
49
#include "clang/AST/RecordLayout.h"
50
#include "clang/AST/StmtVisitor.h"
51
#include "clang/AST/TypeLoc.h"
52
#include "clang/Basic/Builtins.h"
53
#include "clang/Basic/TargetInfo.h"
54
#include "llvm/ADT/APFixedPoint.h"
55
#include "llvm/ADT/Optional.h"
56
#include "llvm/ADT/SmallBitVector.h"
57
#include "llvm/Support/Debug.h"
58
#include "llvm/Support/SaveAndRestore.h"
59
#include "llvm/Support/raw_ostream.h"
60
#include <cstring>
61
#include <functional>
62
63
#define DEBUG_TYPE "exprconstant"
64
65
using namespace clang;
66
using llvm::APFixedPoint;
67
using llvm::APInt;
68
using llvm::APSInt;
69
using llvm::APFloat;
70
using llvm::FixedPointSemantics;
71
using llvm::Optional;
72
73
namespace {
74
  struct LValue;
75
  class CallStackFrame;
76
  class EvalInfo;
77
78
  using SourceLocExprScopeGuard =
79
      CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80
81
19.3M
  static QualType getType(APValue::LValueBase B) {
82
19.3M
    return B.getType();
83
19.3M
  }
84
85
  /// Get an LValue path entry, which is known to not be an array index, as a
86
  /// field declaration.
87
42.5k
  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88
42.5k
    return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89
42.5k
  }
90
  /// Get an LValue path entry, which is known to not be an array index, as a
91
  /// base class declaration.
92
2.93k
  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93
2.93k
    return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94
2.93k
  }
95
  /// Determine whether this LValue path entry for a base class names a virtual
96
  /// base class.
97
807
  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98
807
    return E.getAsBaseOrMember().getInt();
99
807
  }
100
101
  /// Given an expression, determine the type used to store the result of
102
  /// evaluating that expression.
103
1.84M
  static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104
1.84M
    if (E->isPRValue())
105
1.81M
      return E->getType();
106
34.1k
    return Ctx.getLValueReferenceType(E->getType());
107
1.84M
  }
108
109
  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110
6.12k
  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111
6.12k
    if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112
4.54k
      return DirectCallee->getAttr<AllocSizeAttr>();
113
1.58k
    if (const Decl *IndirectCallee = CE->getCalleeDecl())
114
1.58k
      return IndirectCallee->getAttr<AllocSizeAttr>();
115
0
    return nullptr;
116
1.58k
  }
117
118
  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119
  /// This will look through a single cast.
120
  ///
121
  /// Returns null if we couldn't unwrap a function with alloc_size.
122
5.14k
  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123
5.14k
    if (!E->getType()->isPointerType())
124
0
      return nullptr;
125
126
5.14k
    E = E->IgnoreParens();
127
    // If we're doing a variable assignment from e.g. malloc(N), there will
128
    // probably be a cast of some kind. In exotic cases, we might also see a
129
    // top-level ExprWithCleanups. Ignore them either way.
130
5.14k
    if (const auto *FE = dyn_cast<FullExpr>(E))
131
15
      E = FE->getSubExpr()->IgnoreParens();
132
133
5.14k
    if (const auto *Cast = dyn_cast<CastExpr>(E))
134
1.79k
      E = Cast->getSubExpr()->IgnoreParens();
135
136
5.14k
    if (const auto *CE = dyn_cast<CallExpr>(E))
137
4.94k
      return getAllocSizeAttr(CE) ? 
CE4.35k
:
nullptr588
;
138
202
    return nullptr;
139
5.14k
  }
140
141
  /// Determines whether or not the given Base contains a call to a function
142
  /// with the alloc_size attribute.
143
788k
  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144
788k
    const auto *E = Base.dyn_cast<const Expr *>();
145
788k
    return E && 
E->getType()->isPointerType()44.3k
&&
tryUnwrapAllocSizeCall(E)2.61k
;
146
788k
  }
147
148
  /// Determines whether the given kind of constant expression is only ever
149
  /// used for name mangling. If so, it's permitted to reference things that we
150
  /// can't generate code for (in particular, dllimported functions).
151
27.5k
  static bool isForManglingOnly(ConstantExprKind Kind) {
152
27.5k
    switch (Kind) {
153
26.9k
    case ConstantExprKind::Normal:
154
26.9k
    case ConstantExprKind::ClassTemplateArgument:
155
26.9k
    case ConstantExprKind::ImmediateInvocation:
156
      // Note that non-type template arguments of class type are emitted as
157
      // template parameter objects.
158
26.9k
      return false;
159
160
549
    case ConstantExprKind::NonClassTemplateArgument:
161
549
      return true;
162
27.5k
    }
163
0
    llvm_unreachable("unknown ConstantExprKind");
164
0
  }
165
166
92.4k
  static bool isTemplateArgument(ConstantExprKind Kind) {
167
92.4k
    switch (Kind) {
168
91.6k
    case ConstantExprKind::Normal:
169
91.7k
    case ConstantExprKind::ImmediateInvocation:
170
91.7k
      return false;
171
172
46
    case ConstantExprKind::ClassTemplateArgument:
173
726
    case ConstantExprKind::NonClassTemplateArgument:
174
726
      return true;
175
92.4k
    }
176
0
    llvm_unreachable("unknown ConstantExprKind");
177
0
  }
178
179
  /// The bound to claim that an array of unknown bound has.
180
  /// The value in MostDerivedArraySize is undefined in this case. So, set it
181
  /// to an arbitrary value that's likely to loudly break things if it's used.
182
  static const uint64_t AssumedSizeForUnsizedArray =
183
      std::numeric_limits<uint64_t>::max() / 2;
184
185
  /// Determines if an LValue with the given LValueBase will have an unsized
186
  /// array in its designator.
187
  /// Find the path length and type of the most-derived subobject in the given
188
  /// path, and find the size of the containing array, if any.
189
  static unsigned
190
  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191
                           ArrayRef<APValue::LValuePathEntry> Path,
192
                           uint64_t &ArraySize, QualType &Type, bool &IsArray,
193
784k
                           bool &FirstEntryIsUnsizedArray) {
194
    // This only accepts LValueBases from APValues, and APValues don't support
195
    // arrays that lack size info.
196
784k
    assert(!isBaseAnAllocSizeCall(Base) &&
197
784k
           "Unsized arrays shouldn't appear here");
198
0
    unsigned MostDerivedLength = 0;
199
784k
    Type = getType(Base);
200
201
844k
    for (unsigned I = 0, N = Path.size(); I != N; 
++I60.4k
) {
202
60.4k
      if (Type->isArrayType()) {
203
41.7k
        const ArrayType *AT = Ctx.getAsArrayType(Type);
204
41.7k
        Type = AT->getElementType();
205
41.7k
        MostDerivedLength = I + 1;
206
41.7k
        IsArray = true;
207
208
41.7k
        if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209
41.5k
          ArraySize = CAT->getSize().getZExtValue();
210
41.5k
        } else {
211
133
          assert(I == 0 && "unexpected unsized array designator");
212
0
          FirstEntryIsUnsizedArray = true;
213
133
          ArraySize = AssumedSizeForUnsizedArray;
214
133
        }
215
41.7k
      } else 
if (18.7k
Type->isAnyComplexType()18.7k
) {
216
71
        const ComplexType *CT = Type->castAs<ComplexType>();
217
71
        Type = CT->getElementType();
218
71
        ArraySize = 2;
219
71
        MostDerivedLength = I + 1;
220
71
        IsArray = true;
221
18.6k
      } else if (const FieldDecl *FD = getAsField(Path[I])) {
222
15.1k
        Type = FD->getType();
223
15.1k
        ArraySize = 0;
224
15.1k
        MostDerivedLength = I + 1;
225
15.1k
        IsArray = false;
226
15.1k
      } else {
227
        // Path[I] describes a base class.
228
3.47k
        ArraySize = 0;
229
3.47k
        IsArray = false;
230
3.47k
      }
231
60.4k
    }
232
784k
    return MostDerivedLength;
233
784k
  }
234
235
  /// A path from a glvalue to a subobject of that glvalue.
236
  struct SubobjectDesignator {
237
    /// True if the subobject was named in a manner not supported by C++11. Such
238
    /// lvalues can still be folded, but they are not core constant expressions
239
    /// and we cannot perform lvalue-to-rvalue conversions on them.
240
    unsigned Invalid : 1;
241
242
    /// Is this a pointer one past the end of an object?
243
    unsigned IsOnePastTheEnd : 1;
244
245
    /// Indicator of whether the first entry is an unsized array.
246
    unsigned FirstEntryIsAnUnsizedArray : 1;
247
248
    /// Indicator of whether the most-derived object is an array element.
249
    unsigned MostDerivedIsArrayElement : 1;
250
251
    /// The length of the path to the most-derived object of which this is a
252
    /// subobject.
253
    unsigned MostDerivedPathLength : 28;
254
255
    /// The size of the array of which the most-derived object is an element.
256
    /// This will always be 0 if the most-derived object is not an array
257
    /// element. 0 is not an indicator of whether or not the most-derived object
258
    /// is an array, however, because 0-length arrays are allowed.
259
    ///
260
    /// If the current array is an unsized array, the value of this is
261
    /// undefined.
262
    uint64_t MostDerivedArraySize;
263
264
    /// The type of the most derived object referred to by this address.
265
    QualType MostDerivedType;
266
267
    typedef APValue::LValuePathEntry PathEntry;
268
269
    /// The entries on the path from the glvalue to the designated subobject.
270
    SmallVector<PathEntry, 8> Entries;
271
272
14.5M
    SubobjectDesignator() : Invalid(true) {}
273
274
    explicit SubobjectDesignator(QualType T)
275
        : Invalid(false), IsOnePastTheEnd(false),
276
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277
          MostDerivedPathLength(0), MostDerivedArraySize(0),
278
11.6M
          MostDerivedType(T) {}
279
280
    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281
        : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283
803k
          MostDerivedPathLength(0), MostDerivedArraySize(0) {
284
803k
      assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285
803k
      if (!Invalid) {
286
798k
        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287
798k
        ArrayRef<PathEntry> VEntries = V.getLValuePath();
288
798k
        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289
798k
        if (V.getLValueBase()) {
290
784k
          bool IsArray = false;
291
784k
          bool FirstIsUnsizedArray = false;
292
784k
          MostDerivedPathLength = findMostDerivedSubobject(
293
784k
              Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294
784k
              MostDerivedType, IsArray, FirstIsUnsizedArray);
295
784k
          MostDerivedIsArrayElement = IsArray;
296
784k
          FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297
784k
        }
298
798k
      }
299
803k
    }
300
301
    void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302
149
                  unsigned NewLength) {
303
149
      if (Invalid)
304
0
        return;
305
306
149
      assert(Base && "cannot truncate path for null pointer");
307
0
      assert(NewLength <= Entries.size() && "not a truncation");
308
309
149
      if (NewLength == Entries.size())
310
0
        return;
311
149
      Entries.resize(NewLength);
312
313
149
      bool IsArray = false;
314
149
      bool FirstIsUnsizedArray = false;
315
149
      MostDerivedPathLength = findMostDerivedSubobject(
316
149
          Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317
149
          FirstIsUnsizedArray);
318
149
      MostDerivedIsArrayElement = IsArray;
319
149
      FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320
149
    }
321
322
9.65k
    void setInvalid() {
323
9.65k
      Invalid = true;
324
9.65k
      Entries.clear();
325
9.65k
    }
326
327
    /// Determine whether the most derived subobject is an array without a
328
    /// known bound.
329
3.87M
    bool isMostDerivedAnUnsizedArray() const {
330
3.87M
      assert(!Invalid && "Calling this makes no sense on invalid designators");
331
3.87M
      return Entries.size() == 1 && 
FirstEntryIsAnUnsizedArray317k
;
332
3.87M
    }
333
334
    /// Determine what the most derived array's size is. Results in an assertion
335
    /// failure if the most derived array lacks a size.
336
118k
    uint64_t getMostDerivedArraySize() const {
337
118k
      assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338
0
      return MostDerivedArraySize;
339
118k
    }
340
341
    /// Determine whether this is a one-past-the-end pointer.
342
1.96M
    bool isOnePastTheEnd() const {
343
1.96M
      assert(!Invalid);
344
1.96M
      if (IsOnePastTheEnd)
345
105
        return true;
346
1.96M
      if (!isMostDerivedAnUnsizedArray() && 
MostDerivedIsArrayElement1.96M
&&
347
1.96M
          Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348
53.0k
              MostDerivedArraySize)
349
744
        return true;
350
1.96M
      return false;
351
1.96M
    }
352
353
    /// Get the range of valid index adjustments in the form
354
    ///   {maximum value that can be subtracted from this pointer,
355
    ///    maximum value that can be added to this pointer}
356
1.47k
    std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357
1.47k
      if (Invalid || isMostDerivedAnUnsizedArray())
358
64
        return {0, 0};
359
360
      // [expr.add]p4: For the purposes of these operators, a pointer to a
361
      // nonarray object behaves the same as a pointer to the first element of
362
      // an array of length one with the type of the object as its element type.
363
1.41k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
364
1.41k
                     
MostDerivedIsArrayElement1.33k
;
365
1.41k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()1.27k
366
1.41k
                                    : 
(uint64_t)IsOnePastTheEnd136
;
367
1.41k
      uint64_t ArraySize =
368
1.41k
          IsArray ? 
getMostDerivedArraySize()1.27k
:
(uint64_t)1136
;
369
1.41k
      return {ArrayIndex, ArraySize - ArrayIndex};
370
1.47k
    }
371
372
    /// Check that this refers to a valid subobject.
373
0
    bool isValidSubobject() const {
374
0
      if (Invalid)
375
0
        return false;
376
0
      return !isOnePastTheEnd();
377
0
    }
378
    /// Check that this refers to a valid subobject, and if not, produce a
379
    /// relevant diagnostic and set the designator as invalid.
380
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381
382
    /// Get the type of the designated object.
383
11.4k
    QualType getType(ASTContext &Ctx) const {
384
11.4k
      assert(!Invalid && "invalid designator has no subobject type");
385
11.4k
      return MostDerivedPathLength == Entries.size()
386
11.4k
                 ? 
MostDerivedType11.3k
387
11.4k
                 : 
Ctx.getRecordType(getAsBaseClass(Entries.back()))120
;
388
11.4k
    }
389
390
    /// Update this designator to refer to the first element within this array.
391
85.3k
    void addArrayUnchecked(const ConstantArrayType *CAT) {
392
85.3k
      Entries.push_back(PathEntry::ArrayIndex(0));
393
394
      // This is a most-derived object.
395
85.3k
      MostDerivedType = CAT->getElementType();
396
85.3k
      MostDerivedIsArrayElement = true;
397
85.3k
      MostDerivedArraySize = CAT->getSize().getZExtValue();
398
85.3k
      MostDerivedPathLength = Entries.size();
399
85.3k
    }
400
    /// Update this designator to refer to the first element within the array of
401
    /// elements of type T. This is an array of unknown size.
402
4.65k
    void addUnsizedArrayUnchecked(QualType ElemTy) {
403
4.65k
      Entries.push_back(PathEntry::ArrayIndex(0));
404
405
4.65k
      MostDerivedType = ElemTy;
406
4.65k
      MostDerivedIsArrayElement = true;
407
      // The value in MostDerivedArraySize is undefined in this case. So, set it
408
      // to an arbitrary value that's likely to loudly break things if it's
409
      // used.
410
4.65k
      MostDerivedArraySize = AssumedSizeForUnsizedArray;
411
4.65k
      MostDerivedPathLength = Entries.size();
412
4.65k
    }
413
    /// Update this designator to refer to the given base or member of this
414
    /// object.
415
169k
    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416
169k
      Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417
418
      // If this isn't a base class, it's a new most-derived object.
419
169k
      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420
157k
        MostDerivedType = FD->getType();
421
157k
        MostDerivedIsArrayElement = false;
422
157k
        MostDerivedArraySize = 0;
423
157k
        MostDerivedPathLength = Entries.size();
424
157k
      }
425
169k
    }
426
    /// Update this designator to refer to the given complex component.
427
461
    void addComplexUnchecked(QualType EltTy, bool Imag) {
428
461
      Entries.push_back(PathEntry::ArrayIndex(Imag));
429
430
      // This is technically a most-derived object, though in practice this
431
      // is unlikely to matter.
432
461
      MostDerivedType = EltTy;
433
461
      MostDerivedIsArrayElement = true;
434
461
      MostDerivedArraySize = 2;
435
461
      MostDerivedPathLength = Entries.size();
436
461
    }
437
    void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438
    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439
                                   const APSInt &N);
440
    /// Add N to the address of this subobject.
441
117k
    void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442
117k
      if (Invalid || !N) 
return0
;
443
117k
      uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444
117k
      if (isMostDerivedAnUnsizedArray()) {
445
580
        diagnoseUnsizedArrayPointerArithmetic(Info, E);
446
        // Can't verify -- trust that the user is doing the right thing (or if
447
        // not, trust that the caller will catch the bad behavior).
448
        // FIXME: Should we reject if this overflows, at least?
449
580
        Entries.back() = PathEntry::ArrayIndex(
450
580
            Entries.back().getAsArrayIndex() + TruncatedN);
451
580
        return;
452
580
      }
453
454
      // [expr.add]p4: For the purposes of these operators, a pointer to a
455
      // nonarray object behaves the same as a pointer to the first element of
456
      // an array of length one with the type of the object as its element type.
457
116k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
458
116k
                     
MostDerivedIsArrayElement116k
;
459
116k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()116k
460
116k
                                    : 
(uint64_t)IsOnePastTheEnd343
;
461
116k
      uint64_t ArraySize =
462
116k
          IsArray ? 
getMostDerivedArraySize()116k
:
(uint64_t)1343
;
463
464
116k
      if (N < -(int64_t)ArrayIndex || 
N > ArraySize - ArrayIndex116k
) {
465
        // Calculate the actual index in a wide enough type, so we can include
466
        // it in the note.
467
415
        N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468
415
        (llvm::APInt&)N += ArrayIndex;
469
415
        assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470
0
        diagnosePointerArithmetic(Info, E, N);
471
415
        setInvalid();
472
415
        return;
473
415
      }
474
475
116k
      ArrayIndex += TruncatedN;
476
116k
      assert(ArrayIndex <= ArraySize &&
477
116k
             "bounds check succeeded for out-of-bounds index");
478
479
116k
      if (IsArray)
480
116k
        Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481
216
      else
482
216
        IsOnePastTheEnd = (ArrayIndex != 0);
483
116k
    }
484
  };
485
486
  /// A scope at the end of which an object can need to be destroyed.
487
  enum class ScopeKind {
488
    Block,
489
    FullExpression,
490
    Call
491
  };
492
493
  /// A reference to a particular call and its arguments.
494
  struct CallRef {
495
20.3M
    CallRef() : OrigCallee(), CallIndex(0), Version() {}
496
    CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497
393k
        : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498
499
620k
    explicit operator bool() const { return OrigCallee; }
500
501
    /// Get the parameter that the caller initialized, corresponding to the
502
    /// given parameter in the callee.
503
202k
    const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504
202k
      return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505
202k
                        : 
PVD0
;
506
202k
    }
507
508
    /// The callee at the point where the arguments were evaluated. This might
509
    /// be different from the actual callee (a different redeclaration, or a
510
    /// virtual override), but this function's parameters are the ones that
511
    /// appear in the parameter map.
512
    const FunctionDecl *OrigCallee;
513
    /// The call index of the frame that holds the argument values.
514
    unsigned CallIndex;
515
    /// The version of the parameters corresponding to this call.
516
    unsigned Version;
517
  };
518
519
  /// A stack frame in the constexpr call stack.
520
  class CallStackFrame : public interp::Frame {
521
  public:
522
    EvalInfo &Info;
523
524
    /// Parent - The caller of this stack frame.
525
    CallStackFrame *Caller;
526
527
    /// Callee - The function which was called.
528
    const FunctionDecl *Callee;
529
530
    /// This - The binding for the this pointer in this call, if any.
531
    const LValue *This;
532
533
    /// Information on how to find the arguments to this call. Our arguments
534
    /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535
    /// key and this value as the version.
536
    CallRef Arguments;
537
538
    /// Source location information about the default argument or default
539
    /// initializer expression we're evaluating, if any.
540
    CurrentSourceLocExprScope CurSourceLocExprScope;
541
542
    // Note that we intentionally use std::map here so that references to
543
    // values are stable.
544
    typedef std::pair<const void *, unsigned> MapKeyTy;
545
    typedef std::map<MapKeyTy, APValue> MapTy;
546
    /// Temporaries - Temporary lvalues materialized within this stack frame.
547
    MapTy Temporaries;
548
549
    /// CallLoc - The location of the call expression for this call.
550
    SourceLocation CallLoc;
551
552
    /// Index - The call index of this call.
553
    unsigned Index;
554
555
    /// The stack of integers for tracking version numbers for temporaries.
556
    SmallVector<unsigned, 2> TempVersionStack = {1};
557
    unsigned CurTempVersion = TempVersionStack.back();
558
559
48.8k
    unsigned getTempVersion() const { return TempVersionStack.back(); }
560
561
7.53M
    void pushTempVersion() {
562
7.53M
      TempVersionStack.push_back(++CurTempVersion);
563
7.53M
    }
564
565
7.53M
    void popTempVersion() {
566
7.53M
      TempVersionStack.pop_back();
567
7.53M
    }
568
569
393k
    CallRef createCall(const FunctionDecl *Callee) {
570
393k
      return {Callee, Index, ++CurTempVersion};
571
393k
    }
572
573
    // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574
    // on the overall stack usage of deeply-recursing constexpr evaluations.
575
    // (We should cache this map rather than recomputing it repeatedly.)
576
    // But let's try this and see how it goes; we can look into caching the map
577
    // as a later change.
578
579
    /// LambdaCaptureFields - Mapping from captured variables/this to
580
    /// corresponding data members in the closure class.
581
    llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582
    FieldDecl *LambdaThisCaptureField;
583
584
    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585
                   const FunctionDecl *Callee, const LValue *This,
586
                   CallRef Arguments);
587
    ~CallStackFrame();
588
589
    // Return the temporary for Key whose version number is Version.
590
328k
    APValue *getTemporary(const void *Key, unsigned Version) {
591
328k
      MapKeyTy KV(Key, Version);
592
328k
      auto LB = Temporaries.lower_bound(KV);
593
328k
      if (LB != Temporaries.end() && 
LB->first == KV325k
)
594
325k
        return &LB->second;
595
      // Pair (Key,Version) wasn't found in the map. Check that no elements
596
      // in the map have 'Key' as their key.
597
3.65k
      assert((LB == Temporaries.end() || LB->first.first != Key) &&
598
3.65k
             (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599
3.65k
             "Element with key 'Key' found in map");
600
0
      return nullptr;
601
328k
    }
602
603
    // Return the current temporary for Key in the map.
604
3.69k
    APValue *getCurrentTemporary(const void *Key) {
605
3.69k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606
3.69k
      if (UB != Temporaries.begin() && 
std::prev(UB)->first.first == Key2.70k
)
607
2.68k
        return &std::prev(UB)->second;
608
1.00k
      return nullptr;
609
3.69k
    }
610
611
    // Return the version number of the current temporary for Key.
612
89.2k
    unsigned getCurrentTemporaryVersion(const void *Key) const {
613
89.2k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614
89.2k
      if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615
89.2k
        return std::prev(UB)->first.second;
616
0
      return 0;
617
89.2k
    }
618
619
    /// Allocate storage for an object of type T in this stack frame.
620
    /// Populates LV with a handle to the created object. Key identifies
621
    /// the temporary within the stack frame, and must not be reused without
622
    /// bumping the temporary version number.
623
    template<typename KeyT>
624
    APValue &createTemporary(const KeyT *Key, QualType T,
625
                             ScopeKind Scope, LValue &LV);
626
627
    /// Allocate storage for a parameter of a function call made in this frame.
628
    APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629
630
    void describe(llvm::raw_ostream &OS) override;
631
632
2.81k
    Frame *getCaller() const override { return Caller; }
633
2.81k
    SourceLocation getCallLocation() const override { return CallLoc; }
634
5.89k
    const FunctionDecl *getCallee() const override { return Callee; }
635
636
115
    bool isStdFunction() const {
637
174
      for (const DeclContext *DC = Callee; DC; 
DC = DC->getParent()59
)
638
112
        if (DC->isStdNamespace())
639
53
          return true;
640
62
      return false;
641
115
    }
642
643
  private:
644
    APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645
                         ScopeKind Scope);
646
  };
647
648
  /// Temporarily override 'this'.
649
  class ThisOverrideRAII {
650
  public:
651
    ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652
33.5k
        : Frame(Frame), OldThis(Frame.This) {
653
33.5k
      if (Enable)
654
2.84k
        Frame.This = NewThis;
655
33.5k
    }
656
33.5k
    ~ThisOverrideRAII() {
657
33.5k
      Frame.This = OldThis;
658
33.5k
    }
659
  private:
660
    CallStackFrame &Frame;
661
    const LValue *OldThis;
662
  };
663
}
664
665
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666
                              const LValue &This, QualType ThisType);
667
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668
                              APValue::LValueBase LVBase, APValue &Value,
669
                              QualType T);
670
671
namespace {
672
  /// A cleanup, and a flag indicating whether it is lifetime-extended.
673
  class Cleanup {
674
    llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675
    APValue::LValueBase Base;
676
    QualType T;
677
678
  public:
679
    Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680
            ScopeKind Scope)
681
514k
        : Value(Val, Scope), Base(Base), T(T) {}
682
683
    /// Determine whether this cleanup should be performed at the end of the
684
    /// given kind of scope.
685
1.06M
    bool isDestroyedAtEndOf(ScopeKind K) const {
686
1.06M
      return (int)Value.getInt() >= (int)K;
687
1.06M
    }
688
490k
    bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689
490k
      if (RunDestructors) {
690
84.1k
        SourceLocation Loc;
691
84.1k
        if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692
77.0k
          Loc = VD->getLocation();
693
7.12k
        else if (const Expr *E = Base.dyn_cast<const Expr*>())
694
7.12k
          Loc = E->getExprLoc();
695
84.1k
        return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696
84.1k
      }
697
405k
      *Value.getPointer() = APValue();
698
405k
      return true;
699
490k
    }
700
701
24.1k
    bool hasSideEffect() {
702
24.1k
      return T.isDestructedType();
703
24.1k
    }
704
  };
705
706
  /// A reference to an object whose construction we are currently evaluating.
707
  struct ObjectUnderConstruction {
708
    APValue::LValueBase Base;
709
    ArrayRef<APValue::LValuePathEntry> Path;
710
    friend bool operator==(const ObjectUnderConstruction &LHS,
711
1.89M
                           const ObjectUnderConstruction &RHS) {
712
1.89M
      return LHS.Base == RHS.Base && 
LHS.Path == RHS.Path1.48M
;
713
1.89M
    }
714
106k
    friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715
106k
      return llvm::hash_combine(Obj.Base, Obj.Path);
716
106k
    }
717
  };
718
  enum class ConstructionPhase {
719
    None,
720
    Bases,
721
    AfterBases,
722
    AfterFields,
723
    Destroying,
724
    DestroyingBases
725
  };
726
}
727
728
namespace llvm {
729
template<> struct DenseMapInfo<ObjectUnderConstruction> {
730
  using Base = DenseMapInfo<APValue::LValueBase>;
731
174k
  static ObjectUnderConstruction getEmptyKey() {
732
174k
    return {Base::getEmptyKey(), {}}; }
733
153k
  static ObjectUnderConstruction getTombstoneKey() {
734
153k
    return {Base::getTombstoneKey(), {}};
735
153k
  }
736
106k
  static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737
106k
    return hash_value(Object);
738
106k
  }
739
  static bool isEqual(const ObjectUnderConstruction &LHS,
740
1.89M
                      const ObjectUnderConstruction &RHS) {
741
1.89M
    return LHS == RHS;
742
1.89M
  }
743
};
744
}
745
746
namespace {
747
  /// A dynamically-allocated heap object.
748
  struct DynAlloc {
749
    /// The value of this heap-allocated object.
750
    APValue Value;
751
    /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752
    /// or a CallExpr (the latter is for direct calls to operator new inside
753
    /// std::allocator<T>::allocate).
754
    const Expr *AllocExpr = nullptr;
755
756
    enum Kind {
757
      New,
758
      ArrayNew,
759
      StdAllocator
760
    };
761
762
    /// Get the kind of the allocation. This must match between allocation
763
    /// and deallocation.
764
214
    Kind getKind() const {
765
214
      if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766
190
        return NE->isArray() ? 
ArrayNew71
:
New119
;
767
24
      assert(isa<CallExpr>(AllocExpr));
768
0
      return StdAllocator;
769
214
    }
770
  };
771
772
  struct DynAllocOrder {
773
9.71k
    bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774
9.71k
      return L.getIndex() < R.getIndex();
775
9.71k
    }
776
  };
777
778
  /// EvalInfo - This is a private struct used by the evaluator to capture
779
  /// information about a subexpression as it is folded.  It retains information
780
  /// about the AST context, but also maintains information about the folded
781
  /// expression.
782
  ///
783
  /// If an expression could be evaluated, it is still possible it is not a C
784
  /// "integer constant expression" or constant expression.  If not, this struct
785
  /// captures information about how and why not.
786
  ///
787
  /// One bit of information passed *into* the request for constant folding
788
  /// indicates whether the subexpression is "evaluated" or not according to C
789
  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790
  /// evaluate the expression regardless of what the RHS is, but C only allows
791
  /// certain things in certain situations.
792
  class EvalInfo : public interp::State {
793
  public:
794
    ASTContext &Ctx;
795
796
    /// EvalStatus - Contains information about the evaluation.
797
    Expr::EvalStatus &EvalStatus;
798
799
    /// CurrentCall - The top of the constexpr call stack.
800
    CallStackFrame *CurrentCall;
801
802
    /// CallStackDepth - The number of calls in the call stack right now.
803
    unsigned CallStackDepth;
804
805
    /// NextCallIndex - The next call index to assign.
806
    unsigned NextCallIndex;
807
808
    /// StepsLeft - The remaining number of evaluation steps we're permitted
809
    /// to perform. This is essentially a limit for the number of statements
810
    /// we will evaluate.
811
    unsigned StepsLeft;
812
813
    /// Enable the experimental new constant interpreter. If an expression is
814
    /// not supported by the interpreter, an error is triggered.
815
    bool EnableNewConstInterp;
816
817
    /// BottomFrame - The frame in which evaluation started. This must be
818
    /// initialized after CurrentCall and CallStackDepth.
819
    CallStackFrame BottomFrame;
820
821
    /// A stack of values whose lifetimes end at the end of some surrounding
822
    /// evaluation frame.
823
    llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825
    /// EvaluatingDecl - This is the declaration whose initializer is being
826
    /// evaluated, if any.
827
    APValue::LValueBase EvaluatingDecl;
828
829
    enum class EvaluatingDeclKind {
830
      None,
831
      /// We're evaluating the construction of EvaluatingDecl.
832
      Ctor,
833
      /// We're evaluating the destruction of EvaluatingDecl.
834
      Dtor,
835
    };
836
    EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838
    /// EvaluatingDeclValue - This is the value being constructed for the
839
    /// declaration whose initializer is being evaluated, if any.
840
    APValue *EvaluatingDeclValue;
841
842
    /// Set of objects that are currently being constructed.
843
    llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844
        ObjectsUnderConstruction;
845
846
    /// Current heap allocations, along with the location where each was
847
    /// allocated. We use std::map here because we need stable addresses
848
    /// for the stored APValues.
849
    std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850
851
    /// The number of heap allocations performed so far in this evaluation.
852
    unsigned NumHeapAllocs = 0;
853
854
    struct EvaluatingConstructorRAII {
855
      EvalInfo &EI;
856
      ObjectUnderConstruction Object;
857
      bool DidInsert;
858
      EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859
                                bool HasBases)
860
27.3k
          : EI(EI), Object(Object) {
861
27.3k
        DidInsert =
862
27.3k
            EI.ObjectsUnderConstruction
863
27.3k
                .insert({Object, HasBases ? 
ConstructionPhase::Bases1.35k
864
27.3k
                                          : 
ConstructionPhase::AfterBases25.9k
})
865
27.3k
                .second;
866
27.3k
      }
867
1.27k
      void finishedConstructingBases() {
868
1.27k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869
1.27k
      }
870
24.1k
      void finishedConstructingFields() {
871
24.1k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872
24.1k
      }
873
27.3k
      ~EvaluatingConstructorRAII() {
874
27.3k
        if (DidInsert) 
EI.ObjectsUnderConstruction.erase(Object)27.3k
;
875
27.3k
      }
876
    };
877
878
    struct EvaluatingDestructorRAII {
879
      EvalInfo &EI;
880
      ObjectUnderConstruction Object;
881
      bool DidInsert;
882
      EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883
335
          : EI(EI), Object(Object) {
884
335
        DidInsert = EI.ObjectsUnderConstruction
885
335
                        .insert({Object, ConstructionPhase::Destroying})
886
335
                        .second;
887
335
      }
888
47
      void startedDestroyingBases() {
889
47
        EI.ObjectsUnderConstruction[Object] =
890
47
            ConstructionPhase::DestroyingBases;
891
47
      }
892
335
      ~EvaluatingDestructorRAII() {
893
335
        if (DidInsert)
894
334
          EI.ObjectsUnderConstruction.erase(Object);
895
335
      }
896
    };
897
898
    ConstructionPhase
899
    isEvaluatingCtorDtor(APValue::LValueBase Base,
900
28.6k
                         ArrayRef<APValue::LValuePathEntry> Path) {
901
28.6k
      return ObjectsUnderConstruction.lookup({Base, Path});
902
28.6k
    }
903
904
    /// If we're currently speculatively evaluating, the outermost call stack
905
    /// depth at which we can mutate state, otherwise 0.
906
    unsigned SpeculativeEvaluationDepth = 0;
907
908
    /// The current array initialization index, if we're performing array
909
    /// initialization.
910
    uint64_t ArrayInitIndex = -1;
911
912
    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913
    /// notes attached to it will also be stored, otherwise they will not be.
914
    bool HasActiveDiagnostic;
915
916
    /// Have we emitted a diagnostic explaining why we couldn't constant
917
    /// fold (not just why it's not strictly a constant expression)?
918
    bool HasFoldFailureDiagnostic;
919
920
    /// Whether or not we're in a context where the front end requires a
921
    /// constant value.
922
    bool InConstantContext;
923
924
    /// Whether we're checking that an expression is a potential constant
925
    /// expression. If so, do not fail on constructs that could become constant
926
    /// later on (such as a use of an undefined global).
927
    bool CheckingPotentialConstantExpression = false;
928
929
    /// Whether we're checking for an expression that has undefined behavior.
930
    /// If so, we will produce warnings if we encounter an operation that is
931
    /// always undefined.
932
    ///
933
    /// Note that we still need to evaluate the expression normally when this
934
    /// is set; this is used when evaluating ICEs in C.
935
    bool CheckingForUndefinedBehavior = false;
936
937
    enum EvaluationMode {
938
      /// Evaluate as a constant expression. Stop if we find that the expression
939
      /// is not a constant expression.
940
      EM_ConstantExpression,
941
942
      /// Evaluate as a constant expression. Stop if we find that the expression
943
      /// is not a constant expression. Some expressions can be retried in the
944
      /// optimizer if we don't constant fold them here, but in an unevaluated
945
      /// context we try to fold them immediately since the optimizer never
946
      /// gets a chance to look at it.
947
      EM_ConstantExpressionUnevaluated,
948
949
      /// Fold the expression to a constant. Stop if we hit a side-effect that
950
      /// we can't model.
951
      EM_ConstantFold,
952
953
      /// Evaluate in any way we know how. Don't worry about side-effects that
954
      /// can't be modeled.
955
      EM_IgnoreSideEffects,
956
    } EvalMode;
957
958
    /// Are we checking whether the expression is a potential constant
959
    /// expression?
960
10.3M
    bool checkingPotentialConstantExpression() const override  {
961
10.3M
      return CheckingPotentialConstantExpression;
962
10.3M
    }
963
964
    /// Are we checking an expression for overflow?
965
    // FIXME: We should check for any kind of undefined or suspicious behavior
966
    // in such constructs, not just overflow.
967
4.52M
    bool checkingForUndefinedBehavior() const override {
968
4.52M
      return CheckingForUndefinedBehavior;
969
4.52M
    }
970
971
    EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972
        : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973
          CallStackDepth(0), NextCallIndex(1),
974
          StepsLeft(C.getLangOpts().ConstexprStepLimit),
975
          EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976
          BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977
          EvaluatingDecl((const ValueDecl *)nullptr),
978
          EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979
          HasFoldFailureDiagnostic(false), InConstantContext(false),
980
19.5M
          EvalMode(Mode) {}
981
982
19.5M
    ~EvalInfo() {
983
19.5M
      discardCleanups();
984
19.5M
    }
985
986
    void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987
2.31M
                           EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988
2.31M
      EvaluatingDecl = Base;
989
2.31M
      IsEvaluatingDecl = EDK;
990
2.31M
      EvaluatingDeclValue = &Value;
991
2.31M
    }
992
993
148k
    bool CheckCallLimit(SourceLocation Loc) {
994
      // Don't perform any constexpr calls (other than the call we're checking)
995
      // when checking a potential constant expression.
996
148k
      if (checkingPotentialConstantExpression() && 
CallStackDepth > 151.6k
)
997
2.81k
        return false;
998
145k
      if (NextCallIndex == 0) {
999
        // NextCallIndex has wrapped around.
1000
0
        FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001
0
        return false;
1002
0
      }
1003
145k
      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004
145k
        return true;
1005
12
      FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006
12
        << getLangOpts().ConstexprCallDepth;
1007
12
      return false;
1008
145k
    }
1009
1010
    std::pair<CallStackFrame *, unsigned>
1011
492k
    getCallFrameAndDepth(unsigned CallIndex) {
1012
492k
      assert(CallIndex && "no call index in getCallFrameAndDepth");
1013
      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014
      // be null in this loop.
1015
0
      unsigned Depth = CallStackDepth;
1016
492k
      CallStackFrame *Frame = CurrentCall;
1017
1.04M
      while (Frame->Index > CallIndex) {
1018
552k
        Frame = Frame->Caller;
1019
552k
        --Depth;
1020
552k
      }
1021
492k
      if (Frame->Index == CallIndex)
1022
492k
        return {Frame, Depth};
1023
14
      return {nullptr, 0};
1024
492k
    }
1025
1026
3.48M
    bool nextStep(const Stmt *S) {
1027
3.48M
      if (!StepsLeft) {
1028
6
        FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029
6
        return false;
1030
6
      }
1031
3.48M
      --StepsLeft;
1032
3.48M
      return true;
1033
3.48M
    }
1034
1035
    APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036
1037
2.72k
    Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038
2.72k
      Optional<DynAlloc*> Result;
1039
2.72k
      auto It = HeapAllocs.find(DA);
1040
2.72k
      if (It != HeapAllocs.end())
1041
2.71k
        Result = &It->second;
1042
2.72k
      return Result;
1043
2.72k
    }
1044
1045
    /// Get the allocated storage for the given parameter of the given call.
1046
5.82k
    APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047
5.82k
      CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048
5.82k
      return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049
5.82k
                   : 
nullptr0
;
1050
5.82k
    }
1051
1052
    /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053
    struct StdAllocatorCaller {
1054
      unsigned FrameIndex;
1055
      QualType ElemType;
1056
927
      explicit operator bool() const { return FrameIndex != 0; };
1057
    };
1058
1059
927
    StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060
930
      for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061
927
           
Call = Call->Caller3
) {
1062
129
        const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063
129
        if (!MD)
1064
3
          continue;
1065
126
        const IdentifierInfo *FnII = MD->getIdentifier();
1066
126
        if (!FnII || !FnII->isStr(FnName))
1067
0
          continue;
1068
1069
126
        const auto *CTSD =
1070
126
            dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071
126
        if (!CTSD)
1072
0
          continue;
1073
1074
126
        const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075
126
        const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076
126
        if (CTSD->isInStdNamespace() && ClassII &&
1077
126
            ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078
126
            TAL[0].getKind() == TemplateArgument::Type)
1079
126
          return {Call->Index, TAL[0].getAsType()};
1080
126
      }
1081
1082
801
      return {};
1083
927
    }
1084
1085
333k
    void performLifetimeExtension() {
1086
      // Disable the cleanups for lifetime-extended temporaries.
1087
333k
      CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1088
333k
                                        CleanupStack.end(),
1089
333k
                                        [](Cleanup &C) {
1090
345
                                          return !C.isDestroyedAtEndOf(
1091
345
                                              ScopeKind::FullExpression);
1092
345
                                        }),
1093
333k
                         CleanupStack.end());
1094
333k
     }
1095
1096
    /// Throw away any remaining cleanups at the end of evaluation. If any
1097
    /// cleanups would have had a side-effect, note that as an unmodeled
1098
    /// side-effect and return false. Otherwise, return true.
1099
23.5M
    bool discardCleanups() {
1100
23.5M
      for (Cleanup &C : CleanupStack) {
1101
24.1k
        if (C.hasSideEffect() && 
!noteSideEffect()1.66k
) {
1102
464
          CleanupStack.clear();
1103
464
          return false;
1104
464
        }
1105
24.1k
      }
1106
23.5M
      CleanupStack.clear();
1107
23.5M
      return true;
1108
23.5M
    }
1109
1110
  private:
1111
761k
    interp::Frame *getCurrentFrame() override { return CurrentCall; }
1112
761k
    const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1113
1114
4.31M
    bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1115
6.42M
    void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1116
1117
762k
    void setFoldFailureDiagnostic(bool Flag) override {
1118
762k
      HasFoldFailureDiagnostic = Flag;
1119
762k
    }
1120
1121
10.1M
    Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1122
1123
26.3M
    ASTContext &getCtx() const override { return Ctx; }
1124
1125
    // If we have a prior diagnostic, it will be noting that the expression
1126
    // isn't a constant expression. This diagnostic is more important,
1127
    // unless we require this evaluation to produce a constant expression.
1128
    //
1129
    // FIXME: We might want to show both diagnostics to the user in
1130
    // EM_ConstantFold mode.
1131
765k
    bool hasPriorDiagnostic() override {
1132
765k
      if (!EvalStatus.Diag->empty()) {
1133
4.40k
        switch (EvalMode) {
1134
937
        case EM_ConstantFold:
1135
1.00k
        case EM_IgnoreSideEffects:
1136
1.00k
          if (!HasFoldFailureDiagnostic)
1137
927
            break;
1138
          // We've already failed to fold something. Keep that diagnostic.
1139
1.00k
          
LLVM_FALLTHROUGH77
;77
1140
3.48k
        case EM_ConstantExpression:
1141
3.48k
        case EM_ConstantExpressionUnevaluated:
1142
3.48k
          setActiveDiagnostic(false);
1143
3.48k
          return true;
1144
4.40k
        }
1145
4.40k
      }
1146
762k
      return false;
1147
765k
    }
1148
1149
1.52M
    unsigned getCallStackDepth() override { return CallStackDepth; }
1150
1151
  public:
1152
    /// Should we continue evaluation after encountering a side-effect that we
1153
    /// couldn't model?
1154
1.46M
    bool keepEvaluatingAfterSideEffect() {
1155
1.46M
      switch (EvalMode) {
1156
57.2k
      case EM_IgnoreSideEffects:
1157
57.2k
        return true;
1158
1159
1.39M
      case EM_ConstantExpression:
1160
1.41M
      case EM_ConstantExpressionUnevaluated:
1161
1.41M
      case EM_ConstantFold:
1162
        // By default, assume any side effect might be valid in some other
1163
        // evaluation of this expression from a different context.
1164
1.41M
        return checkingPotentialConstantExpression() ||
1165
1.41M
               
checkingForUndefinedBehavior()1.32k
;
1166
1.46M
      }
1167
0
      llvm_unreachable("Missed EvalMode case");
1168
0
    }
1169
1170
    /// Note that we have had a side-effect, and determine whether we should
1171
    /// keep evaluating.
1172
1.46M
    bool noteSideEffect() {
1173
1.46M
      EvalStatus.HasSideEffects = true;
1174
1.46M
      return keepEvaluatingAfterSideEffect();
1175
1.46M
    }
1176
1177
    /// Should we continue evaluation after encountering undefined behavior?
1178
679
    bool keepEvaluatingAfterUndefinedBehavior() {
1179
679
      switch (EvalMode) {
1180
582
      case EM_IgnoreSideEffects:
1181
602
      case EM_ConstantFold:
1182
602
        return true;
1183
1184
77
      case EM_ConstantExpression:
1185
77
      case EM_ConstantExpressionUnevaluated:
1186
77
        return checkingForUndefinedBehavior();
1187
679
      }
1188
0
      llvm_unreachable("Missed EvalMode case");
1189
0
    }
1190
1191
    /// Note that we hit something that was technically undefined behavior, but
1192
    /// that we can evaluate past it (such as signed overflow or floating-point
1193
    /// division by zero.)
1194
679
    bool noteUndefinedBehavior() override {
1195
679
      EvalStatus.HasUndefinedBehavior = true;
1196
679
      return keepEvaluatingAfterUndefinedBehavior();
1197
679
    }
1198
1199
    /// Should we continue evaluation as much as possible after encountering a
1200
    /// construct which can't be reduced to a value?
1201
4.56M
    bool keepEvaluatingAfterFailure() const override {
1202
4.56M
      if (!StepsLeft)
1203
0
        return false;
1204
1205
4.56M
      switch (EvalMode) {
1206
169k
      case EM_ConstantExpression:
1207
190k
      case EM_ConstantExpressionUnevaluated:
1208
216k
      case EM_ConstantFold:
1209
4.56M
      case EM_IgnoreSideEffects:
1210
4.56M
        return checkingPotentialConstantExpression() ||
1211
4.56M
               
checkingForUndefinedBehavior()4.51M
;
1212
4.56M
      }
1213
0
      llvm_unreachable("Missed EvalMode case");
1214
0
    }
1215
1216
    /// Notes that we failed to evaluate an expression that other expressions
1217
    /// directly depend on, and determine if we should keep evaluating. This
1218
    /// should only be called if we actually intend to keep evaluating.
1219
    ///
1220
    /// Call noteSideEffect() instead if we may be able to ignore the value that
1221
    /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1222
    ///
1223
    /// (Foo(), 1)      // use noteSideEffect
1224
    /// (Foo() || true) // use noteSideEffect
1225
    /// Foo() + 1       // use noteFailure
1226
4.07M
    LLVM_NODISCARD bool noteFailure() {
1227
      // Failure when evaluating some expression often means there is some
1228
      // subexpression whose evaluation was skipped. Therefore, (because we
1229
      // don't track whether we skipped an expression when unwinding after an
1230
      // evaluation failure) every evaluation failure that bubbles up from a
1231
      // subexpression implies that a side-effect has potentially happened. We
1232
      // skip setting the HasSideEffects flag to true until we decide to
1233
      // continue evaluating after that point, which happens here.
1234
4.07M
      bool KeepGoing = keepEvaluatingAfterFailure();
1235
4.07M
      EvalStatus.HasSideEffects |= KeepGoing;
1236
4.07M
      return KeepGoing;
1237
4.07M
    }
1238
1239
    class ArrayInitLoopIndex {
1240
      EvalInfo &Info;
1241
      uint64_t OuterIndex;
1242
1243
    public:
1244
      ArrayInitLoopIndex(EvalInfo &Info)
1245
9
          : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1246
9
        Info.ArrayInitIndex = 0;
1247
9
      }
1248
9
      ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1249
1250
153
      operator uint64_t&() { return Info.ArrayInitIndex; }
1251
    };
1252
  };
1253
1254
  /// Object used to treat all foldable expressions as constant expressions.
1255
  struct FoldConstant {
1256
    EvalInfo &Info;
1257
    bool Enabled;
1258
    bool HadNoPriorDiags;
1259
    EvalInfo::EvaluationMode OldMode;
1260
1261
    explicit FoldConstant(EvalInfo &Info, bool Enabled)
1262
      : Info(Info),
1263
        Enabled(Enabled),
1264
        HadNoPriorDiags(Info.EvalStatus.Diag &&
1265
                        Info.EvalStatus.Diag->empty() &&
1266
                        !Info.EvalStatus.HasSideEffects),
1267
250k
        OldMode(Info.EvalMode) {
1268
250k
      if (Enabled)
1269
5.15k
        Info.EvalMode = EvalInfo::EM_ConstantFold;
1270
250k
    }
1271
157k
    void keepDiagnostics() { Enabled = false; }
1272
250k
    ~FoldConstant() {
1273
250k
      if (Enabled && 
HadNoPriorDiags2.20k
&&
!Info.EvalStatus.Diag->empty()67
&&
1274
250k
          
!Info.EvalStatus.HasSideEffects67
)
1275
67
        Info.EvalStatus.Diag->clear();
1276
250k
      Info.EvalMode = OldMode;
1277
250k
    }
1278
  };
1279
1280
  /// RAII object used to set the current evaluation mode to ignore
1281
  /// side-effects.
1282
  struct IgnoreSideEffectsRAII {
1283
    EvalInfo &Info;
1284
    EvalInfo::EvaluationMode OldMode;
1285
    explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1286
5.12k
        : Info(Info), OldMode(Info.EvalMode) {
1287
5.12k
      Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1288
5.12k
    }
1289
1290
5.12k
    ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1291
  };
1292
1293
  /// RAII object used to optionally suppress diagnostics and side-effects from
1294
  /// a speculative evaluation.
1295
  class SpeculativeEvaluationRAII {
1296
    EvalInfo *Info = nullptr;
1297
    Expr::EvalStatus OldStatus;
1298
    unsigned OldSpeculativeEvaluationDepth;
1299
1300
91.4k
    void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1301
91.4k
      Info = Other.Info;
1302
91.4k
      OldStatus = Other.OldStatus;
1303
91.4k
      OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1304
91.4k
      Other.Info = nullptr;
1305
91.4k
    }
1306
1307
15.2M
    void maybeRestoreState() {
1308
15.2M
      if (!Info)
1309
15.1M
        return;
1310
1311
69.9k
      Info->EvalStatus = OldStatus;
1312
69.9k
      Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1313
69.9k
    }
1314
1315
  public:
1316
15.1M
    SpeculativeEvaluationRAII() = default;
1317
1318
    SpeculativeEvaluationRAII(
1319
        EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1320
        : Info(&Info), OldStatus(Info.EvalStatus),
1321
69.9k
          OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1322
69.9k
      Info.EvalStatus.Diag = NewDiag;
1323
69.9k
      Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1324
69.9k
    }
1325
1326
    SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1327
33.8k
    SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1328
33.8k
      moveFromAndCancel(std::move(Other));
1329
33.8k
    }
1330
1331
57.6k
    SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1332
57.6k
      maybeRestoreState();
1333
57.6k
      moveFromAndCancel(std::move(Other));
1334
57.6k
      return *this;
1335
57.6k
    }
1336
1337
15.2M
    ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1338
  };
1339
1340
  /// RAII object wrapping a full-expression or block scope, and handling
1341
  /// the ending of the lifetime of temporaries created within it.
1342
  template<ScopeKind Kind>
1343
  class ScopeRAII {
1344
    EvalInfo &Info;
1345
    unsigned OldStackSize;
1346
  public:
1347
    ScopeRAII(EvalInfo &Info)
1348
7.52M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349
      // Push a new temporary version. This is needed to distinguish between
1350
      // temporaries created in different iterations of a loop.
1351
7.52M
      Info.CurrentCall->pushTempVersion();
1352
7.52M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1348
692k
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349
      // Push a new temporary version. This is needed to distinguish between
1350
      // temporaries created in different iterations of a loop.
1351
692k
      Info.CurrentCall->pushTempVersion();
1352
692k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1348
5.51M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349
      // Push a new temporary version. This is needed to distinguish between
1350
      // temporaries created in different iterations of a loop.
1351
5.51M
      Info.CurrentCall->pushTempVersion();
1352
5.51M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1348
1.31M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349
      // Push a new temporary version. This is needed to distinguish between
1350
      // temporaries created in different iterations of a loop.
1351
1.31M
      Info.CurrentCall->pushTempVersion();
1352
1.31M
    }
1353
7.52M
    bool destroy(bool RunDestructors = true) {
1354
7.52M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355
7.52M
      OldStackSize = -1U;
1356
7.52M
      return OK;
1357
7.52M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::destroy(bool)
Line
Count
Source
1353
5.51M
    bool destroy(bool RunDestructors = true) {
1354
5.51M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355
5.51M
      OldStackSize = -1U;
1356
5.51M
      return OK;
1357
5.51M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::destroy(bool)
Line
Count
Source
1353
692k
    bool destroy(bool RunDestructors = true) {
1354
692k
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355
692k
      OldStackSize = -1U;
1356
692k
      return OK;
1357
692k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::destroy(bool)
Line
Count
Source
1353
1.31M
    bool destroy(bool RunDestructors = true) {
1354
1.31M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355
1.31M
      OldStackSize = -1U;
1356
1.31M
      return OK;
1357
1.31M
    }
1358
7.52M
    ~ScopeRAII() {
1359
7.52M
      if (OldStackSize != -1U)
1360
754k
        destroy(false);
1361
      // Body moved to a static method to encourage the compiler to inline away
1362
      // instances of this class.
1363
7.52M
      Info.CurrentCall->popTempVersion();
1364
7.52M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::~ScopeRAII()
Line
Count
Source
1358
5.51M
    ~ScopeRAII() {
1359
5.51M
      if (OldStackSize != -1U)
1360
54.3k
        destroy(false);
1361
      // Body moved to a static method to encourage the compiler to inline away
1362
      // instances of this class.
1363
5.51M
      Info.CurrentCall->popTempVersion();
1364
5.51M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::~ScopeRAII()
Line
Count
Source
1358
692k
    ~ScopeRAII() {
1359
692k
      if (OldStackSize != -1U)
1360
616k
        destroy(false);
1361
      // Body moved to a static method to encourage the compiler to inline away
1362
      // instances of this class.
1363
692k
      Info.CurrentCall->popTempVersion();
1364
692k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::~ScopeRAII()
Line
Count
Source
1358
1.31M
    ~ScopeRAII() {
1359
1.31M
      if (OldStackSize != -1U)
1360
83.7k
        destroy(false);
1361
      // Body moved to a static method to encourage the compiler to inline away
1362
      // instances of this class.
1363
1.31M
      Info.CurrentCall->popTempVersion();
1364
1.31M
    }
1365
  private:
1366
    static bool cleanup(EvalInfo &Info, bool RunDestructors,
1367
7.52M
                        unsigned OldStackSize) {
1368
7.52M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1369
7.52M
             "running cleanups out of order?");
1370
1371
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372
      // for a full-expression scope.
1373
0
      bool Success = true;
1374
8.05M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I536k
) {
1375
536k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376
490k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377
272
            Success = false;
1378
272
            break;
1379
272
          }
1380
490k
        }
1381
536k
      }
1382
1383
      // Compact any retained cleanups.
1384
7.52M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385
7.52M
      if (Kind != ScopeKind::Block)
1386
2.01M
        NewEnd =
1387
2.01M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
526k
              return C.isDestroyedAtEndOf(Kind);
1389
526k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1387
498k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
498k
              return C.isDestroyedAtEndOf(Kind);
1389
498k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1387
27.8k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
27.8k
              return C.isDestroyedAtEndOf(Kind);
1389
27.8k
            });
1390
7.52M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391
7.52M
      return Success;
1392
7.52M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1367
5.51M
                        unsigned OldStackSize) {
1368
5.51M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1369
5.51M
             "running cleanups out of order?");
1370
1371
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372
      // for a full-expression scope.
1373
0
      bool Success = true;
1374
5.52M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I9.78k
) {
1375
9.92k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376
9.92k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377
140
            Success = false;
1378
140
            break;
1379
140
          }
1380
9.92k
        }
1381
9.92k
      }
1382
1383
      // Compact any retained cleanups.
1384
5.51M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385
5.51M
      if (Kind != ScopeKind::Block)
1386
0
        NewEnd =
1387
0
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
0
              return C.isDestroyedAtEndOf(Kind);
1389
0
            });
1390
5.51M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391
5.51M
      return Success;
1392
5.51M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1367
692k
                        unsigned OldStackSize) {
1368
692k
      assert(OldStackSize <= Info.CleanupStack.size() &&
1369
692k
             "running cleanups out of order?");
1370
1371
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372
      // for a full-expression scope.
1373
0
      bool Success = true;
1374
1.19M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I498k
) {
1375
498k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376
463k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377
108
            Success = false;
1378
108
            break;
1379
108
          }
1380
463k
        }
1381
498k
      }
1382
1383
      // Compact any retained cleanups.
1384
692k
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385
692k
      if (Kind != ScopeKind::Block)
1386
692k
        NewEnd =
1387
692k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
692k
              return C.isDestroyedAtEndOf(Kind);
1389
692k
            });
1390
692k
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391
692k
      return Success;
1392
692k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1367
1.31M
                        unsigned OldStackSize) {
1368
1.31M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1369
1.31M
             "running cleanups out of order?");
1370
1371
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372
      // for a full-expression scope.
1373
0
      bool Success = true;
1374
1.34M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I27.8k
) {
1375
27.8k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376
16.3k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377
24
            Success = false;
1378
24
            break;
1379
24
          }
1380
16.3k
        }
1381
27.8k
      }
1382
1383
      // Compact any retained cleanups.
1384
1.31M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385
1.31M
      if (Kind != ScopeKind::Block)
1386
1.31M
        NewEnd =
1387
1.31M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388
1.31M
              return C.isDestroyedAtEndOf(Kind);
1389
1.31M
            });
1390
1.31M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391
1.31M
      return Success;
1392
1.31M
    }
1393
  };
1394
  typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1395
  typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1396
  typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1397
}
1398
1399
bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1400
260k
                                         CheckSubobjectKind CSK) {
1401
260k
  if (Invalid)
1402
23
    return false;
1403
260k
  if (isOnePastTheEnd()) {
1404
32
    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1405
32
      << CSK;
1406
32
    setInvalid();
1407
32
    return false;
1408
32
  }
1409
  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1410
  // must actually be at least one array element; even a VLA cannot have a
1411
  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1412
260k
  return true;
1413
260k
}
1414
1415
void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1416
580
                                                                const Expr *E) {
1417
580
  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1418
  // Do not set the designator as invalid: we can represent this situation,
1419
  // and correct handling of __builtin_object_size requires us to do so.
1420
580
}
1421
1422
void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1423
                                                    const Expr *E,
1424
415
                                                    const APSInt &N) {
1425
  // If we're complaining, we must be able to statically determine the size of
1426
  // the most derived array.
1427
415
  if (MostDerivedPathLength == Entries.size() && 
MostDerivedIsArrayElement403
)
1428
288
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1429
288
      << N << /*array*/ 0
1430
288
      << static_cast<unsigned>(getMostDerivedArraySize());
1431
127
  else
1432
127
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1433
127
      << N << /*non-array*/ 1;
1434
415
  setInvalid();
1435
415
}
1436
1437
CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1438
                               const FunctionDecl *Callee, const LValue *This,
1439
                               CallRef Call)
1440
    : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1441
19.7M
      Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1442
19.7M
  Info.CurrentCall = this;
1443
19.7M
  ++Info.CallStackDepth;
1444
19.7M
}
1445
1446
19.7M
CallStackFrame::~CallStackFrame() {
1447
19.7M
  assert(Info.CurrentCall == this && "calls retired out of order");
1448
0
  --Info.CallStackDepth;
1449
19.7M
  Info.CurrentCall = Caller;
1450
19.7M
}
1451
1452
13.9M
static bool isRead(AccessKinds AK) {
1453
13.9M
  return AK == AK_Read || 
AK == AK_ReadObjectRepresentation274k
;
1454
13.9M
}
1455
1456
8.50M
static bool isModification(AccessKinds AK) {
1457
8.50M
  switch (AK) {
1458
8.04M
  case AK_Read:
1459
8.04M
  case AK_ReadObjectRepresentation:
1460
8.20M
  case AK_MemberCall:
1461
8.20M
  case AK_DynamicCast:
1462
8.20M
  case AK_TypeId:
1463
8.20M
    return false;
1464
158k
  case AK_Assign:
1465
296k
  case AK_Increment:
1466
298k
  case AK_Decrement:
1467
298k
  case AK_Construct:
1468
299k
  case AK_Destroy:
1469
299k
    return true;
1470
8.50M
  }
1471
0
  llvm_unreachable("unknown access kind");
1472
0
}
1473
1474
13.8M
static bool isAnyAccess(AccessKinds AK) {
1475
13.8M
  return isRead(AK) || 
isModification(AK)272k
;
1476
13.8M
}
1477
1478
/// Is this an access per the C++ definition?
1479
6.93M
static bool isFormalAccess(AccessKinds AK) {
1480
6.93M
  return isAnyAccess(AK) && 
AK != AK_Construct6.89M
&&
AK != AK_Destroy6.89M
;
1481
6.93M
}
1482
1483
/// Is this kind of axcess valid on an indeterminate object value?
1484
672
static bool isValidIndeterminateAccess(AccessKinds AK) {
1485
672
  switch (AK) {
1486
63
  case AK_Read:
1487
63
  case AK_Increment:
1488
63
  case AK_Decrement:
1489
    // These need the object's value.
1490
63
    return false;
1491
1492
0
  case AK_ReadObjectRepresentation:
1493
598
  case AK_Assign:
1494
607
  case AK_Construct:
1495
609
  case AK_Destroy:
1496
    // Construction and destruction don't need the value.
1497
609
    return true;
1498
1499
0
  case AK_MemberCall:
1500
0
  case AK_DynamicCast:
1501
0
  case AK_TypeId:
1502
    // These aren't really meaningful on scalars.
1503
0
    return true;
1504
672
  }
1505
0
  llvm_unreachable("unknown access kind");
1506
0
}
1507
1508
namespace {
1509
  struct ComplexValue {
1510
  private:
1511
    bool IsInt;
1512
1513
  public:
1514
    APSInt IntReal, IntImag;
1515
    APFloat FloatReal, FloatImag;
1516
1517
4.50k
    ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1518
1519
991
    void makeComplexFloat() { IsInt = false; }
1520
1.10k
    bool isComplexFloat() const { return !IsInt; }
1521
1.23k
    APFloat &getComplexFloatReal() { return FloatReal; }
1522
1.28k
    APFloat &getComplexFloatImag() { return FloatImag; }
1523
1524
342
    void makeComplexInt() { IsInt = true; }
1525
2
    bool isComplexInt() const { return IsInt; }
1526
377
    APSInt &getComplexIntReal() { return IntReal; }
1527
369
    APSInt &getComplexIntImag() { return IntImag; }
1528
1529
394
    void moveInto(APValue &v) const {
1530
394
      if (isComplexFloat())
1531
251
        v = APValue(FloatReal, FloatImag);
1532
143
      else
1533
143
        v = APValue(IntReal, IntImag);
1534
394
    }
1535
35
    void setFrom(const APValue &v) {
1536
35
      assert(v.isComplexFloat() || v.isComplexInt());
1537
35
      if (v.isComplexFloat()) {
1538
15
        makeComplexFloat();
1539
15
        FloatReal = v.getComplexFloatReal();
1540
15
        FloatImag = v.getComplexFloatImag();
1541
20
      } else {
1542
20
        makeComplexInt();
1543
20
        IntReal = v.getComplexIntReal();
1544
20
        IntImag = v.getComplexIntImag();
1545
20
      }
1546
35
    }
1547
  };
1548
1549
  struct LValue {
1550
    APValue::LValueBase Base;
1551
    CharUnits Offset;
1552
    SubobjectDesignator Designator;
1553
    bool IsNullPtr : 1;
1554
    bool InvalidBase : 1;
1555
1556
2.17M
    const APValue::LValueBase getLValueBase() const { return Base; }
1557
372k
    CharUnits &getLValueOffset() { return Offset; }
1558
337
    const CharUnits &getLValueOffset() const { return Offset; }
1559
8.47k
    SubobjectDesignator &getLValueDesignator() { return Designator; }
1560
92.9k
    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1561
286
    bool isNullPointer() const { return IsNullPtr;}
1562
1563
7.35M
    unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1564
3.49M
    unsigned getLValueVersion() const { return Base.getVersion(); }
1565
1566
1.32M
    void moveInto(APValue &V) const {
1567
1.32M
      if (Designator.Invalid)
1568
6.15k
        V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1569
1.31M
      else {
1570
1.31M
        assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1571
0
        V = APValue(Base, Offset, Designator.Entries,
1572
1.31M
                    Designator.IsOnePastTheEnd, IsNullPtr);
1573
1.31M
      }
1574
1.32M
    }
1575
803k
    void setFrom(ASTContext &Ctx, const APValue &V) {
1576
803k
      assert(V.isLValue() && "Setting LValue from a non-LValue?");
1577
0
      Base = V.getLValueBase();
1578
803k
      Offset = V.getLValueOffset();
1579
803k
      InvalidBase = false;
1580
803k
      Designator = SubobjectDesignator(Ctx, V);
1581
803k
      IsNullPtr = V.isNullPointer();
1582
803k
    }
1583
1584
11.6M
    void set(APValue::LValueBase B, bool BInvalid = false) {
1585
11.6M
#ifndef NDEBUG
1586
      // We only allow a few types of invalid bases. Enforce that here.
1587
11.6M
      if (BInvalid) {
1588
1.50k
        const auto *E = B.get<const Expr *>();
1589
1.50k
        assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590
1.50k
               "Unexpected type of invalid base");
1591
1.50k
      }
1592
0
#endif
1593
1594
0
      Base = B;
1595
11.6M
      Offset = CharUnits::fromQuantity(0);
1596
11.6M
      InvalidBase = BInvalid;
1597
11.6M
      Designator = SubobjectDesignator(getType(B));
1598
11.6M
      IsNullPtr = false;
1599
11.6M
    }
1600
1601
54.4k
    void setNull(ASTContext &Ctx, QualType PointerTy) {
1602
54.4k
      Base = (const ValueDecl *)nullptr;
1603
54.4k
      Offset =
1604
54.4k
          CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1605
54.4k
      InvalidBase = false;
1606
54.4k
      Designator = SubobjectDesignator(PointerTy->getPointeeType());
1607
54.4k
      IsNullPtr = true;
1608
54.4k
    }
1609
1610
1.50k
    void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1611
1.50k
      set(B, true);
1612
1.50k
    }
1613
1614
14
    std::string toString(ASTContext &Ctx, QualType T) const {
1615
14
      APValue Printable;
1616
14
      moveInto(Printable);
1617
14
      return Printable.getAsString(Ctx, T);
1618
14
    }
1619
1620
  private:
1621
    // Check that this LValue is not based on a null pointer. If it is, produce
1622
    // a diagnostic and mark the designator as invalid.
1623
    template <typename GenDiagType>
1624
294k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625
294k
      if (Designator.Invalid)
1626
274
        return false;
1627
294k
      if (IsNullPtr) {
1628
738
        GenDiag();
1629
738
        Designator.setInvalid();
1630
738
        return false;
1631
738
      }
1632
293k
      return true;
1633
294k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'()>((anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'() const&)
Line
Count
Source
1624
288k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625
288k
      if (Designator.Invalid)
1626
274
        return false;
1627
288k
      if (IsNullPtr) {
1628
594
        GenDiag();
1629
594
        Designator.setInvalid();
1630
594
        return false;
1631
594
      }
1632
287k
      return true;
1633
288k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'()>((anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'() const&)
Line
Count
Source
1624
6.20k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625
6.20k
      if (Designator.Invalid)
1626
0
        return false;
1627
6.20k
      if (IsNullPtr) {
1628
144
        GenDiag();
1629
144
        Designator.setInvalid();
1630
144
        return false;
1631
144
      }
1632
6.06k
      return true;
1633
6.20k
    }
1634
1635
  public:
1636
    bool checkNullPointer(EvalInfo &Info, const Expr *E,
1637
288k
                          CheckSubobjectKind CSK) {
1638
288k
      return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1639
594
        Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1640
594
      });
1641
288k
    }
1642
1643
    bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1644
6.20k
                                       AccessKinds AK) {
1645
6.20k
      return checkNullPointerDiagnosingWith([&Info, E, AK] {
1646
144
        Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1647
144
      });
1648
6.20k
    }
1649
1650
    // Check this LValue refers to an object. If not, set the designator to be
1651
    // invalid and emit a diagnostic.
1652
260k
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1653
260k
      return (CSK == CSK_ArrayToPointer || 
checkNullPointer(Info, E, CSK)170k
) &&
1654
260k
             
Designator.checkSubobject(Info, E, CSK)260k
;
1655
260k
    }
1656
1657
    void addDecl(EvalInfo &Info, const Expr *E,
1658
169k
                 const Decl *D, bool Virtual = false) {
1659
169k
      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? 
CSK_Field157k
:
CSK_Base12.1k
))
1660
169k
        Designator.addDeclUnchecked(D, Virtual);
1661
169k
    }
1662
4.67k
    void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1663
4.67k
      if (!Designator.Entries.empty()) {
1664
24
        Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1665
24
        Designator.setInvalid();
1666
24
        return;
1667
24
      }
1668
4.65k
      if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1669
4.65k
        assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1670
0
        Designator.FirstEntryIsAnUnsizedArray = true;
1671
4.65k
        Designator.addUnsizedArrayUnchecked(ElemTy);
1672
4.65k
      }
1673
4.65k
    }
1674
85.4k
    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1675
85.4k
      if (checkSubobject(Info, E, CSK_ArrayToPointer))
1676
85.3k
        Designator.addArrayUnchecked(CAT);
1677
85.4k
    }
1678
473
    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1679
473
      if (checkSubobject(Info, E, Imag ? 
CSK_Imag224
:
CSK_Real249
))
1680
461
        Designator.addComplexUnchecked(EltTy, Imag);
1681
473
    }
1682
170k
    void clearIsNullPointer() {
1683
170k
      IsNullPtr = false;
1684
170k
    }
1685
    void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1686
128k
                              const APSInt &Index, CharUnits ElementSize) {
1687
      // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1688
      // but we're not required to diagnose it and it's valid in C++.)
1689
128k
      if (!Index)
1690
10.7k
        return;
1691
1692
      // Compute the new offset in the appropriate width, wrapping at 64 bits.
1693
      // FIXME: When compiling for a 32-bit target, we should use 32-bit
1694
      // offsets.
1695
117k
      uint64_t Offset64 = Offset.getQuantity();
1696
117k
      uint64_t ElemSize64 = ElementSize.getQuantity();
1697
117k
      uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1698
117k
      Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1699
1700
117k
      if (checkNullPointer(Info, E, CSK_ArrayIndex))
1701
117k
        Designator.adjustIndex(Info, E, Index);
1702
117k
      clearIsNullPointer();
1703
117k
    }
1704
157k
    void adjustOffset(CharUnits N) {
1705
157k
      Offset += N;
1706
157k
      if (N.getQuantity())
1707
53.2k
        clearIsNullPointer();
1708
157k
    }
1709
  };
1710
1711
  struct MemberPtr {
1712
2.98k
    MemberPtr() {}
1713
    explicit MemberPtr(const ValueDecl *Decl) :
1714
1.92k
      DeclAndIsDerivedMember(Decl, false), Path() {}
1715
1716
    /// The member or (direct or indirect) field referred to by this member
1717
    /// pointer, or 0 if this is a null member pointer.
1718
3.77k
    const ValueDecl *getDecl() const {
1719
3.77k
      return DeclAndIsDerivedMember.getPointer();
1720
3.77k
    }
1721
    /// Is this actually a member of some type derived from the relevant class?
1722
2.77k
    bool isDerivedMember() const {
1723
2.77k
      return DeclAndIsDerivedMember.getInt();
1724
2.77k
    }
1725
    /// Get the class which the declaration actually lives in.
1726
116
    const CXXRecordDecl *getContainingRecord() const {
1727
116
      return cast<CXXRecordDecl>(
1728
116
          DeclAndIsDerivedMember.getPointer()->getDeclContext());
1729
116
    }
1730
1731
1.63k
    void moveInto(APValue &V) const {
1732
1.63k
      V = APValue(getDecl(), isDerivedMember(), Path);
1733
1.63k
    }
1734
234
    void setFrom(const APValue &V) {
1735
234
      assert(V.isMemberPointer());
1736
0
      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1737
234
      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1738
234
      Path.clear();
1739
234
      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1740
234
      Path.insert(Path.end(), P.begin(), P.end());
1741
234
    }
1742
1743
    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1744
    /// whether the member is a member of some class derived from the class type
1745
    /// of the member pointer.
1746
    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1747
    /// Path - The path of base/derived classes from the member declaration's
1748
    /// class (exclusive) to the class type of the member pointer (inclusive).
1749
    SmallVector<const CXXRecordDecl*, 4> Path;
1750
1751
    /// Perform a cast towards the class of the Decl (either up or down the
1752
    /// hierarchy).
1753
144
    bool castBack(const CXXRecordDecl *Class) {
1754
144
      assert(!Path.empty());
1755
0
      const CXXRecordDecl *Expected;
1756
144
      if (Path.size() >= 2)
1757
141
        Expected = Path[Path.size() - 2];
1758
3
      else
1759
3
        Expected = getContainingRecord();
1760
144
      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1761
        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1762
        // if B does not contain the original member and is not a base or
1763
        // derived class of the class containing the original member, the result
1764
        // of the cast is undefined.
1765
        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1766
        // (D::*). We consider that to be a language defect.
1767
0
        return false;
1768
0
      }
1769
144
      Path.pop_back();
1770
144
      return true;
1771
144
    }
1772
    /// Perform a base-to-derived member pointer cast.
1773
498
    bool castToDerived(const CXXRecordDecl *Derived) {
1774
498
      if (!getDecl())
1775
0
        return true;
1776
498
      if (!isDerivedMember()) {
1777
438
        Path.push_back(Derived);
1778
438
        return true;
1779
438
      }
1780
60
      if (!castBack(Derived))
1781
0
        return false;
1782
60
      if (Path.empty())
1783
3
        DeclAndIsDerivedMember.setInt(false);
1784
60
      return true;
1785
60
    }
1786
    /// Perform a derived-to-base member pointer cast.
1787
343
    bool castToBase(const CXXRecordDecl *Base) {
1788
343
      if (!getDecl())
1789
0
        return true;
1790
343
      if (Path.empty())
1791
82
        DeclAndIsDerivedMember.setInt(true);
1792
343
      if (isDerivedMember()) {
1793
259
        Path.push_back(Base);
1794
259
        return true;
1795
259
      }
1796
84
      return castBack(Base);
1797
343
    }
1798
  };
1799
1800
  /// Compare two member pointers, which are assumed to be of the same type.
1801
57
  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1802
57
    if (!LHS.getDecl() || !RHS.getDecl())
1803
0
      return !LHS.getDecl() && !RHS.getDecl();
1804
57
    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1805
12
      return false;
1806
45
    return LHS.Path == RHS.Path;
1807
57
  }
1808
}
1809
1810
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1811
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1812
                            const LValue &This, const Expr *E,
1813
                            bool AllowNonLiteralTypes = false);
1814
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1815
                           bool InvalidBaseOK = false);
1816
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1817
                            bool InvalidBaseOK = false);
1818
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1819
                                  EvalInfo &Info);
1820
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1821
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1822
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1823
                                    EvalInfo &Info);
1824
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1825
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1826
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1827
                           EvalInfo &Info);
1828
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1829
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1830
                                  EvalInfo &Info);
1831
1832
/// Evaluate an integer or fixed point expression into an APResult.
1833
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1834
                                        EvalInfo &Info);
1835
1836
/// Evaluate only a fixed point expression into an APResult.
1837
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1838
                               EvalInfo &Info);
1839
1840
//===----------------------------------------------------------------------===//
1841
// Misc utilities
1842
//===----------------------------------------------------------------------===//
1843
1844
/// Negate an APSInt in place, converting it to a signed form if necessary, and
1845
/// preserving its value (by extending by up to one bit as needed).
1846
262
static void negateAsSigned(APSInt &Int) {
1847
262
  if (Int.isUnsigned() || 
Int.isMinSignedValue()252
) {
1848
10
    Int = Int.extend(Int.getBitWidth() + 1);
1849
10
    Int.setIsSigned(true);
1850
10
  }
1851
262
  Int = -Int;
1852
262
}
1853
1854
template<typename KeyT>
1855
APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1856
48.8k
                                         ScopeKind Scope, LValue &LV) {
1857
48.8k
  unsigned Version = getTempVersion();
1858
48.8k
  APValue::LValueBase Base(Key, Index, Version);
1859
48.8k
  LV.set(Base);
1860
48.8k
  return createLocal(Base, Key, T, Scope);
1861
48.8k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::OpaqueValueExpr>(clang::OpaqueValueExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1856
1.46k
                                         ScopeKind Scope, LValue &LV) {
1857
1.46k
  unsigned Version = getTempVersion();
1858
1.46k
  APValue::LValueBase Base(Key, Index, Version);
1859
1.46k
  LV.set(Base);
1860
1.46k
  return createLocal(Base, Key, T, Scope);
1861
1.46k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::VarDecl>(clang::VarDecl const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1856
9.89k
                                         ScopeKind Scope, LValue &LV) {
1857
9.89k
  unsigned Version = getTempVersion();
1858
9.89k
  APValue::LValueBase Base(Key, Index, Version);
1859
9.89k
  LV.set(Base);
1860
9.89k
  return createLocal(Base, Key, T, Scope);
1861
9.89k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::Expr>(clang::Expr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1856
6.32k
                                         ScopeKind Scope, LValue &LV) {
1857
6.32k
  unsigned Version = getTempVersion();
1858
6.32k
  APValue::LValueBase Base(Key, Index, Version);
1859
6.32k
  LV.set(Base);
1860
6.32k
  return createLocal(Base, Key, T, Scope);
1861
6.32k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::MaterializeTemporaryExpr>(clang::MaterializeTemporaryExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1856
31.1k
                                         ScopeKind Scope, LValue &LV) {
1857
31.1k
  unsigned Version = getTempVersion();
1858
31.1k
  APValue::LValueBase Base(Key, Index, Version);
1859
31.1k
  LV.set(Base);
1860
31.1k
  return createLocal(Base, Key, T, Scope);
1861
31.1k
}
1862
1863
/// Allocate storage for a parameter of a function call made in this frame.
1864
APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1865
472k
                                     LValue &LV) {
1866
472k
  assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1867
0
  APValue::LValueBase Base(PVD, Index, Args.Version);
1868
472k
  LV.set(Base);
1869
  // We always destroy parameters at the end of the call, even if we'd allow
1870
  // them to live to the end of the full-expression at runtime, in order to
1871
  // give portable results and match other compilers.
1872
472k
  return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1873
472k
}
1874
1875
APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1876
521k
                                     QualType T, ScopeKind Scope) {
1877
521k
  assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1878
0
  unsigned Version = Base.getVersion();
1879
521k
  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1880
521k
  assert(Result.isAbsent() && "local created multiple times");
1881
1882
  // If we're creating a local immediately in the operand of a speculative
1883
  // evaluation, don't register a cleanup to be run outside the speculative
1884
  // evaluation context, since we won't actually be able to initialize this
1885
  // object.
1886
521k
  if (Index <= Info.SpeculativeEvaluationDepth) {
1887
6.72k
    if (T.isDestructedType())
1888
524
      Info.noteSideEffect();
1889
514k
  } else {
1890
514k
    Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1891
514k
  }
1892
521k
  return Result;
1893
521k
}
1894
1895
843
APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1896
843
  if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1897
0
    FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1898
0
    return nullptr;
1899
0
  }
1900
1901
843
  DynamicAllocLValue DA(NumHeapAllocs++);
1902
843
  LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1903
843
  auto Result = HeapAllocs.emplace(std::piecewise_construct,
1904
843
                                   std::forward_as_tuple(DA), std::tuple<>());
1905
843
  assert(Result.second && "reused a heap alloc index?");
1906
0
  Result.first->second.AllocExpr = E;
1907
843
  return &Result.first->second.Value;
1908
843
}
1909
1910
/// Produce a string describing the given constexpr call.
1911
2.10k
void CallStackFrame::describe(raw_ostream &Out) {
1912
2.10k
  unsigned ArgIndex = 0;
1913
2.10k
  bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1914
2.10k
                      
!isa<CXXConstructorDecl>(Callee)1.25k
&&
1915
2.10k
                      
cast<CXXMethodDecl>(Callee)->isInstance()804
;
1916
1917
2.10k
  if (!IsMemberCall)
1918
1.29k
    Out << *Callee << '(';
1919
1920
2.10k
  if (This && 
IsMemberCall1.25k
) {
1921
804
    APValue Val;
1922
804
    This->moveInto(Val);
1923
804
    Val.printPretty(Out, Info.Ctx,
1924
804
                    This->Designator.MostDerivedType);
1925
    // FIXME: Add parens around Val if needed.
1926
804
    Out << "->" << *Callee << '(';
1927
804
    IsMemberCall = false;
1928
804
  }
1929
1930
2.10k
  for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1931
3.93k
       E = Callee->param_end(); I != E; 
++I, ++ArgIndex1.83k
) {
1932
1.83k
    if (ArgIndex > (unsigned)IsMemberCall)
1933
654
      Out << ", ";
1934
1935
1.83k
    const ParmVarDecl *Param = *I;
1936
1.83k
    APValue *V = Info.getParamSlot(Arguments, Param);
1937
1.83k
    if (V)
1938
1.83k
      V->printPretty(Out, Info.Ctx, Param->getType());
1939
0
    else
1940
0
      Out << "<...>";
1941
1942
1.83k
    if (ArgIndex == 0 && 
IsMemberCall1.18k
)
1943
0
      Out << "->" << *Callee << '(';
1944
1.83k
  }
1945
1946
2.10k
  Out << ')';
1947
2.10k
}
1948
1949
/// Evaluate an expression to see if it had side-effects, and discard its
1950
/// result.
1951
/// \return \c true if the caller should keep evaluating.
1952
87.8k
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1953
87.8k
  assert(!E->isValueDependent());
1954
0
  APValue Scratch;
1955
87.8k
  if (!Evaluate(Scratch, Info, E))
1956
    // We don't need the value, but we might have skipped a side effect here.
1957
8.73k
    return Info.noteSideEffect();
1958
79.0k
  return true;
1959
87.8k
}
1960
1961
/// Should this call expression be treated as a string literal?
1962
30.5k
static bool IsStringLiteralCall(const CallExpr *E) {
1963
30.5k
  unsigned Builtin = E->getBuiltinCallee();
1964
30.5k
  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1965
30.5k
          
Builtin == Builtin::BI__builtin___NSStringMakeConstantString29.1k
);
1966
30.5k
}
1967
1968
92.3k
static bool IsGlobalLValue(APValue::LValueBase B) {
1969
  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970
  // constant expression of pointer type that evaluates to...
1971
1972
  // ... a null pointer value, or a prvalue core constant expression of type
1973
  // std::nullptr_t.
1974
92.3k
  if (!B) 
return true14.8k
;
1975
1976
77.5k
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977
    // ... the address of an object with static storage duration,
1978
65.2k
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979
53.4k
      return VD->hasGlobalStorage();
1980
11.8k
    if (isa<TemplateParamObjectDecl>(D))
1981
83
      return true;
1982
    // ... the address of a function,
1983
    // ... the address of a GUID [MS extension],
1984
11.7k
    return isa<FunctionDecl>(D) || 
isa<MSGuidDecl>(D)99
;
1985
11.8k
  }
1986
1987
12.3k
  if (B.is<TypeInfoLValue>() || 
B.is<DynamicAllocLValue>()11.2k
)
1988
1.28k
    return true;
1989
1990
11.0k
  const Expr *E = B.get<const Expr*>();
1991
11.0k
  switch (E->getStmtClass()) {
1992
0
  default:
1993
0
    return false;
1994
90
  case Expr::CompoundLiteralExprClass: {
1995
90
    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1996
90
    return CLE->isFileScope() && 
CLE->isLValue()87
;
1997
0
  }
1998
1.05k
  case Expr::MaterializeTemporaryExprClass:
1999
    // A materialized temporary might have been lifetime-extended to static
2000
    // storage duration.
2001
1.05k
    return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2002
  // A string literal has static storage duration.
2003
5.08k
  case Expr::StringLiteralClass:
2004
5.12k
  case Expr::PredefinedExprClass:
2005
8.77k
  case Expr::ObjCStringLiteralClass:
2006
8.85k
  case Expr::ObjCEncodeExprClass:
2007
8.85k
    return true;
2008
9
  case Expr::ObjCBoxedExprClass:
2009
9
    return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2010
682
  case Expr::CallExprClass:
2011
682
    return IsStringLiteralCall(cast<CallExpr>(E));
2012
  // For GCC compatibility, &&label has static storage duration.
2013
104
  case Expr::AddrLabelExprClass:
2014
104
    return true;
2015
  // A Block literal expression may be used as the initialization value for
2016
  // Block variables at global or local static scope.
2017
255
  case Expr::BlockExprClass:
2018
255
    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2019
0
  case Expr::ImplicitValueInitExprClass:
2020
    // FIXME:
2021
    // We can never form an lvalue with an implicit value initialization as its
2022
    // base through expression evaluation, so these only appear in one case: the
2023
    // implicit variable declaration we invent when checking whether a constexpr
2024
    // constructor can produce a constant expression. We must assume that such
2025
    // an expression might be a global lvalue.
2026
0
    return true;
2027
11.0k
  }
2028
11.0k
}
2029
2030
1.67k
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2031
1.67k
  return LVal.Base.dyn_cast<const ValueDecl*>();
2032
1.67k
}
2033
2034
1.16k
static bool IsLiteralLValue(const LValue &Value) {
2035
1.16k
  if (Value.getLValueCallIndex())
2036
15
    return false;
2037
1.14k
  const Expr *E = Value.Base.dyn_cast<const Expr*>();
2038
1.14k
  return E && 
!isa<MaterializeTemporaryExpr>(E)102
;
2039
1.16k
}
2040
2041
1.08k
static bool IsWeakLValue(const LValue &Value) {
2042
1.08k
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2043
1.08k
  return Decl && 
Decl->isWeak()652
;
2044
1.08k
}
2045
2046
590
static bool isZeroSized(const LValue &Value) {
2047
590
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048
590
  if (Decl && 
isa<VarDecl>(Decl)220
) {
2049
166
    QualType Ty = Decl->getType();
2050
166
    if (Ty->isArrayType())
2051
62
      return Ty->isIncompleteType() ||
2052
62
             
Decl->getASTContext().getTypeSize(Ty) == 042
;
2053
166
  }
2054
528
  return false;
2055
590
}
2056
2057
5.56k
static bool HasSameBase(const LValue &A, const LValue &B) {
2058
5.56k
  if (!A.getLValueBase())
2059
885
    return !B.getLValueBase();
2060
4.68k
  if (!B.getLValueBase())
2061
419
    return false;
2062
2063
4.26k
  if (A.getLValueBase().getOpaqueValue() !=
2064
4.26k
      B.getLValueBase().getOpaqueValue())
2065
352
    return false;
2066
2067
3.91k
  return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2068
3.91k
         A.getLValueVersion() == B.getLValueVersion();
2069
4.26k
}
2070
2071
1.24M
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2072
1.24M
  assert(Base && "no location for a null lvalue");
2073
0
  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2074
2075
  // For a parameter, find the corresponding call stack frame (if it still
2076
  // exists), and point at the parameter of the function definition we actually
2077
  // invoked.
2078
1.24M
  if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2079
980k
    unsigned Idx = PVD->getFunctionScopeIndex();
2080
1.97M
    for (CallStackFrame *F = Info.CurrentCall; F; 
F = F->Caller995k
) {
2081
995k
      if (F->Arguments.CallIndex == Base.getCallIndex() &&
2082
995k
          
F->Arguments.Version == Base.getVersion()980k
&&
F->Callee980k
&&
2083
995k
          
Idx < F->Callee->getNumParams()15
) {
2084
12
        VD = F->Callee->getParamDecl(Idx);
2085
12
        break;
2086
12
      }
2087
995k
    }
2088
980k
  }
2089
2090
1.24M
  if (VD)
2091
1.24M
    Info.Note(VD->getLocation(), diag::note_declared_at);
2092
672
  else if (const Expr *E = Base.dyn_cast<const Expr*>())
2093
389
    Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2094
283
  else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2095
    // FIXME: Produce a note for dangling pointers too.
2096
238
    if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2097
238
      Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2098
238
                diag::note_constexpr_dynamic_alloc_here);
2099
238
  }
2100
  // We have no information to show for a typeid(T) object.
2101
1.24M
}
2102
2103
enum class CheckEvaluationResultKind {
2104
  ConstantExpression,
2105
  FullyInitialized,
2106
};
2107
2108
/// Materialized temporaries that we've already checked to determine if they're
2109
/// initializsed by a constant expression.
2110
using CheckedTemporaries =
2111
    llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2112
2113
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2114
                                  EvalInfo &Info, SourceLocation DiagLoc,
2115
                                  QualType Type, const APValue &Value,
2116
                                  ConstantExprKind Kind,
2117
                                  SourceLocation SubobjectLoc,
2118
                                  CheckedTemporaries &CheckedTemps);
2119
2120
/// Check that this reference or pointer core constant expression is a valid
2121
/// value for an address or reference constant expression. Return true if we
2122
/// can fold this expression, whether or not it's a constant expression.
2123
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2124
                                          QualType Type, const LValue &LVal,
2125
                                          ConstantExprKind Kind,
2126
92.4k
                                          CheckedTemporaries &CheckedTemps) {
2127
92.4k
  bool IsReferenceType = Type->isReferenceType();
2128
2129
92.4k
  APValue::LValueBase Base = LVal.getLValueBase();
2130
92.4k
  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2131
2132
92.4k
  const Expr *BaseE = Base.dyn_cast<const Expr *>();
2133
92.4k
  const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2134
2135
  // Additional restrictions apply in a template argument. We only enforce the
2136
  // C++20 restrictions here; additional syntactic and semantic restrictions
2137
  // are applied elsewhere.
2138
92.4k
  if (isTemplateArgument(Kind)) {
2139
726
    int InvalidBaseKind = -1;
2140
726
    StringRef Ident;
2141
726
    if (Base.is<TypeInfoLValue>())
2142
6
      InvalidBaseKind = 0;
2143
720
    else if (isa_and_nonnull<StringLiteral>(BaseE))
2144
12
      InvalidBaseKind = 1;
2145
708
    else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2146
708
             
isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)693
)
2147
15
      InvalidBaseKind = 2;
2148
693
    else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2149
8
      InvalidBaseKind = 3;
2150
8
      Ident = PE->getIdentKindName();
2151
8
    }
2152
2153
726
    if (InvalidBaseKind != -1) {
2154
41
      Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2155
41
          << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2156
41
          << Ident;
2157
41
      return false;
2158
41
    }
2159
726
  }
2160
2161
92.4k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2162
11.7k
    if (FD->isConsteval()) {
2163
95
      Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2164
95
          << !Type->isAnyPointerType();
2165
95
      Info.Note(FD->getLocation(), diag::note_declared_at);
2166
95
      return false;
2167
95
    }
2168
11.7k
  }
2169
2170
  // Check that the object is a global. Note that the fake 'this' object we
2171
  // manufacture when checking potential constant expressions is conservatively
2172
  // assumed to be global here.
2173
92.3k
  if (!IsGlobalLValue(Base)) {
2174
36.8k
    if (Info.getLangOpts().CPlusPlus11) {
2175
34.5k
      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2176
34.5k
      Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2177
34.5k
        << IsReferenceType << !Designator.Entries.empty()
2178
34.5k
        << !!VD << VD;
2179
2180
34.5k
      auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2181
34.5k
      if (VarD && 
VarD->isConstexpr()34.1k
) {
2182
        // Non-static local constexpr variables have unintuitive semantics:
2183
        //   constexpr int a = 1;
2184
        //   constexpr const int *p = &a;
2185
        // ... is invalid because the address of 'a' is not constant. Suggest
2186
        // adding a 'static' in this case.
2187
42
        Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2188
42
            << VarD
2189
42
            << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2190
34.4k
      } else {
2191
34.4k
        NoteLValueLocation(Info, Base);
2192
34.4k
      }
2193
34.5k
    } else {
2194
2.34k
      Info.FFDiag(Loc);
2195
2.34k
    }
2196
    // Don't allow references to temporaries to escape.
2197
36.8k
    return false;
2198
36.8k
  }
2199
55.4k
  assert((Info.checkingPotentialConstantExpression() ||
2200
55.4k
          LVal.getLValueCallIndex() == 0) &&
2201
55.4k
         "have call index for global lvalue");
2202
2203
55.4k
  if (Base.is<DynamicAllocLValue>()) {
2204
219
    Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2205
219
        << IsReferenceType << !Designator.Entries.empty();
2206
219
    NoteLValueLocation(Info, Base);
2207
219
    return false;
2208
219
  }
2209
2210
55.2k
  if (BaseVD) {
2211
28.6k
    if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2212
      // Check if this is a thread-local variable.
2213
16.8k
      if (Var->getTLSKind())
2214
        // FIXME: Diagnostic!
2215
116
        return false;
2216
2217
      // A dllimport variable never acts like a constant, unless we're
2218
      // evaluating a value for use only in name mangling.
2219
16.7k
      if (!isForManglingOnly(Kind) && 
Var->hasAttr<DLLImportAttr>()16.3k
)
2220
        // FIXME: Diagnostic!
2221
74
        return false;
2222
16.7k
    }
2223
28.4k
    if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2224
      // __declspec(dllimport) must be handled very carefully:
2225
      // We must never initialize an expression with the thunk in C++.
2226
      // Doing otherwise would allow the same id-expression to yield
2227
      // different addresses for the same function in different translation
2228
      // units.  However, this means that we must dynamically initialize the
2229
      // expression with the contents of the import address table at runtime.
2230
      //
2231
      // The C language has no notion of ODR; furthermore, it has no notion of
2232
      // dynamic initialization.  This means that we are permitted to
2233
      // perform initialization with the address of the thunk.
2234
11.6k
      if (Info.getLangOpts().CPlusPlus && 
!isForManglingOnly(Kind)9.86k
&&
2235
11.6k
          
FD->hasAttr<DLLImportAttr>()9.75k
)
2236
        // FIXME: Diagnostic!
2237
217
        return false;
2238
11.6k
    }
2239
28.4k
  } else 
if (const auto *26.5k
MTE26.5k
=
2240
26.5k
                 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2241
688
    if (CheckedTemps.insert(MTE).second) {
2242
676
      QualType TempType = getType(Base);
2243
676
      if (TempType.isDestructedType()) {
2244
4
        Info.FFDiag(MTE->getExprLoc(),
2245
4
                    diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2246
4
            << TempType;
2247
4
        return false;
2248
4
      }
2249
2250
672
      APValue *V = MTE->getOrCreateValue(false);
2251
672
      assert(V && "evasluation result refers to uninitialised temporary");
2252
672
      if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2253
672
                                 Info, MTE->getExprLoc(), TempType, *V,
2254
672
                                 Kind, SourceLocation(), CheckedTemps))
2255
11
        return false;
2256
672
    }
2257
688
  }
2258
2259
  // Allow address constant expressions to be past-the-end pointers. This is
2260
  // an extension: the standard requires them to point to an object.
2261
54.8k
  if (!IsReferenceType)
2262
36.5k
    return true;
2263
2264
  // A reference constant expression must refer to an object.
2265
18.2k
  if (!Base) {
2266
    // FIXME: diagnostic
2267
267
    Info.CCEDiag(Loc);
2268
267
    return true;
2269
267
  }
2270
2271
  // Does this refer one past the end of some object?
2272
17.9k
  if (!Designator.Invalid && 
Designator.isOnePastTheEnd()17.9k
) {
2273
59
    Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2274
59
      << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2275
59
    NoteLValueLocation(Info, Base);
2276
59
  }
2277
2278
17.9k
  return true;
2279
18.2k
}
2280
2281
/// Member pointers are constant expressions unless they point to a
2282
/// non-virtual dllimport member function.
2283
static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2284
                                                 SourceLocation Loc,
2285
                                                 QualType Type,
2286
                                                 const APValue &Value,
2287
1.30k
                                                 ConstantExprKind Kind) {
2288
1.30k
  const ValueDecl *Member = Value.getMemberPointerDecl();
2289
1.30k
  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2290
1.30k
  if (!FD)
2291
386
    return true;
2292
921
  if (FD->isConsteval()) {
2293
4
    Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2294
4
    Info.Note(FD->getLocation(), diag::note_declared_at);
2295
4
    return false;
2296
4
  }
2297
917
  return isForManglingOnly(Kind) || 
FD->isVirtual()903
||
2298
917
         
!FD->hasAttr<DLLImportAttr>()780
;
2299
921
}
2300
2301
/// Check that this core constant expression is of literal type, and if not,
2302
/// produce an appropriate diagnostic.
2303
static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2304
13.9M
                             const LValue *This = nullptr) {
2305
13.9M
  if (!E->isPRValue() || 
E->getType()->isLiteralType(Info.Ctx)12.0M
)
2306
13.7M
    return true;
2307
2308
  // C++1y: A constant initializer for an object o [...] may also invoke
2309
  // constexpr constructors for o and its subobjects even if those objects
2310
  // are of non-literal class types.
2311
  //
2312
  // C++11 missed this detail for aggregates, so classes like this:
2313
  //   struct foo_t { union { int i; volatile int j; } u; };
2314
  // are not (obviously) initializable like so:
2315
  //   __attribute__((__require_constant_initialization__))
2316
  //   static const foo_t x = {{0}};
2317
  // because "i" is a subobject with non-literal initialization (due to the
2318
  // volatile member of the union). See:
2319
  //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2320
  // Therefore, we use the C++1y behavior.
2321
185k
  if (This && 
Info.EvaluatingDecl == This->getLValueBase()21.8k
)
2322
2.64k
    return true;
2323
2324
  // Prvalue constant expressions must be of literal types.
2325
182k
  if (Info.getLangOpts().CPlusPlus11)
2326
52.8k
    Info.FFDiag(E, diag::note_constexpr_nonliteral)
2327
52.8k
      << E->getType();
2328
129k
  else
2329
129k
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2330
182k
  return false;
2331
185k
}
2332
2333
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2334
                                  EvalInfo &Info, SourceLocation DiagLoc,
2335
                                  QualType Type, const APValue &Value,
2336
                                  ConstantExprKind Kind,
2337
                                  SourceLocation SubobjectLoc,
2338
10.4M
                                  CheckedTemporaries &CheckedTemps) {
2339
10.4M
  if (!Value.hasValue()) {
2340
1.36k
    Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2341
1.36k
      << true << Type;
2342
1.36k
    if (SubobjectLoc.isValid())
2343
1.36k
      Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2344
1.36k
    return false;
2345
1.36k
  }
2346
2347
  // We allow _Atomic(T) to be initialized from anything that T can be
2348
  // initialized from.
2349
10.4M
  if (const AtomicType *AT = Type->getAs<AtomicType>())
2350
136
    Type = AT->getValueType();
2351
2352
  // Core issue 1454: For a literal constant expression of array or class type,
2353
  // each subobject of its value shall have been initialized by a constant
2354
  // expression.
2355
10.4M
  if (Value.isArray()) {
2356
6.04k
    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2357
84.2k
    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; 
++I78.1k
) {
2358
78.2k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2359
78.2k
                                 Value.getArrayInitializedElt(I), Kind,
2360
78.2k
                                 SubobjectLoc, CheckedTemps))
2361
85
        return false;
2362
78.2k
    }
2363
5.96k
    if (!Value.hasArrayFiller())
2364
3.75k
      return true;
2365
2.20k
    return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2366
2.20k
                                 Value.getArrayFiller(), Kind, SubobjectLoc,
2367
2.20k
                                 CheckedTemps);
2368
5.96k
  }
2369
10.4M
  if (Value.isUnion() && 
Value.getUnionField()1.03k
) {
2370
792
    return CheckEvaluationResult(
2371
792
        CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2372
792
        Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2373
792
        CheckedTemps);
2374
792
  }
2375
10.4M
  if (Value.isStruct()) {
2376
25.4k
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2377
25.4k
    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2378
25.4k
      unsigned BaseIndex = 0;
2379
25.4k
      for (const CXXBaseSpecifier &BS : CD->bases()) {
2380
2.84k
        if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2381
2.84k
                                   Value.getStructBase(BaseIndex), Kind,
2382
2.84k
                                   BS.getBeginLoc(), CheckedTemps))
2383
644
          return false;
2384
2.19k
        ++BaseIndex;
2385
2.19k
      }
2386
25.4k
    }
2387
24.8k
    for (const auto *I : RD->fields()) {
2388
20.2k
      if (I->isUnnamedBitfield())
2389
87
        continue;
2390
2391
20.1k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2392
20.1k
                                 Value.getStructField(I->getFieldIndex()),
2393
20.1k
                                 Kind, I->getLocation(), CheckedTemps))
2394
1.72k
        return false;
2395
20.1k
    }
2396
24.8k
  }
2397
2398
10.4M
  if (Value.isLValue() &&
2399
10.4M
      
CERK == CheckEvaluationResultKind::ConstantExpression121k
) {
2400
92.1k
    LValue LVal;
2401
92.1k
    LVal.setFrom(Info.Ctx, Value);
2402
92.1k
    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2403
92.1k
                                         CheckedTemps);
2404
92.1k
  }
2405
2406
10.3M
  if (Value.isMemberPointer() &&
2407
10.3M
      
CERK == CheckEvaluationResultKind::ConstantExpression1.54k
)
2408
1.30k
    return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2409
2410
  // Everything else is fine.
2411
10.3M
  return true;
2412
10.3M
}
2413
2414
/// Check that this core constant expression value is a valid value for a
2415
/// constant expression. If not, report an appropriate diagnostic. Does not
2416
/// check that the expression is of literal type.
2417
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2418
                                    QualType Type, const APValue &Value,
2419
8.79M
                                    ConstantExprKind Kind) {
2420
  // Nothing to check for a constant expression of type 'cv void'.
2421
8.79M
  if (Type->isVoidType())
2422
171
    return true;
2423
2424
8.79M
  CheckedTemporaries CheckedTemps;
2425
8.79M
  return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2426
8.79M
                               Info, DiagLoc, Type, Value, Kind,
2427
8.79M
                               SourceLocation(), CheckedTemps);
2428
8.79M
}
2429
2430
/// Check that this evaluated value is fully-initialized and can be loaded by
2431
/// an lvalue-to-rvalue conversion.
2432
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2433
1.57M
                                  QualType Type, const APValue &Value) {
2434
1.57M
  CheckedTemporaries CheckedTemps;
2435
1.57M
  return CheckEvaluationResult(
2436
1.57M
      CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2437
1.57M
      ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2438
1.57M
}
2439
2440
/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2441
/// "the allocated storage is deallocated within the evaluation".
2442
8.75M
static bool CheckMemoryLeaks(EvalInfo &Info) {
2443
8.75M
  if (!Info.HeapAllocs.empty()) {
2444
    // We can still fold to a constant despite a compile-time memory leak,
2445
    // so long as the heap allocation isn't referenced in the result (we check
2446
    // that in CheckConstantExpression).
2447
23
    Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2448
23
                 diag::note_constexpr_memory_leak)
2449
23
        << unsigned(Info.HeapAllocs.size() - 1);
2450
23
  }
2451
8.75M
  return true;
2452
8.75M
}
2453
2454
6.06k
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2455
  // A null base expression indicates a null pointer.  These are always
2456
  // evaluatable, and they are false unless the offset is zero.
2457
6.06k
  if (!Value.getLValueBase()) {
2458
631
    Result = !Value.getLValueOffset().isZero();
2459
631
    return true;
2460
631
  }
2461
2462
  // We have a non-null base.  These are generally known to be true, but if it's
2463
  // a weak declaration it can be null at runtime.
2464
5.42k
  Result = true;
2465
5.42k
  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2466
5.42k
  return !Decl || 
!Decl->isWeak()953
;
2467
6.06k
}
2468
2469
2.25M
static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2470
2.25M
  switch (Val.getKind()) {
2471
115k
  case APValue::None:
2472
115k
  case APValue::Indeterminate:
2473
115k
    return false;
2474
2.13M
  case APValue::Int:
2475
2.13M
    Result = Val.getInt().getBoolValue();
2476
2.13M
    return true;
2477
0
  case APValue::FixedPoint:
2478
0
    Result = Val.getFixedPoint().getBoolValue();
2479
0
    return true;
2480
86
  case APValue::Float:
2481
86
    Result = !Val.getFloat().isZero();
2482
86
    return true;
2483
2
  case APValue::ComplexInt:
2484
2
    Result = Val.getComplexIntReal().getBoolValue() ||
2485
2
             
Val.getComplexIntImag().getBoolValue()1
;
2486
2
    return true;
2487
2
  case APValue::ComplexFloat:
2488
2
    Result = !Val.getComplexFloatReal().isZero() ||
2489
2
             
!Val.getComplexFloatImag().isZero()1
;
2490
2
    return true;
2491
6.06k
  case APValue::LValue:
2492
6.06k
    return EvalPointerValueAsBool(Val, Result);
2493
75
  case APValue::MemberPointer:
2494
75
    Result = Val.getMemberPointerDecl();
2495
75
    return true;
2496
36
  case APValue::Vector:
2497
36
  case APValue::Array:
2498
36
  case APValue::Struct:
2499
36
  case APValue::Union:
2500
36
  case APValue::AddrLabelDiff:
2501
36
    return false;
2502
2.25M
  }
2503
2504
0
  llvm_unreachable("unknown APValue kind");
2505
0
}
2506
2507
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2508
1.74M
                                       EvalInfo &Info) {
2509
1.74M
  assert(!E->isValueDependent());
2510
0
  assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2511
0
  APValue Val;
2512
1.74M
  if (!Evaluate(Val, Info, E))
2513
381k
    return false;
2514
1.36M
  return HandleConversionToBool(Val, Result);
2515
1.74M
}
2516
2517
template<typename T>
2518
static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2519
670
                           const T &SrcValue, QualType DestType) {
2520
670
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2521
670
    << SrcValue << DestType;
2522
670
  return Info.noteUndefinedBehavior();
2523
670
}
ExprConstant.cpp:bool HandleOverflow<llvm::APSInt>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, clang::QualType)
Line
Count
Source
2519
584
                           const T &SrcValue, QualType DestType) {
2520
584
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2521
584
    << SrcValue << DestType;
2522
584
  return Info.noteUndefinedBehavior();
2523
584
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFixedPoint>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFixedPoint const&, clang::QualType)
Line
Count
Source
2519
58
                           const T &SrcValue, QualType DestType) {
2520
58
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2521
58
    << SrcValue << DestType;
2522
58
  return Info.noteUndefinedBehavior();
2523
58
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFloat>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFloat const&, clang::QualType)
Line
Count
Source
2519
28
                           const T &SrcValue, QualType DestType) {
2520
28
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2521
28
    << SrcValue << DestType;
2522
28
  return Info.noteUndefinedBehavior();
2523
28
}
2524
2525
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2526
                                 QualType SrcType, const APFloat &Value,
2527
4.48k
                                 QualType DestType, APSInt &Result) {
2528
4.48k
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2529
  // Determine whether we are converting to unsigned or signed.
2530
4.48k
  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2531
2532
4.48k
  Result = APSInt(DestWidth, !DestSigned);
2533
4.48k
  bool ignored;
2534
4.48k
  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2535
4.48k
      & APFloat::opInvalidOp)
2536
28
    return HandleOverflow(Info, E, Value, DestType);
2537
4.45k
  return true;
2538
4.48k
}
2539
2540
/// Get rounding mode used for evaluation of the specified expression.
2541
/// \param[out] DynamicRM Is set to true is the requested rounding mode is
2542
///                       dynamic.
2543
/// If rounding mode is unknown at compile time, still try to evaluate the
2544
/// expression. If the result is exact, it does not depend on rounding mode.
2545
/// So return "tonearest" mode instead of "dynamic".
2546
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2547
26.8k
                                                bool &DynamicRM) {
2548
26.8k
  llvm::RoundingMode RM =
2549
26.8k
      E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2550
26.8k
  DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2551
26.8k
  if (DynamicRM)
2552
176
    RM = llvm::RoundingMode::NearestTiesToEven;
2553
26.8k
  return RM;
2554
26.8k
}
2555
2556
/// Check if the given evaluation result is allowed for constant evaluation.
2557
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2558
26.8k
                                     APFloat::opStatus St) {
2559
  // In a constant context, assume that any dynamic rounding mode or FP
2560
  // exception state matches the default floating-point environment.
2561
26.8k
  if (Info.InConstantContext)
2562
16.9k
    return true;
2563
2564
9.89k
  FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2565
9.89k
  if ((St & APFloat::opInexact) &&
2566
9.89k
      
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic437
) {
2567
    // Inexact result means that it depends on rounding mode. If the requested
2568
    // mode is dynamic, the evaluation cannot be made in compile time.
2569
24
    Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2570
24
    return false;
2571
24
  }
2572
2573
9.87k
  if ((St != APFloat::opOK) &&
2574
9.87k
      
(419
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic419
||
2575
419
       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2576
419
       
FPO.getAllowFEnvAccess()417
)) {
2577
2
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2578
2
    return false;
2579
2
  }
2580
2581
9.86k
  if ((St & APFloat::opStatus::opInvalidOp) &&
2582
9.86k
      
FPO.getFPExceptionMode() != LangOptions::FPE_Ignore0
) {
2583
    // There is no usefully definable result.
2584
0
    Info.FFDiag(E);
2585
0
    return false;
2586
0
  }
2587
2588
  // FIXME: if:
2589
  // - evaluation triggered other FP exception, and
2590
  // - exception mode is not "ignore", and
2591
  // - the expression being evaluated is not a part of global variable
2592
  //   initializer,
2593
  // the evaluation probably need to be rejected.
2594
9.86k
  return true;
2595
9.86k
}
2596
2597
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2598
                                   QualType SrcType, QualType DestType,
2599
10.3k
                                   APFloat &Result) {
2600
10.3k
  assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2601
0
  bool DynamicRM;
2602
10.3k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2603
10.3k
  APFloat::opStatus St;
2604
10.3k
  APFloat Value = Result;
2605
10.3k
  bool ignored;
2606
10.3k
  St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2607
10.3k
  return checkFloatingPointResult(Info, E, St);
2608
10.3k
}
2609
2610
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2611
                                 QualType DestType, QualType SrcType,
2612
1.13M
                                 const APSInt &Value) {
2613
1.13M
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2614
  // Figure out if this is a truncate, extend or noop cast.
2615
  // If the input is signed, do a sign extend, noop, or truncate.
2616
1.13M
  APSInt Result = Value.extOrTrunc(DestWidth);
2617
1.13M
  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2618
1.13M
  if (DestType->isBooleanType())
2619
60
    Result = Value.getBoolValue();
2620
1.13M
  return Result;
2621
1.13M
}
2622
2623
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2624
                                 const FPOptions FPO,
2625
                                 QualType SrcType, const APSInt &Value,
2626
23.1k
                                 QualType DestType, APFloat &Result) {
2627
23.1k
  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2628
23.1k
  APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2629
23.1k
       APFloat::rmNearestTiesToEven);
2630
23.1k
  if (!Info.InConstantContext && 
St != llvm::APFloatBase::opOK11.9k
&&
2631
23.1k
      
FPO.isFPConstrained()4
) {
2632
0
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2633
0
    return false;
2634
0
  }
2635
23.1k
  return true;
2636
23.1k
}
2637
2638
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2639
427
                                  APValue &Value, const FieldDecl *FD) {
2640
427
  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2641
2642
427
  if (!Value.isInt()) {
2643
    // Trying to store a pointer-cast-to-integer into a bitfield.
2644
    // FIXME: In this case, we should provide the diagnostic for casting
2645
    // a pointer to an integer.
2646
4
    assert(Value.isLValue() && "integral value neither int nor lvalue?");
2647
0
    Info.FFDiag(E);
2648
4
    return false;
2649
4
  }
2650
2651
423
  APSInt &Int = Value.getInt();
2652
423
  unsigned OldBitWidth = Int.getBitWidth();
2653
423
  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2654
423
  if (NewBitWidth < OldBitWidth)
2655
370
    Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2656
423
  return true;
2657
427
}
2658
2659
static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2660
339k
                                  llvm::APInt &Res) {
2661
339k
  APValue SVal;
2662
339k
  if (!Evaluate(SVal, Info, E))
2663
338k
    return false;
2664
529
  if (SVal.isInt()) {
2665
22
    Res = SVal.getInt();
2666
22
    return true;
2667
22
  }
2668
507
  if (SVal.isFloat()) {
2669
0
    Res = SVal.getFloat().bitcastToAPInt();
2670
0
    return true;
2671
0
  }
2672
507
  if (SVal.isVector()) {
2673
507
    QualType VecTy = E->getType();
2674
507
    unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2675
507
    QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2676
507
    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2677
507
    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2678
507
    Res = llvm::APInt::getZero(VecSize);
2679
2.97k
    for (unsigned i = 0; i < SVal.getVectorLength(); 
i++2.46k
) {
2680
2.46k
      APValue &Elt = SVal.getVectorElt(i);
2681
2.46k
      llvm::APInt EltAsInt;
2682
2.46k
      if (Elt.isInt()) {
2683
2.32k
        EltAsInt = Elt.getInt();
2684
2.32k
      } else 
if (140
Elt.isFloat()140
) {
2685
140
        EltAsInt = Elt.getFloat().bitcastToAPInt();
2686
140
      } else {
2687
        // Don't try to handle vectors of anything other than int or float
2688
        // (not sure if it's possible to hit this case).
2689
0
        Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2690
0
        return false;
2691
0
      }
2692
2.46k
      unsigned BaseEltSize = EltAsInt.getBitWidth();
2693
2.46k
      if (BigEndian)
2694
1.45k
        Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2695
1.01k
      else
2696
1.01k
        Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2697
2.46k
    }
2698
507
    return true;
2699
507
  }
2700
  // Give up if the input isn't an int, float, or vector.  For example, we
2701
  // reject "(v4i16)(intptr_t)&a".
2702
0
  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2703
0
  return false;
2704
507
}
2705
2706
/// Perform the given integer operation, which is known to need at most BitWidth
2707
/// bits, and check for overflow in the original type (if that type was not an
2708
/// unsigned type).
2709
template<typename Operation>
2710
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2711
                                 const APSInt &LHS, const APSInt &RHS,
2712
                                 unsigned BitWidth, Operation Op,
2713
2.72M
                                 APSInt &Result) {
2714
2.72M
  if (LHS.isUnsigned()) {
2715
150k
    Result = Op(LHS, RHS);
2716
150k
    return true;
2717
150k
  }
2718
2719
2.57M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720
2.57M
  Result = Value.trunc(LHS.getBitWidth());
2721
2.57M
  if (Result.extend(BitWidth) != Value) {
2722
557
    if (Info.checkingForUndefinedBehavior())
2723
206
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724
206
                                       diag::warn_integer_constant_overflow)
2725
206
          << toString(Result, 10) << E->getType();
2726
557
    return HandleOverflow(Info, E, Value, E->getType());
2727
557
  }
2728
2.57M
  return true;
2729
2.57M
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::multiplies<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::multiplies<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2713
210k
                                 APSInt &Result) {
2714
210k
  if (LHS.isUnsigned()) {
2715
61.2k
    Result = Op(LHS, RHS);
2716
61.2k
    return true;
2717
61.2k
  }
2718
2719
149k
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720
149k
  Result = Value.trunc(LHS.getBitWidth());
2721
149k
  if (Result.extend(BitWidth) != Value) {
2722
535
    if (Info.checkingForUndefinedBehavior())
2723
204
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724
204
                                       diag::warn_integer_constant_overflow)
2725
204
          << toString(Result, 10) << E->getType();
2726
535
    return HandleOverflow(Info, E, Value, E->getType());
2727
535
  }
2728
148k
  return true;
2729
149k
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::plus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::plus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2713
908k
                                 APSInt &Result) {
2714
908k
  if (LHS.isUnsigned()) {
2715
17.4k
    Result = Op(LHS, RHS);
2716
17.4k
    return true;
2717
17.4k
  }
2718
2719
891k
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720
891k
  Result = Value.trunc(LHS.getBitWidth());
2721
891k
  if (Result.extend(BitWidth) != Value) {
2722
14
    if (Info.checkingForUndefinedBehavior())
2723
2
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724
2
                                       diag::warn_integer_constant_overflow)
2725
2
          << toString(Result, 10) << E->getType();
2726
14
    return HandleOverflow(Info, E, Value, E->getType());
2727
14
  }
2728
891k
  return true;
2729
891k
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::minus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::minus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2713
1.60M
                                 APSInt &Result) {
2714
1.60M
  if (LHS.isUnsigned()) {
2715
71.6k
    Result = Op(LHS, RHS);
2716
71.6k
    return true;
2717
71.6k
  }
2718
2719
1.53M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720
1.53M
  Result = Value.trunc(LHS.getBitWidth());
2721
1.53M
  if (Result.extend(BitWidth) != Value) {
2722
8
    if (Info.checkingForUndefinedBehavior())
2723
0
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724
0
                                       diag::warn_integer_constant_overflow)
2725
0
          << toString(Result, 10) << E->getType();
2726
8
    return HandleOverflow(Info, E, Value, E->getType());
2727
8
  }
2728
1.53M
  return true;
2729
1.53M
}
2730
2731
/// Perform the given binary integer operation.
2732
static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2733
                              BinaryOperatorKind Opcode, APSInt RHS,
2734
4.05M
                              APSInt &Result) {
2735
4.05M
  switch (Opcode) {
2736
0
  default:
2737
0
    Info.FFDiag(E);
2738
0
    return false;
2739
210k
  case BO_Mul:
2740
210k
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2741
210k
                                std::multiplies<APSInt>(), Result);
2742
908k
  case BO_Add:
2743
908k
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744
908k
                                std::plus<APSInt>(), Result);
2745
1.60M
  case BO_Sub:
2746
1.60M
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2747
1.60M
                                std::minus<APSInt>(), Result);
2748
20.1k
  case BO_And: Result = LHS & RHS; return true;
2749
1.60k
  case BO_Xor: Result = LHS ^ RHS; return true;
2750
66.2k
  case BO_Or:  Result = LHS | RHS; return true;
2751
683k
  case BO_Div:
2752
692k
  case BO_Rem:
2753
692k
    if (RHS == 0) {
2754
138
      Info.FFDiag(E, diag::note_expr_divide_by_zero);
2755
138
      return false;
2756
138
    }
2757
692k
    Result = (Opcode == BO_Rem ? 
LHS % RHS8.55k
:
LHS / RHS683k
);
2758
    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2759
    // this operation and gives the two's complement result.
2760
692k
    if (RHS.isNegative() && 
RHS.isAllOnesValue()7
&&
2761
692k
        
LHS.isSigned()7
&&
LHS.isMinSignedValue()7
)
2762
6
      return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2763
6
                            E->getType());
2764
692k
    return true;
2765
258k
  case BO_Shl: {
2766
258k
    if (Info.getLangOpts().OpenCL)
2767
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2768
18
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2769
18
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2770
18
                    RHS.isUnsigned());
2771
258k
    else if (RHS.isSigned() && 
RHS.isNegative()226k
) {
2772
      // During constant-folding, a negative shift is an opposite shift. Such
2773
      // a shift is not a constant expression.
2774
13
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2775
13
      RHS = -RHS;
2776
13
      goto shift_right;
2777
13
    }
2778
258k
  shift_left:
2779
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2780
    // the shifted type.
2781
258k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2782
258k
    if (SA != RHS) {
2783
19
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2784
19
        << RHS << E->getType() << LHS.getBitWidth();
2785
258k
    } else if (LHS.isSigned() && 
!Info.getLangOpts().CPlusPlus20173k
) {
2786
      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2787
      // operand, and must not overflow the corresponding unsigned type.
2788
      // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2789
      // E1 x 2^E2 module 2^N.
2790
173k
      if (LHS.isNegative())
2791
13
        Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2792
173k
      else if (LHS.countLeadingZeros() < SA)
2793
9
        Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2794
173k
    }
2795
258k
    Result = LHS << SA;
2796
258k
    return true;
2797
258k
  }
2798
11.0k
  case BO_Shr: {
2799
11.0k
    if (Info.getLangOpts().OpenCL)
2800
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2801
2
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2802
2
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2803
2
                    RHS.isUnsigned());
2804
10.9k
    else if (RHS.isSigned() && 
RHS.isNegative()10.9k
) {
2805
      // During constant-folding, a negative shift is an opposite shift. Such a
2806
      // shift is not a constant expression.
2807
9
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2808
9
      RHS = -RHS;
2809
9
      goto shift_left;
2810
9
    }
2811
11.0k
  shift_right:
2812
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2813
    // shifted type.
2814
11.0k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2815
11.0k
    if (SA != RHS)
2816
9
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2817
9
        << RHS << E->getType() << LHS.getBitWidth();
2818
11.0k
    Result = LHS >> SA;
2819
11.0k
    return true;
2820
11.0k
  }
2821
2822
76.2k
  case BO_LT: Result = LHS < RHS; return true;
2823
10.6k
  case BO_GT: Result = LHS > RHS; return true;
2824
32.2k
  case BO_LE: Result = LHS <= RHS; return true;
2825
8.12k
  case BO_GE: Result = LHS >= RHS; return true;
2826
99.4k
  case BO_EQ: Result = LHS == RHS; return true;
2827
49.9k
  case BO_NE: Result = LHS != RHS; return true;
2828
0
  case BO_Cmp:
2829
0
    llvm_unreachable("BO_Cmp should be handled elsewhere");
2830
4.05M
  }
2831
4.05M
}
2832
2833
/// Perform the given binary floating-point operation, in-place, on LHS.
2834
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2835
                                  APFloat &LHS, BinaryOperatorKind Opcode,
2836
16.4k
                                  const APFloat &RHS) {
2837
16.4k
  bool DynamicRM;
2838
16.4k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2839
16.4k
  APFloat::opStatus St;
2840
16.4k
  switch (Opcode) {
2841
0
  default:
2842
0
    Info.FFDiag(E);
2843
0
    return false;
2844
4.23k
  case BO_Mul:
2845
4.23k
    St = LHS.multiply(RHS, RM);
2846
4.23k
    break;
2847
2.20k
  case BO_Add:
2848
2.20k
    St = LHS.add(RHS, RM);
2849
2.20k
    break;
2850
3.85k
  case BO_Sub:
2851
3.85k
    St = LHS.subtract(RHS, RM);
2852
3.85k
    break;
2853
6.14k
  case BO_Div:
2854
    // [expr.mul]p4:
2855
    //   If the second operand of / or % is zero the behavior is undefined.
2856
6.14k
    if (RHS.isZero())
2857
13
      Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2858
6.14k
    St = LHS.divide(RHS, RM);
2859
6.14k
    break;
2860
16.4k
  }
2861
2862
  // [expr.pre]p4:
2863
  //   If during the evaluation of an expression, the result is not
2864
  //   mathematically defined [...], the behavior is undefined.
2865
  // FIXME: C++ rules require us to not conform to IEEE 754 here.
2866
16.4k
  if (LHS.isNaN()) {
2867
9
    Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2868
9
    return Info.noteUndefinedBehavior();
2869
9
  }
2870
2871
16.4k
  return checkFloatingPointResult(Info, E, St);
2872
16.4k
}
2873
2874
static bool handleLogicalOpForVector(const APInt &LHSValue,
2875
                                     BinaryOperatorKind Opcode,
2876
32
                                     const APInt &RHSValue, APInt &Result) {
2877
32
  bool LHS = (LHSValue != 0);
2878
32
  bool RHS = (RHSValue != 0);
2879
2880
32
  if (Opcode == BO_LAnd)
2881
16
    Result = LHS && 
RHS8
;
2882
16
  else
2883
16
    Result = LHS || 
RHS8
;
2884
32
  return true;
2885
32
}
2886
static bool handleLogicalOpForVector(const APFloat &LHSValue,
2887
                                     BinaryOperatorKind Opcode,
2888
96
                                     const APFloat &RHSValue, APInt &Result) {
2889
96
  bool LHS = !LHSValue.isZero();
2890
96
  bool RHS = !RHSValue.isZero();
2891
2892
96
  if (Opcode == BO_LAnd)
2893
48
    Result = LHS && 
RHS24
;
2894
48
  else
2895
48
    Result = LHS || 
RHS40
;
2896
96
  return true;
2897
96
}
2898
2899
static bool handleLogicalOpForVector(const APValue &LHSValue,
2900
                                     BinaryOperatorKind Opcode,
2901
128
                                     const APValue &RHSValue, APInt &Result) {
2902
  // The result is always an int type, however operands match the first.
2903
128
  if (LHSValue.getKind() == APValue::Int)
2904
32
    return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2905
32
                                    RHSValue.getInt(), Result);
2906
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2907
0
  return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2908
96
                                  RHSValue.getFloat(), Result);
2909
128
}
2910
2911
template <typename APTy>
2912
static bool
2913
handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2914
192
                               const APTy &RHSValue, APInt &Result) {
2915
192
  switch (Opcode) {
2916
0
  default:
2917
0
    llvm_unreachable("unsupported binary operator");
2918
32
  case BO_EQ:
2919
32
    Result = (LHSValue == RHSValue);
2920
32
    break;
2921
32
  case BO_NE:
2922
32
    Result = (LHSValue != RHSValue);
2923
32
    break;
2924
32
  case BO_LT:
2925
32
    Result = (LHSValue < RHSValue);
2926
32
    break;
2927
32
  case BO_GT:
2928
32
    Result = (LHSValue > RHSValue);
2929
32
    break;
2930
32
  case BO_LE:
2931
32
    Result = (LHSValue <= RHSValue);
2932
32
    break;
2933
32
  case BO_GE:
2934
32
    Result = (LHSValue >= RHSValue);
2935
32
    break;
2936
192
  }
2937
2938
192
  return true;
2939
192
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APSInt>(llvm::APSInt const&, clang::BinaryOperatorKind, llvm::APSInt const&, llvm::APInt&)
Line
Count
Source
2914
96
                               const APTy &RHSValue, APInt &Result) {
2915
96
  switch (Opcode) {
2916
0
  default:
2917
0
    llvm_unreachable("unsupported binary operator");
2918
16
  case BO_EQ:
2919
16
    Result = (LHSValue == RHSValue);
2920
16
    break;
2921
16
  case BO_NE:
2922
16
    Result = (LHSValue != RHSValue);
2923
16
    break;
2924
16
  case BO_LT:
2925
16
    Result = (LHSValue < RHSValue);
2926
16
    break;
2927
16
  case BO_GT:
2928
16
    Result = (LHSValue > RHSValue);
2929
16
    break;
2930
16
  case BO_LE:
2931
16
    Result = (LHSValue <= RHSValue);
2932
16
    break;
2933
16
  case BO_GE:
2934
16
    Result = (LHSValue >= RHSValue);
2935
16
    break;
2936
96
  }
2937
2938
96
  return true;
2939
96
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APFloat>(llvm::APFloat const&, clang::BinaryOperatorKind, llvm::APFloat const&, llvm::APInt&)
Line
Count
Source
2914
96
                               const APTy &RHSValue, APInt &Result) {
2915
96
  switch (Opcode) {
2916
0
  default:
2917
0
    llvm_unreachable("unsupported binary operator");
2918
16
  case BO_EQ:
2919
16
    Result = (LHSValue == RHSValue);
2920
16
    break;
2921
16
  case BO_NE:
2922
16
    Result = (LHSValue != RHSValue);
2923
16
    break;
2924
16
  case BO_LT:
2925
16
    Result = (LHSValue < RHSValue);
2926
16
    break;
2927
16
  case BO_GT:
2928
16
    Result = (LHSValue > RHSValue);
2929
16
    break;
2930
16
  case BO_LE:
2931
16
    Result = (LHSValue <= RHSValue);
2932
16
    break;
2933
16
  case BO_GE:
2934
16
    Result = (LHSValue >= RHSValue);
2935
16
    break;
2936
96
  }
2937
2938
96
  return true;
2939
96
}
2940
2941
static bool handleCompareOpForVector(const APValue &LHSValue,
2942
                                     BinaryOperatorKind Opcode,
2943
192
                                     const APValue &RHSValue, APInt &Result) {
2944
  // The result is always an int type, however operands match the first.
2945
192
  if (LHSValue.getKind() == APValue::Int)
2946
96
    return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2947
96
                                          RHSValue.getInt(), Result);
2948
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2949
0
  return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2950
96
                                        RHSValue.getFloat(), Result);
2951
192
}
2952
2953
// Perform binary operations for vector types, in place on the LHS.
2954
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2955
                                    BinaryOperatorKind Opcode,
2956
                                    APValue &LHSValue,
2957
752
                                    const APValue &RHSValue) {
2958
752
  assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2959
752
         "Operation not supported on vector types");
2960
2961
0
  const auto *VT = E->getType()->castAs<VectorType>();
2962
752
  unsigned NumElements = VT->getNumElements();
2963
752
  QualType EltTy = VT->getElementType();
2964
2965
  // In the cases (typically C as I've observed) where we aren't evaluating
2966
  // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2967
  // just give up.
2968
752
  if (!LHSValue.isVector()) {
2969
566
    assert(LHSValue.isLValue() &&
2970
566
           "A vector result that isn't a vector OR uncalculated LValue");
2971
0
    Info.FFDiag(E);
2972
566
    return false;
2973
566
  }
2974
2975
186
  assert(LHSValue.getVectorLength() == NumElements &&
2976
186
         RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2977
2978
0
  SmallVector<APValue, 4> ResultElements;
2979
2980
930
  for (unsigned EltNum = 0; EltNum < NumElements; 
++EltNum744
) {
2981
744
    APValue LHSElt = LHSValue.getVectorElt(EltNum);
2982
744
    APValue RHSElt = RHSValue.getVectorElt(EltNum);
2983
2984
744
    if (EltTy->isIntegerType()) {
2985
616
      APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2986
616
                       EltTy->isUnsignedIntegerType()};
2987
616
      bool Success = true;
2988
2989
616
      if (BinaryOperator::isLogicalOp(Opcode))
2990
128
        Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2991
488
      else if (BinaryOperator::isComparisonOp(Opcode))
2992
192
        Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993
296
      else
2994
296
        Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2995
296
                                    RHSElt.getInt(), EltResult);
2996
2997
616
      if (!Success) {
2998
0
        Info.FFDiag(E);
2999
0
        return false;
3000
0
      }
3001
616
      ResultElements.emplace_back(EltResult);
3002
3003
616
    } else 
if (128
EltTy->isFloatingType()128
) {
3004
128
      assert(LHSElt.getKind() == APValue::Float &&
3005
128
             RHSElt.getKind() == APValue::Float &&
3006
128
             "Mismatched LHS/RHS/Result Type");
3007
0
      APFloat LHSFloat = LHSElt.getFloat();
3008
3009
128
      if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3010
128
                                 RHSElt.getFloat())) {
3011
0
        Info.FFDiag(E);
3012
0
        return false;
3013
0
      }
3014
3015
128
      ResultElements.emplace_back(LHSFloat);
3016
128
    }
3017
744
  }
3018
3019
186
  LHSValue = APValue(ResultElements.data(), ResultElements.size());
3020
186
  return true;
3021
186
}
3022
3023
/// Cast an lvalue referring to a base subobject to a derived class, by
3024
/// truncating the lvalue's path to the given length.
3025
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3026
                               const RecordDecl *TruncatedType,
3027
416
                               unsigned TruncatedElements) {
3028
416
  SubobjectDesignator &D = Result.Designator;
3029
3030
  // Check we actually point to a derived class object.
3031
416
  if (TruncatedElements == D.Entries.size())
3032
161
    return true;
3033
255
  assert(TruncatedElements >= D.MostDerivedPathLength &&
3034
255
         "not casting to a derived class");
3035
255
  if (!Result.checkSubobject(Info, E, CSK_Derived))
3036
5
    return false;
3037
3038
  // Truncate the path to the subobject, and remove any derived-to-base offsets.
3039
250
  const RecordDecl *RD = TruncatedType;
3040
1.05k
  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; 
++I807
) {
3041
807
    if (RD->isInvalidDecl()) 
return false0
;
3042
807
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3043
807
    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3044
807
    if (isVirtualBaseClass(D.Entries[I]))
3045
3
      Result.Offset -= Layout.getVBaseClassOffset(Base);
3046
804
    else
3047
804
      Result.Offset -= Layout.getBaseClassOffset(Base);
3048
807
    RD = Base;
3049
807
  }
3050
250
  D.Entries.resize(TruncatedElements);
3051
250
  return true;
3052
250
}
3053
3054
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3055
                                   const CXXRecordDecl *Derived,
3056
                                   const CXXRecordDecl *Base,
3057
12.0k
                                   const ASTRecordLayout *RL = nullptr) {
3058
12.0k
  if (!RL) {
3059
9.22k
    if (Derived->isInvalidDecl()) 
return false0
;
3060
9.22k
    RL = &Info.Ctx.getASTRecordLayout(Derived);
3061
9.22k
  }
3062
3063
12.0k
  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3064
12.0k
  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3065
12.0k
  return true;
3066
12.0k
}
3067
3068
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3069
                             const CXXRecordDecl *DerivedDecl,
3070
8.98k
                             const CXXBaseSpecifier *Base) {
3071
8.98k
  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3072
3073
8.98k
  if (!Base->isVirtual())
3074
8.87k
    return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3075
3076
115
  SubobjectDesignator &D = Obj.Designator;
3077
115
  if (D.Invalid)
3078
0
    return false;
3079
3080
  // Extract most-derived object and corresponding type.
3081
115
  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3082
115
  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3083
0
    return false;
3084
3085
  // Find the virtual base class.
3086
115
  if (DerivedDecl->isInvalidDecl()) 
return false0
;
3087
115
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3088
115
  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3089
115
  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3090
115
  return true;
3091
115
}
3092
3093
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3094
4.48k
                                 QualType Type, LValue &Result) {
3095
4.48k
  for (CastExpr::path_const_iterator PathI = E->path_begin(),
3096
4.48k
                                     PathE = E->path_end();
3097
13.1k
       PathI != PathE; 
++PathI8.64k
) {
3098
8.64k
    if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3099
8.64k
                          *PathI))
3100
0
      return false;
3101
8.64k
    Type = (*PathI)->getType();
3102
8.64k
  }
3103
4.48k
  return true;
3104
4.48k
}
3105
3106
/// Cast an lvalue referring to a derived class to a known base subobject.
3107
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3108
                            const CXXRecordDecl *DerivedRD,
3109
42
                            const CXXRecordDecl *BaseRD) {
3110
42
  CXXBasePaths Paths(/*FindAmbiguities=*/false,
3111
42
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
3112
42
  if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3113
0
    llvm_unreachable("Class must be derived from the passed in base class!");
3114
3115
42
  for (CXXBasePathElement &Elem : Paths.front())
3116
63
    if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3117
0
      return false;
3118
42
  return true;
3119
42
}
3120
3121
/// Update LVal to refer to the given field, which must be a member of the type
3122
/// currently described by LVal.
3123
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3124
                               const FieldDecl *FD,
3125
157k
                               const ASTRecordLayout *RL = nullptr) {
3126
157k
  if (!RL) {
3127
124k
    if (FD->getParent()->isInvalidDecl()) 
return false3
;
3128
124k
    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3129
124k
  }
3130
3131
157k
  unsigned I = FD->getFieldIndex();
3132
157k
  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3133
157k
  LVal.addDecl(Info, E, FD);
3134
157k
  return true;
3135
157k
}
3136
3137
/// Update LVal to refer to the given indirect field.
3138
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3139
                                       LValue &LVal,
3140
0
                                       const IndirectFieldDecl *IFD) {
3141
0
  for (const auto *C : IFD->chain())
3142
0
    if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3143
0
      return false;
3144
0
  return true;
3145
0
}
3146
3147
/// Get the size of the given type in char units.
3148
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3149
275k
                         QualType Type, CharUnits &Size) {
3150
  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3151
  // extension.
3152
275k
  if (Type->isVoidType() || 
Type->isFunctionType()275k
) {
3153
144
    Size = CharUnits::One();
3154
144
    return true;
3155
144
  }
3156
3157
275k
  if (Type->isDependentType()) {
3158
0
    Info.FFDiag(Loc);
3159
0
    return false;
3160
0
  }
3161
3162
275k
  if (!Type->isConstantSizeType()) {
3163
    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3164
    // FIXME: Better diagnostic.
3165
2.13k
    Info.FFDiag(Loc);
3166
2.13k
    return false;
3167
2.13k
  }
3168
3169
273k
  Size = Info.Ctx.getTypeSizeInChars(Type);
3170
273k
  return true;
3171
275k
}
3172
3173
/// Update a pointer value to model pointer arithmetic.
3174
/// \param Info - Information about the ongoing evaluation.
3175
/// \param E - The expression being evaluated, for diagnostic purposes.
3176
/// \param LVal - The pointer value to be updated.
3177
/// \param EltTy - The pointee type represented by LVal.
3178
/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3179
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3180
                                        LValue &LVal, QualType EltTy,
3181
130k
                                        APSInt Adjustment) {
3182
130k
  CharUnits SizeOfPointee;
3183
130k
  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3184
1.95k
    return false;
3185
3186
128k
  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3187
128k
  return true;
3188
130k
}
3189
3190
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3191
                                        LValue &LVal, QualType EltTy,
3192
92.0k
                                        int64_t Adjustment) {
3193
92.0k
  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3194
92.0k
                                     APSInt::get(Adjustment));
3195
92.0k
}
3196
3197
/// Update an lvalue to refer to a component of a complex number.
3198
/// \param Info - Information about the ongoing evaluation.
3199
/// \param LVal - The lvalue to be updated.
3200
/// \param EltTy - The complex number's component type.
3201
/// \param Imag - False for the real component, true for the imaginary.
3202
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3203
                                       LValue &LVal, QualType EltTy,
3204
473
                                       bool Imag) {
3205
473
  if (Imag) {
3206
224
    CharUnits SizeOfComponent;
3207
224
    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3208
0
      return false;
3209
224
    LVal.Offset += SizeOfComponent;
3210
224
  }
3211
473
  LVal.addComplex(Info, E, EltTy, Imag);
3212
473
  return true;
3213
473
}
3214
3215
/// Try to evaluate the initializer for a variable declaration.
3216
///
3217
/// \param Info   Information about the ongoing evaluation.
3218
/// \param E      An expression to be used when printing diagnostics.
3219
/// \param VD     The variable whose initializer should be obtained.
3220
/// \param Version The version of the variable within the frame.
3221
/// \param Frame  The frame in which the variable was created. Must be null
3222
///               if this variable is not local to the evaluation.
3223
/// \param Result Filled in with a pointer to the value of the variable.
3224
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3225
                                const VarDecl *VD, CallStackFrame *Frame,
3226
3.64M
                                unsigned Version, APValue *&Result) {
3227
3.64M
  APValue::LValueBase Base(VD, Frame ? 
Frame->Index288k
:
03.35M
, Version);
3228
3229
  // If this is a local variable, dig out its value.
3230
3.64M
  if (Frame) {
3231
288k
    Result = Frame->getTemporary(VD, Version);
3232
288k
    if (Result)
3233
285k
      return true;
3234
3235
3.64k
    if (!isa<ParmVarDecl>(VD)) {
3236
      // Assume variables referenced within a lambda's call operator that were
3237
      // not declared within the call operator are captures and during checking
3238
      // of a potential constant expression, assume they are unknown constant
3239
      // expressions.
3240
0
      assert(isLambdaCallOperator(Frame->Callee) &&
3241
0
             (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3242
0
             "missing value for local variable");
3243
0
      if (Info.checkingPotentialConstantExpression())
3244
0
        return false;
3245
      // FIXME: This diagnostic is bogus; we do support captures. Is this code
3246
      // still reachable at all?
3247
0
      Info.FFDiag(E->getBeginLoc(),
3248
0
                  diag::note_unimplemented_constexpr_lambda_feature_ast)
3249
0
          << "captures not currently allowed";
3250
0
      return false;
3251
0
    }
3252
3.64k
  }
3253
3254
  // If we're currently evaluating the initializer of this declaration, use that
3255
  // in-flight value.
3256
3.35M
  if (Info.EvaluatingDecl == Base) {
3257
84
    Result = Info.EvaluatingDeclValue;
3258
84
    return true;
3259
84
  }
3260
3261
3.35M
  if (isa<ParmVarDecl>(VD)) {
3262
    // Assume parameters of a potential constant expression are usable in
3263
    // constant expressions.
3264
1.76M
    if (!Info.checkingPotentialConstantExpression() ||
3265
1.76M
        
!Info.CurrentCall->Callee58.2k
||
3266
1.76M
        
!Info.CurrentCall->Callee->Equals(VD->getDeclContext())58.2k
) {
3267
1.71M
      if (Info.getLangOpts().CPlusPlus11) {
3268
975k
        Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3269
975k
            << VD;
3270
975k
        NoteLValueLocation(Info, Base);
3271
975k
      } else {
3272
735k
        Info.FFDiag(E);
3273
735k
      }
3274
1.71M
    }
3275
1.76M
    return false;
3276
1.76M
  }
3277
3278
  // Dig out the initializer, and use the declaration which it's attached to.
3279
  // FIXME: We should eventually check whether the variable has a reachable
3280
  // initializing declaration.
3281
1.58M
  const Expr *Init = VD->getAnyInitializer(VD);
3282
1.58M
  if (!Init) {
3283
    // Don't diagnose during potential constant expression checking; an
3284
    // initializer might be added later.
3285
102k
    if (!Info.checkingPotentialConstantExpression()) {
3286
102k
      Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3287
102k
        << VD;
3288
102k
      NoteLValueLocation(Info, Base);
3289
102k
    }
3290
102k
    return false;
3291
102k
  }
3292
3293
1.48M
  if (Init->isValueDependent()) {
3294
    // The DeclRefExpr is not value-dependent, but the variable it refers to
3295
    // has a value-dependent initializer. This should only happen in
3296
    // constant-folding cases, where the variable is not actually of a suitable
3297
    // type for use in a constant expression (otherwise the DeclRefExpr would
3298
    // have been value-dependent too), so diagnose that.
3299
2
    assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3300
2
    if (!Info.checkingPotentialConstantExpression()) {
3301
2
      Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3302
2
                         ? 
diag::note_constexpr_ltor_non_constexpr0
3303
2
                         : diag::note_constexpr_ltor_non_integral, 1)
3304
2
          << VD << VD->getType();
3305
2
      NoteLValueLocation(Info, Base);
3306
2
    }
3307
2
    return false;
3308
2
  }
3309
3310
  // Check that we can fold the initializer. In C++, we will have already done
3311
  // this in the cases where it matters for conformance.
3312
1.48M
  if (!VD->evaluateValue()) {
3313
132k
    Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3314
132k
    NoteLValueLocation(Info, Base);
3315
132k
    return false;
3316
132k
  }
3317
3318
  // Check that the variable is actually usable in constant expressions. For a
3319
  // const integral variable or a reference, we might have a non-constant
3320
  // initializer that we can nonetheless evaluate the initializer for. Such
3321
  // variables are not usable in constant expressions. In C++98, the
3322
  // initializer also syntactically needs to be an ICE.
3323
  //
3324
  // FIXME: We don't diagnose cases that aren't potentially usable in constant
3325
  // expressions here; doing so would regress diagnostics for things like
3326
  // reading from a volatile constexpr variable.
3327
1.35M
  if ((Info.getLangOpts().CPlusPlus && 
!VD->hasConstantInitialization()1.35M
&&
3328
1.35M
       
VD->mightBeUsableInConstantExpressions(Info.Ctx)626
) ||
3329
1.35M
      
(1.35M
(1.35M
Info.getLangOpts().CPlusPlus1.35M
||
Info.getLangOpts().OpenCL2.62k
) &&
3330
1.35M
       
!Info.getLangOpts().CPlusPlus111.35M
&&
!VD->hasICEInitializer(Info.Ctx)506
)) {
3331
108
    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3332
108
    NoteLValueLocation(Info, Base);
3333
108
  }
3334
3335
  // Never use the initializer of a weak variable, not even for constant
3336
  // folding. We can't be sure that this is the definition that will be used.
3337
1.35M
  if (VD->isWeak()) {
3338
9
    Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3339
9
    NoteLValueLocation(Info, Base);
3340
9
    return false;
3341
9
  }
3342
3343
1.35M
  Result = VD->getEvaluatedValue();
3344
1.35M
  return true;
3345
1.35M
}
3346
3347
/// Get the base index of the given base class within an APValue representing
3348
/// the given derived class.
3349
static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3350
1.36k
                             const CXXRecordDecl *Base) {
3351
1.36k
  Base = Base->getCanonicalDecl();
3352
1.36k
  unsigned Index = 0;
3353
1.36k
  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3354
1.70k
         E = Derived->bases_end(); I != E; 
++I, ++Index345
) {
3355
1.70k
    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3356
1.36k
      return Index;
3357
1.70k
  }
3358
3359
0
  llvm_unreachable("base class missing from derived class's bases list");
3360
0
}
3361
3362
/// Extract the value of a character from a string literal.
3363
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3364
23.0k
                                            uint64_t Index) {
3365
23.0k
  assert(!isa<SourceLocExpr>(Lit) &&
3366
23.0k
         "SourceLocExpr should have already been converted to a StringLiteral");
3367
3368
  // FIXME: Support MakeStringConstant
3369
23.0k
  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3370
0
    std::string Str;
3371
0
    Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3372
0
    assert(Index <= Str.size() && "Index too large");
3373
0
    return APSInt::getUnsigned(Str.c_str()[Index]);
3374
0
  }
3375
3376
23.0k
  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3377
185
    Lit = PE->getFunctionName();
3378
23.0k
  const StringLiteral *S = cast<StringLiteral>(Lit);
3379
23.0k
  const ConstantArrayType *CAT =
3380
23.0k
      Info.Ctx.getAsConstantArrayType(S->getType());
3381
23.0k
  assert(CAT && "string literal isn't an array");
3382
0
  QualType CharType = CAT->getElementType();
3383
23.0k
  assert(CharType->isIntegerType() && "unexpected character type");
3384
3385
0
  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3386
23.0k
               CharType->isUnsignedIntegerType());
3387
23.0k
  if (Index < S->getLength())
3388
21.9k
    Value = S->getCodeUnit(Index);
3389
23.0k
  return Value;
3390
23.0k
}
3391
3392
// Expand a string literal into an array of characters.
3393
//
3394
// FIXME: This is inefficient; we should probably introduce something similar
3395
// to the LLVM ConstantDataArray to make this cheaper.
3396
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3397
                                APValue &Result,
3398
1.57k
                                QualType AllocType = QualType()) {
3399
1.57k
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3400
1.57k
      AllocType.isNull() ? 
S->getType()1.55k
:
AllocType19
);
3401
1.57k
  assert(CAT && "string literal isn't an array");
3402
0
  QualType CharType = CAT->getElementType();
3403
1.57k
  assert(CharType->isIntegerType() && "unexpected character type");
3404
3405
0
  unsigned Elts = CAT->getSize().getZExtValue();
3406
1.57k
  Result = APValue(APValue::UninitArray(),
3407
1.57k
                   std::min(S->getLength(), Elts), Elts);
3408
1.57k
  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3409
1.57k
               CharType->isUnsignedIntegerType());
3410
1.57k
  if (Result.hasArrayFiller())
3411
1.56k
    Result.getArrayFiller() = APValue(Value);
3412
65.9k
  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; 
++I64.4k
) {
3413
64.4k
    Value = S->getCodeUnit(I);
3414
64.4k
    Result.getArrayInitializedElt(I) = APValue(Value);
3415
64.4k
  }
3416
1.57k
}
3417
3418
// Expand an array so that it has more than Index filled elements.
3419
343
static void expandArray(APValue &Array, unsigned Index) {
3420
343
  unsigned Size = Array.getArraySize();
3421
343
  assert(Index < Size);
3422
3423
  // Always at least double the number of elements for which we store a value.
3424
0
  unsigned OldElts = Array.getArrayInitializedElts();
3425
343
  unsigned NewElts = std::max(Index+1, OldElts * 2);
3426
343
  NewElts = std::min(Size, std::max(NewElts, 8u));
3427
3428
  // Copy the data across.
3429
343
  APValue NewValue(APValue::UninitArray(), NewElts, Size);
3430
1.46k
  for (unsigned I = 0; I != OldElts; 
++I1.12k
)
3431
1.12k
    NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3432
34.9k
  for (unsigned I = OldElts; I != NewElts; 
++I34.6k
)
3433
34.6k
    NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3434
343
  if (NewValue.hasArrayFiller())
3435
43
    NewValue.getArrayFiller() = Array.getArrayFiller();
3436
343
  Array.swap(NewValue);
3437
343
}
3438
3439
/// Determine whether a type would actually be read by an lvalue-to-rvalue
3440
/// conversion. If it's of class type, we may assume that the copy operation
3441
/// is trivial. Note that this is never true for a union type with fields
3442
/// (because the copy always "reads" the active member) and always true for
3443
/// a non-class type.
3444
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3445
1.72k
static bool isReadByLvalueToRvalueConversion(QualType T) {
3446
1.72k
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3447
1.72k
  return !RD || 
isReadByLvalueToRvalueConversion(RD)174
;
3448
1.72k
}
3449
2.35k
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3450
  // FIXME: A trivial copy of a union copies the object representation, even if
3451
  // the union is empty.
3452
2.35k
  if (RD->isUnion())
3453
22
    return !RD->field_empty();
3454
2.33k
  if (RD->isEmpty())
3455
691
    return false;
3456
3457
1.64k
  for (auto *Field : RD->fields())
3458
1.68k
    if (!Field->isUnnamedBitfield() &&
3459
1.68k
        
isReadByLvalueToRvalueConversion(Field->getType())1.68k
)
3460
1.60k
      return true;
3461
3462
33
  for (auto &BaseSpec : RD->bases())
3463
26
    if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3464
20
      return true;
3465
3466
13
  return false;
3467
33
}
3468
3469
/// Diagnose an attempt to read from any unreadable field within the specified
3470
/// type, which might be a class type.
3471
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3472
682
                                  QualType T) {
3473
682
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3474
682
  if (!RD)
3475
14
    return false;
3476
3477
668
  if (!RD->hasMutableFields())
3478
649
    return false;
3479
3480
35
  
for (auto *Field : RD->fields())19
{
3481
    // If we're actually going to read this field in some way, then it can't
3482
    // be mutable. If we're in a union, then assigning to a mutable field
3483
    // (even an empty one) can change the active member, so that's not OK.
3484
    // FIXME: Add core issue number for the union case.
3485
35
    if (Field->isMutable() &&
3486
35
        
(22
RD->isUnion()22
||
isReadByLvalueToRvalueConversion(Field->getType())16
)) {
3487
13
      Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3488
13
      Info.Note(Field->getLocation(), diag::note_declared_at);
3489
13
      return true;
3490
13
    }
3491
3492
22
    if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3493
3
      return true;
3494
22
  }
3495
3496
3
  for (auto &BaseSpec : RD->bases())
3497
0
    if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3498
0
      return true;
3499
3500
  // All mutable fields were empty, and thus not actually read.
3501
3
  return false;
3502
3
}
3503
3504
static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3505
                                        APValue::LValueBase Base,
3506
1.59M
                                        bool MutableSubobject = false) {
3507
  // A temporary or transient heap allocation we created.
3508
1.59M
  if (Base.getCallIndex() || 
Base.is<DynamicAllocLValue>()1.59M
)
3509
792
    return true;
3510
3511
1.59M
  switch (Info.IsEvaluatingDecl) {
3512
1.54M
  case EvalInfo::EvaluatingDeclKind::None:
3513
1.54M
    return false;
3514
3515
40.8k
  case EvalInfo::EvaluatingDeclKind::Ctor:
3516
    // The variable whose initializer we're evaluating.
3517
40.8k
    if (Info.EvaluatingDecl == Base)
3518
463
      return true;
3519
3520
    // A temporary lifetime-extended by the variable whose initializer we're
3521
    // evaluating.
3522
40.4k
    if (auto *BaseE = Base.dyn_cast<const Expr *>())
3523
56
      if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3524
56
        return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3525
40.3k
    return false;
3526
3527
109
  case EvalInfo::EvaluatingDeclKind::Dtor:
3528
    // C++2a [expr.const]p6:
3529
    //   [during constant destruction] the lifetime of a and its non-mutable
3530
    //   subobjects (but not its mutable subobjects) [are] considered to start
3531
    //   within e.
3532
109
    if (MutableSubobject || 
Base != Info.EvaluatingDecl106
)
3533
8
      return false;
3534
    // FIXME: We can meaningfully extend this to cover non-const objects, but
3535
    // we will need special handling: we should be able to access only
3536
    // subobjects of such objects that are themselves declared const.
3537
101
    QualType T = getType(Base);
3538
101
    return T.isConstQualified() || 
T->isReferenceType()34
;
3539
1.59M
  }
3540
3541
0
  llvm_unreachable("unknown evaluating decl kind");
3542
0
}
3543
3544
namespace {
3545
/// A handle to a complete object (an object that is not a subobject of
3546
/// another object).
3547
struct CompleteObject {
3548
  /// The identity of the object.
3549
  APValue::LValueBase Base;
3550
  /// The value of the complete object.
3551
  APValue *Value;
3552
  /// The type of the complete object.
3553
  QualType Type;
3554
3555
5.27M
  CompleteObject() : Value(nullptr) {}
3556
  CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3557
1.66M
      : Base(Base), Value(Value), Type(Type) {}
3558
3559
20.2k
  bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3560
    // If this isn't a "real" access (eg, if it's just accessing the type
3561
    // info), allow it. We assume the type doesn't change dynamically for
3562
    // subobjects of constexpr objects (even though we'd hit UB here if it
3563
    // did). FIXME: Is this right?
3564
20.2k
    if (!isAnyAccess(AK))
3565
18.7k
      return true;
3566
3567
    // In C++14 onwards, it is permitted to read a mutable member whose
3568
    // lifetime began within the evaluation.
3569
    // FIXME: Should we also allow this in C++11?
3570
1.49k
    if (!Info.getLangOpts().CPlusPlus14)
3571
80
      return false;
3572
1.41k
    return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3573
1.49k
  }
3574
3575
6.95M
  explicit operator bool() const { return !Type.isNull(); }
3576
};
3577
} // end anonymous namespace
3578
3579
static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3580
23.2k
                                 bool IsMutable = false) {
3581
  // C++ [basic.type.qualifier]p1:
3582
  // - A const object is an object of type const T or a non-mutable subobject
3583
  //   of a const object.
3584
23.2k
  if (ObjType.isConstQualified() && 
!IsMutable15.2k
)
3585
15.2k
    SubobjType.addConst();
3586
  // - A volatile object is an object of type const T or a subobject of a
3587
  //   volatile object.
3588
23.2k
  if (ObjType.isVolatileQualified())
3589
11
    SubobjType.addVolatile();
3590
23.2k
  return SubobjType;
3591
23.2k
}
3592
3593
/// Find the designated sub-object of an rvalue.
3594
template<typename SubobjectHandler>
3595
typename SubobjectHandler::result_type
3596
findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3597
1.64M
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
1.64M
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
1.64M
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()1.64M
) {
3602
300
    if (Info.getLangOpts().CPlusPlus11)
3603
300
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
300
                         ? diag::note_constexpr_access_past_end
3605
300
                         : 
diag::note_constexpr_access_unsized_array0
)
3606
300
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
300
    return handler.failed();
3610
300
  }
3611
3612
1.64M
  APValue *O = Obj.Value;
3613
1.64M
  QualType ObjType = Obj.Type;
3614
1.64M
  const FieldDecl *LastField = nullptr;
3615
1.64M
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
1.68M
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I38.1k
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
1.68M
    if ((O->isAbsent() && 
!(550
handler.AccessKind == AK_Construct550
&&
I == N30
)) ||
3621
1.68M
        
(1.68M
O->isIndeterminate()1.68M
&&
3622
1.68M
         
!isValidIndeterminateAccess(handler.AccessKind)672
)) {
3623
586
      if (!Info.checkingPotentialConstantExpression())
3624
568
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
568
            << handler.AccessKind << O->isIndeterminate();
3626
586
      return handler.failed();
3627
586
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
1.68M
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()275k
) &&
3633
1.68M
        
ObjType->isRecordType()1.40M
&&
3634
1.68M
        Info.isEvaluatingCtorDtor(
3635
28.1k
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
28.1k
                                         Sub.Entries.begin() + I)) !=
3637
28.1k
                          ConstructionPhase::None) {
3638
367
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
367
      ObjType.removeLocalConst();
3640
367
      ObjType.removeLocalVolatile();
3641
367
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
1.68M
    if (I == N || 
(38.4k
I == N - 138.4k
&&
ObjType->isAnyComplexType()32.5k
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
1.64M
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)24
) {
3647
24
        if (Info.getLangOpts().CPlusPlus) {
3648
24
          int DiagKind;
3649
24
          SourceLocation Loc;
3650
24
          const NamedDecl *Decl = nullptr;
3651
24
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
24
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
21
            DiagKind = 1;
3657
21
            Loc = VD->getLocation();
3658
21
            Decl = VD;
3659
21
          } else {
3660
3
            DiagKind = 0;
3661
3
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
3
              Loc = E->getExprLoc();
3663
3
          }
3664
24
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
24
              << handler.AccessKind << DiagKind << Decl;
3666
24
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
24
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
24
        return handler.failed();
3671
24
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
1.64M
      if (ObjType->isRecordType() &&
3678
1.64M
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)20.2k
&&
3679
1.64M
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)660
)
3680
13
        return handler.failed();
3681
1.64M
    }
3682
3683
1.68M
    if (I == N) {
3684
1.64M
      if (!handler.found(*O, ObjType))
3685
37
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
1.64M
      if (isModification(handler.AccessKind) &&
3689
1.64M
          
LastField43.0k
&&
LastField->isBitField()1.18k
&&
3690
1.64M
          
!truncateBitfieldValue(Info, E, *O, LastField)24
)
3691
0
        return false;
3692
3693
1.64M
      return true;
3694
1.64M
    }
3695
3696
38.4k
    LastField = nullptr;
3697
38.4k
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
14.8k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
14.8k
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
14.8k
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
14.8k
      ObjType = CAT->getElementType();
3714
3715
14.8k
      if (O->getArrayInitializedElts() > Index)
3716
14.0k
        O = &O->getArrayInitializedElt(Index);
3717
766
      else if (!isRead(handler.AccessKind)) {
3718
170
        expandArray(*O, Index);
3719
170
        O = &O->getArrayInitializedElt(Index);
3720
170
      } else
3721
596
        O = &O->getArrayFiller();
3722
23.6k
    } else if (ObjType->isAnyComplexType()) {
3723
      // Next subobject is a complex number.
3724
24
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725
24
      if (Index > 1) {
3726
0
        if (Info.getLangOpts().CPlusPlus11)
3727
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728
0
            << handler.AccessKind;
3729
0
        else
3730
0
          Info.FFDiag(E);
3731
0
        return handler.failed();
3732
0
      }
3733
3734
24
      ObjType = getSubobjectType(
3735
24
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736
3737
24
      assert(I == N - 1 && "extracting subobject of scalar?");
3738
24
      if (O->isComplexInt()) {
3739
12
        return handler.found(Index ? 
O->getComplexIntImag()6
3740
12
                                   : 
O->getComplexIntReal()6
, ObjType);
3741
12
      } else {
3742
12
        assert(O->isComplexFloat());
3743
12
        return handler.found(Index ? 
O->getComplexFloatImag()6
3744
12
                                   : 
O->getComplexFloatReal()6
, ObjType);
3745
12
      }
3746
23.6k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747
22.3k
      if (Field->isMutable() &&
3748
22.3k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)40
) {
3749
29
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750
29
          << handler.AccessKind << Field;
3751
29
        Info.Note(Field->getLocation(), diag::note_declared_at);
3752
29
        return handler.failed();
3753
29
      }
3754
3755
      // Next subobject is a class, struct or union field.
3756
22.2k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757
22.2k
      if (RD->isUnion()) {
3758
988
        const FieldDecl *UnionField = O->getUnionField();
3759
988
        if (!UnionField ||
3760
988
            
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()981
) {
3761
327
          if (I == N - 1 && 
handler.AccessKind == AK_Construct295
) {
3762
            // Placement new onto an inactive union member makes it active.
3763
3
            O->setUnion(Field, APValue());
3764
324
          } else {
3765
            // FIXME: If O->getUnionValue() is absent, report that there's no
3766
            // active union member rather than reporting the prior active union
3767
            // member. We'll need to fix nullptr_t to not use APValue() as its
3768
            // representation first.
3769
324
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770
324
                << handler.AccessKind << Field << !UnionField << UnionField;
3771
324
            return handler.failed();
3772
324
          }
3773
327
        }
3774
664
        O = &O->getUnionValue();
3775
664
      } else
3776
21.2k
        O = &O->getStructField(Field->getFieldIndex());
3777
3778
21.9k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779
21.9k
      LastField = Field;
3780
21.9k
      if (Field->getType().isVolatileQualified())
3781
0
        VolatileField = Field;
3782
21.9k
    } else {
3783
      // Next subobject is a base class.
3784
1.31k
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785
1.31k
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786
1.31k
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3787
3788
1.31k
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789
1.31k
    }
3790
38.4k
  }
3791
1.64M
}
ExprConstant.cpp:(anonymous namespace)::StartLifetimeOfUnionMemberHandler::result_type findSubobject<(anonymous namespace)::StartLifetimeOfUnionMemberHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::StartLifetimeOfUnionMemberHandler&)
Line
Count
Source
3597
149
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
149
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
149
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3602
0
    if (Info.getLangOpts().CPlusPlus11)
3603
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
0
                         ? diag::note_constexpr_access_past_end
3605
0
                         : diag::note_constexpr_access_unsized_array)
3606
0
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
0
    return handler.failed();
3610
0
  }
3611
3612
149
  APValue *O = Obj.Value;
3613
149
  QualType ObjType = Obj.Type;
3614
149
  const FieldDecl *LastField = nullptr;
3615
149
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
173
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I24
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
173
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3621
173
        (O->isIndeterminate() &&
3622
173
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3623
0
      if (!Info.checkingPotentialConstantExpression())
3624
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
0
            << handler.AccessKind << O->isIndeterminate();
3626
0
      return handler.failed();
3627
0
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
173
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3633
173
        
ObjType->isRecordType()0
&&
3634
173
        Info.isEvaluatingCtorDtor(
3635
0
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
0
                                         Sub.Entries.begin() + I)) !=
3637
0
                          ConstructionPhase::None) {
3638
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
0
      ObjType.removeLocalConst();
3640
0
      ObjType.removeLocalVolatile();
3641
0
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
173
    if (I == N || 
(26
I == N - 126
&&
ObjType->isAnyComplexType()10
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
147
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3647
0
        if (Info.getLangOpts().CPlusPlus) {
3648
0
          int DiagKind;
3649
0
          SourceLocation Loc;
3650
0
          const NamedDecl *Decl = nullptr;
3651
0
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
0
            DiagKind = 1;
3657
0
            Loc = VD->getLocation();
3658
0
            Decl = VD;
3659
0
          } else {
3660
0
            DiagKind = 0;
3661
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
0
              Loc = E->getExprLoc();
3663
0
          }
3664
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
0
              << handler.AccessKind << DiagKind << Decl;
3666
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
0
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
0
        return handler.failed();
3671
0
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
147
      if (ObjType->isRecordType() &&
3678
147
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3679
147
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3680
0
        return handler.failed();
3681
147
    }
3682
3683
173
    if (I == N) {
3684
147
      if (!handler.found(*O, ObjType))
3685
3
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
144
      if (isModification(handler.AccessKind) &&
3689
144
          LastField && 
LastField->isBitField()10
&&
3690
144
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3691
0
        return false;
3692
3693
144
      return true;
3694
144
    }
3695
3696
26
    LastField = nullptr;
3697
26
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
0
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
0
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
0
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
0
      ObjType = CAT->getElementType();
3714
3715
0
      if (O->getArrayInitializedElts() > Index)
3716
0
        O = &O->getArrayInitializedElt(Index);
3717
0
      else if (!isRead(handler.AccessKind)) {
3718
0
        expandArray(*O, Index);
3719
0
        O = &O->getArrayInitializedElt(Index);
3720
0
      } else
3721
0
        O = &O->getArrayFiller();
3722
26
    } else if (ObjType->isAnyComplexType()) {
3723
      // Next subobject is a complex number.
3724
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725
0
      if (Index > 1) {
3726
0
        if (Info.getLangOpts().CPlusPlus11)
3727
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728
0
            << handler.AccessKind;
3729
0
        else
3730
0
          Info.FFDiag(E);
3731
0
        return handler.failed();
3732
0
      }
3733
3734
0
      ObjType = getSubobjectType(
3735
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736
3737
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3738
0
      if (O->isComplexInt()) {
3739
0
        return handler.found(Index ? O->getComplexIntImag()
3740
0
                                   : O->getComplexIntReal(), ObjType);
3741
0
      } else {
3742
0
        assert(O->isComplexFloat());
3743
0
        return handler.found(Index ? O->getComplexFloatImag()
3744
0
                                   : O->getComplexFloatReal(), ObjType);
3745
0
      }
3746
26
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747
22
      if (Field->isMutable() &&
3748
22
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3749
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750
0
          << handler.AccessKind << Field;
3751
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3752
0
        return handler.failed();
3753
0
      }
3754
3755
      // Next subobject is a class, struct or union field.
3756
22
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757
22
      if (RD->isUnion()) {
3758
6
        const FieldDecl *UnionField = O->getUnionField();
3759
6
        if (!UnionField ||
3760
6
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761
2
          if (I == N - 1 && 
handler.AccessKind == AK_Construct0
) {
3762
            // Placement new onto an inactive union member makes it active.
3763
0
            O->setUnion(Field, APValue());
3764
2
          } else {
3765
            // FIXME: If O->getUnionValue() is absent, report that there's no
3766
            // active union member rather than reporting the prior active union
3767
            // member. We'll need to fix nullptr_t to not use APValue() as its
3768
            // representation first.
3769
2
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770
2
                << handler.AccessKind << Field << !UnionField << UnionField;
3771
2
            return handler.failed();
3772
2
          }
3773
2
        }
3774
4
        O = &O->getUnionValue();
3775
4
      } else
3776
16
        O = &O->getStructField(Field->getFieldIndex());
3777
3778
20
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779
20
      LastField = Field;
3780
20
      if (Field->getType().isVolatileQualified())
3781
0
        VolatileField = Field;
3782
20
    } else {
3783
      // Next subobject is a base class.
3784
4
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785
4
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786
4
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3787
3788
4
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789
4
    }
3790
26
  }
3791
149
}
ExprConstant.cpp:(anonymous namespace)::ModifySubobjectHandler::result_type findSubobject<(anonymous namespace)::ModifySubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::ModifySubobjectHandler&)
Line
Count
Source
3597
4.16k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
4.16k
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
4.16k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()4.14k
) {
3602
12
    if (Info.getLangOpts().CPlusPlus11)
3603
12
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
12
                         ? diag::note_constexpr_access_past_end
3605
12
                         : 
diag::note_constexpr_access_unsized_array0
)
3606
12
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
12
    return handler.failed();
3610
12
  }
3611
3612
4.14k
  APValue *O = Obj.Value;
3613
4.14k
  QualType ObjType = Obj.Type;
3614
4.14k
  const FieldDecl *LastField = nullptr;
3615
4.14k
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
7.44k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I3.29k
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
7.44k
    if ((O->isAbsent() && 
!(53
handler.AccessKind == AK_Construct53
&&
I == N0
)) ||
3621
7.44k
        
(7.39k
O->isIndeterminate()7.39k
&&
3622
7.39k
         
!isValidIndeterminateAccess(handler.AccessKind)598
)) {
3623
53
      if (!Info.checkingPotentialConstantExpression())
3624
50
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
50
            << handler.AccessKind << O->isIndeterminate();
3626
53
      return handler.failed();
3627
53
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
7.39k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()7.23k
) &&
3633
7.39k
        
ObjType->isRecordType()179
&&
3634
7.39k
        Info.isEvaluatingCtorDtor(
3635
153
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
153
                                         Sub.Entries.begin() + I)) !=
3637
153
                          ConstructionPhase::None) {
3638
147
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
147
      ObjType.removeLocalConst();
3640
147
      ObjType.removeLocalVolatile();
3641
147
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
7.39k
    if (I == N || 
(3.30k
I == N - 13.30k
&&
ObjType->isAnyComplexType()2.66k
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
4.08k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3647
0
        if (Info.getLangOpts().CPlusPlus) {
3648
0
          int DiagKind;
3649
0
          SourceLocation Loc;
3650
0
          const NamedDecl *Decl = nullptr;
3651
0
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
0
            DiagKind = 1;
3657
0
            Loc = VD->getLocation();
3658
0
            Decl = VD;
3659
0
          } else {
3660
0
            DiagKind = 0;
3661
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
0
              Loc = E->getExprLoc();
3663
0
          }
3664
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
0
              << handler.AccessKind << DiagKind << Decl;
3666
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
0
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
0
        return handler.failed();
3671
0
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
4.08k
      if (ObjType->isRecordType() &&
3678
4.08k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)68
&&
3679
4.08k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3680
0
        return handler.failed();
3681
4.08k
    }
3682
3683
7.39k
    if (I == N) {
3684
4.08k
      if (!handler.found(*O, ObjType))
3685
21
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
4.06k
      if (isModification(handler.AccessKind) &&
3689
4.06k
          LastField && 
LastField->isBitField()945
&&
3690
4.06k
          
!truncateBitfieldValue(Info, E, *O, LastField)6
)
3691
0
        return false;
3692
3693
4.06k
      return true;
3694
4.06k
    }
3695
3696
3.30k
    LastField = nullptr;
3697
3.30k
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
1.74k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
1.74k
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
1.74k
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
1.74k
      ObjType = CAT->getElementType();
3714
3715
1.74k
      if (O->getArrayInitializedElts() > Index)
3716
1.57k
        O = &O->getArrayInitializedElt(Index);
3717
164
      else if (!isRead(handler.AccessKind)) {
3718
164
        expandArray(*O, Index);
3719
164
        O = &O->getArrayInitializedElt(Index);
3720
164
      } else
3721
0
        O = &O->getArrayFiller();
3722
1.74k
    } else 
if (1.56k
ObjType->isAnyComplexType()1.56k
) {
3723
      // Next subobject is a complex number.
3724
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725
0
      if (Index > 1) {
3726
0
        if (Info.getLangOpts().CPlusPlus11)
3727
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728
0
            << handler.AccessKind;
3729
0
        else
3730
0
          Info.FFDiag(E);
3731
0
        return handler.failed();
3732
0
      }
3733
3734
0
      ObjType = getSubobjectType(
3735
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736
3737
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3738
0
      if (O->isComplexInt()) {
3739
0
        return handler.found(Index ? O->getComplexIntImag()
3740
0
                                   : O->getComplexIntReal(), ObjType);
3741
0
      } else {
3742
0
        assert(O->isComplexFloat());
3743
0
        return handler.found(Index ? O->getComplexFloatImag()
3744
0
                                   : O->getComplexFloatReal(), ObjType);
3745
0
      }
3746
1.56k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747
1.49k
      if (Field->isMutable() &&
3748
1.49k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)1
) {
3749
1
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750
1
          << handler.AccessKind << Field;
3751
1
        Info.Note(Field->getLocation(), diag::note_declared_at);
3752
1
        return handler.failed();
3753
1
      }
3754
3755
      // Next subobject is a class, struct or union field.
3756
1.49k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757
1.49k
      if (RD->isUnion()) {
3758
177
        const FieldDecl *UnionField = O->getUnionField();
3759
177
        if (!UnionField ||
3760
177
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761
7
          if (I == N - 1 && 
handler.AccessKind == AK_Construct1
) {
3762
            // Placement new onto an inactive union member makes it active.
3763
0
            O->setUnion(Field, APValue());
3764
7
          } else {
3765
            // FIXME: If O->getUnionValue() is absent, report that there's no
3766
            // active union member rather than reporting the prior active union
3767
            // member. We'll need to fix nullptr_t to not use APValue() as its
3768
            // representation first.
3769
7
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770
7
                << handler.AccessKind << Field << !UnionField << UnionField;
3771
7
            return handler.failed();
3772
7
          }
3773
7
        }
3774
170
        O = &O->getUnionValue();
3775
170
      } else
3776
1.32k
        O = &O->getStructField(Field->getFieldIndex());
3777
3778
1.49k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779
1.49k
      LastField = Field;
3780
1.49k
      if (Field->getType().isVolatileQualified())
3781
0
        VolatileField = Field;
3782
1.49k
    } else {
3783
      // Next subobject is a base class.
3784
65
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785
65
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786
65
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3787
3788
65
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789
65
    }
3790
3.30k
  }
3791
4.14k
}
ExprConstant.cpp:(anonymous namespace)::IncDecSubobjectHandler::result_type findSubobject<(anonymous namespace)::IncDecSubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::IncDecSubobjectHandler&)
Line
Count
Source
3597
33.7k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
33.7k
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
33.7k
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3602
0
    if (Info.getLangOpts().CPlusPlus11)
3603
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
0
                         ? diag::note_constexpr_access_past_end
3605
0
                         : diag::note_constexpr_access_unsized_array)
3606
0
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
0
    return handler.failed();
3610
0
  }
3611
3612
33.7k
  APValue *O = Obj.Value;
3613
33.7k
  QualType ObjType = Obj.Type;
3614
33.7k
  const FieldDecl *LastField = nullptr;
3615
33.7k
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
34.0k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I243
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
34.0k
    if ((O->isAbsent() && 
!(17
handler.AccessKind == AK_Construct17
&&
I == N0
)) ||
3621
34.0k
        
(34.0k
O->isIndeterminate()34.0k
&&
3622
34.0k
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3623
17
      if (!Info.checkingPotentialConstantExpression())
3624
14
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
14
            << handler.AccessKind << O->isIndeterminate();
3626
17
      return handler.failed();
3627
17
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
34.0k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()34.0k
) &&
3633
34.0k
        
ObjType->isRecordType()18
&&
3634
34.0k
        Info.isEvaluatingCtorDtor(
3635
18
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
18
                                         Sub.Entries.begin() + I)) !=
3637
18
                          ConstructionPhase::None) {
3638
18
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
18
      ObjType.removeLocalConst();
3640
18
      ObjType.removeLocalVolatile();
3641
18
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
34.0k
    if (I == N || 
(249
I == N - 1249
&&
ObjType->isAnyComplexType()190
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
33.7k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3647
0
        if (Info.getLangOpts().CPlusPlus) {
3648
0
          int DiagKind;
3649
0
          SourceLocation Loc;
3650
0
          const NamedDecl *Decl = nullptr;
3651
0
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
0
            DiagKind = 1;
3657
0
            Loc = VD->getLocation();
3658
0
            Decl = VD;
3659
0
          } else {
3660
0
            DiagKind = 0;
3661
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
0
              Loc = E->getExprLoc();
3663
0
          }
3664
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
0
              << handler.AccessKind << DiagKind << Decl;
3666
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
0
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
0
        return handler.failed();
3671
0
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
33.7k
      if (ObjType->isRecordType() &&
3678
33.7k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
&&
3679
33.7k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3680
0
        return handler.failed();
3681
33.7k
    }
3682
3683
34.0k
    if (I == N) {
3684
33.7k
      if (!handler.found(*O, ObjType))
3685
4
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
33.7k
      if (isModification(handler.AccessKind) &&
3689
33.7k
          LastField && 
LastField->isBitField()184
&&
3690
33.7k
          
!truncateBitfieldValue(Info, E, *O, LastField)12
)
3691
0
        return false;
3692
3693
33.7k
      return true;
3694
33.7k
    }
3695
3696
249
    LastField = nullptr;
3697
249
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
7
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
7
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
7
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
7
      ObjType = CAT->getElementType();
3714
3715
7
      if (O->getArrayInitializedElts() > Index)
3716
7
        O = &O->getArrayInitializedElt(Index);
3717
0
      else if (!isRead(handler.AccessKind)) {
3718
0
        expandArray(*O, Index);
3719
0
        O = &O->getArrayInitializedElt(Index);
3720
0
      } else
3721
0
        O = &O->getArrayFiller();
3722
242
    } else if (ObjType->isAnyComplexType()) {
3723
      // Next subobject is a complex number.
3724
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725
0
      if (Index > 1) {
3726
0
        if (Info.getLangOpts().CPlusPlus11)
3727
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728
0
            << handler.AccessKind;
3729
0
        else
3730
0
          Info.FFDiag(E);
3731
0
        return handler.failed();
3732
0
      }
3733
3734
0
      ObjType = getSubobjectType(
3735
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736
3737
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3738
0
      if (O->isComplexInt()) {
3739
0
        return handler.found(Index ? O->getComplexIntImag()
3740
0
                                   : O->getComplexIntReal(), ObjType);
3741
0
      } else {
3742
0
        assert(O->isComplexFloat());
3743
0
        return handler.found(Index ? O->getComplexFloatImag()
3744
0
                                   : O->getComplexFloatReal(), ObjType);
3745
0
      }
3746
242
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747
216
      if (Field->isMutable() &&
3748
216
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3749
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750
0
          << handler.AccessKind << Field;
3751
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3752
0
        return handler.failed();
3753
0
      }
3754
3755
      // Next subobject is a class, struct or union field.
3756
216
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757
216
      if (RD->isUnion()) {
3758
25
        const FieldDecl *UnionField = O->getUnionField();
3759
25
        if (!UnionField ||
3760
25
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761
6
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3762
            // Placement new onto an inactive union member makes it active.
3763
0
            O->setUnion(Field, APValue());
3764
6
          } else {
3765
            // FIXME: If O->getUnionValue() is absent, report that there's no
3766
            // active union member rather than reporting the prior active union
3767
            // member. We'll need to fix nullptr_t to not use APValue() as its
3768
            // representation first.
3769
6
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770
6
                << handler.AccessKind << Field << !UnionField << UnionField;
3771
6
            return handler.failed();
3772
6
          }
3773
6
        }
3774
19
        O = &O->getUnionValue();
3775
19
      } else
3776
191
        O = &O->getStructField(Field->getFieldIndex());
3777
3778
210
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779
210
      LastField = Field;
3780
210
      if (Field->getType().isVolatileQualified())
3781
0
        VolatileField = Field;
3782
210
    } else {
3783
      // Next subobject is a base class.
3784
26
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785
26
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786
26
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3787
3788
26
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789
26
    }
3790
249
  }
3791
33.7k
}
ExprConstant.cpp:(anonymous namespace)::DestroyObjectHandler::result_type findSubobject<(anonymous namespace)::DestroyObjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::DestroyObjectHandler&)
Line
Count
Source
3597
52
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
52
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
52
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3602
0
    if (Info.getLangOpts().CPlusPlus11)
3603
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
0
                         ? diag::note_constexpr_access_past_end
3605
0
                         : diag::note_constexpr_access_unsized_array)
3606
0
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
0
    return handler.failed();
3610
0
  }
3611
3612
52
  APValue *O = Obj.Value;
3613
52
  QualType ObjType = Obj.Type;
3614
52
  const FieldDecl *LastField = nullptr;
3615
52
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
79
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I27
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
79
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3621
79
        (O->isIndeterminate() &&
3622
79
         
!isValidIndeterminateAccess(handler.AccessKind)2
)) {
3623
0
      if (!Info.checkingPotentialConstantExpression())
3624
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
0
            << handler.AccessKind << O->isIndeterminate();
3626
0
      return handler.failed();
3627
0
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
79
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3633
79
        
ObjType->isRecordType()0
&&
3634
79
        Info.isEvaluatingCtorDtor(
3635
0
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
0
                                         Sub.Entries.begin() + I)) !=
3637
0
                          ConstructionPhase::None) {
3638
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
0
      ObjType.removeLocalConst();
3640
0
      ObjType.removeLocalVolatile();
3641
0
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
79
    if (I == N || 
(27
I == N - 127
&&
ObjType->isAnyComplexType()22
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
52
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3647
0
        if (Info.getLangOpts().CPlusPlus) {
3648
0
          int DiagKind;
3649
0
          SourceLocation Loc;
3650
0
          const NamedDecl *Decl = nullptr;
3651
0
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
0
            DiagKind = 1;
3657
0
            Loc = VD->getLocation();
3658
0
            Decl = VD;
3659
0
          } else {
3660
0
            DiagKind = 0;
3661
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
0
              Loc = E->getExprLoc();
3663
0
          }
3664
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
0
              << handler.AccessKind << DiagKind << Decl;
3666
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
0
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
0
        return handler.failed();
3671
0
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
52
      if (ObjType->isRecordType() &&
3678
52
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)34
&&
3679
52
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3680
0
        return handler.failed();
3681
52
    }
3682
3683
79
    if (I == N) {
3684
52
      if (!handler.found(*O, ObjType))
3685
0
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
52
      if (isModification(handler.AccessKind) &&
3689
52
          LastField && 
LastField->isBitField()13
&&
3690
52
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3691
0
        return false;
3692
3693
52
      return true;
3694
52
    }
3695
3696
27
    LastField = nullptr;
3697
27
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
6
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
6
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
6
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
6
      ObjType = CAT->getElementType();
3714
3715
6
      if (O->getArrayInitializedElts() > Index)
3716
6
        O = &O->getArrayInitializedElt(Index);
3717
0
      else if (!isRead(handler.AccessKind)) {
3718
0
        expandArray(*O, Index);
3719
0
        O = &O->getArrayInitializedElt(Index);
3720
0
      } else
3721
0
        O = &O->getArrayFiller();
3722
21
    } else if (ObjType->isAnyComplexType()) {
3723
      // Next subobject is a complex number.
3724
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725
0
      if (Index > 1) {
3726
0
        if (Info.getLangOpts().CPlusPlus11)
3727
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728
0
            << handler.AccessKind;
3729
0
        else
3730
0
          Info.FFDiag(E);
3731
0
        return handler.failed();
3732
0
      }
3733
3734
0
      ObjType = getSubobjectType(
3735
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736
3737
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3738
0
      if (O->isComplexInt()) {
3739
0
        return handler.found(Index ? O->getComplexIntImag()
3740
0
                                   : O->getComplexIntReal(), ObjType);
3741
0
      } else {
3742
0
        assert(O->isComplexFloat());
3743
0
        return handler.found(Index ? O->getComplexFloatImag()
3744
0
                                   : O->getComplexFloatReal(), ObjType);
3745
0
      }
3746
21
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747
16
      if (Field->isMutable() &&
3748
16
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3749
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750
0
          << handler.AccessKind << Field;
3751
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3752
0
        return handler.failed();
3753
0
      }
3754
3755
      // Next subobject is a class, struct or union field.
3756
16
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757
16
      if (RD->isUnion()) {
3758
16
        const FieldDecl *UnionField = O->getUnionField();
3759
16
        if (!UnionField ||
3760
16
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761
0
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3762
            // Placement new onto an inactive union member makes it active.
3763
0
            O->setUnion(Field, APValue());
3764
0
          } else {
3765
            // FIXME: If O->getUnionValue() is absent, report that there's no
3766
            // active union member rather than reporting the prior active union
3767
            // member. We'll need to fix nullptr_t to not use APValue() as its
3768
            // representation first.
3769
0
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770
0
                << handler.AccessKind << Field << !UnionField << UnionField;
3771
0
            return handler.failed();
3772
0
          }
3773
0
        }
3774
16
        O = &O->getUnionValue();
3775
16
      } else
3776
0
        O = &O->getStructField(Field->getFieldIndex());
3777
3778
16
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779
16
      LastField = Field;
3780
16
      if (Field->getType().isVolatileQualified())
3781
0
        VolatileField = Field;
3782
16
    } else {
3783
      // Next subobject is a base class.
3784
5
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785
5
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786
5
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3787
3788
5
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789
5
    }
3790
27
  }
3791
52
}
ExprConstant.cpp:(anonymous namespace)::CheckDynamicTypeHandler::result_type findSubobject<(anonymous namespace)::CheckDynamicTypeHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::CheckDynamicTypeHandler&)
Line
Count
Source
3597
18.8k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598
18.8k
  if (Sub.Invalid)
3599
    // A diagnostic will have already been produced.
3600
0
    return handler.failed();
3601
18.8k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()18.8k
) {
3602
18
    if (Info.getLangOpts().CPlusPlus11)
3603
18
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3604
18
                         ? diag::note_constexpr_access_past_end
3605
18
                         : 
diag::note_constexpr_access_unsized_array0
)
3606
18
          << handler.AccessKind;
3607
0
    else
3608
0
      Info.FFDiag(E);
3609
18
    return handler.failed();
3610
18
  }
3611
3612
18.8k
  APValue *O = Obj.Value;
3613
18.8k
  QualType ObjType = Obj.Type;
3614
18.8k
  const FieldDecl *LastField = nullptr;
3615
18.8k
  const FieldDecl *VolatileField = nullptr;
3616
3617
  // Walk the designator's path to find the subobject.
3618
19.5k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I695
) {
3619
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3620
19.5k
    if ((O->isAbsent() && 
!(20
handler.AccessKind == AK_Construct20
&&
I == N0
)) ||
3621
19.5k
        
(19.4k
O->isIndeterminate()19.4k
&&
3622
19.4k
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3623
20
      if (!Info.checkingPotentialConstantExpression())
3624
18
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625
18
            << handler.AccessKind << O->isIndeterminate();
3626
20
      return handler.failed();
3627
20
    }
3628
3629
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630
    //    const and volatile semantics are not applied on an object under
3631
    //    {con,de}struction.
3632
19.4k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()7.25k
) &&
3633
19.4k
        
ObjType->isRecordType()12.2k
&&
3634
19.4k
        Info.isEvaluatingCtorDtor(
3635
12.2k
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636
12.2k
                                         Sub.Entries.begin() + I)) !=
3637
12.2k
                          ConstructionPhase::None) {
3638
51
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3639
51
      ObjType.removeLocalConst();
3640
51
      ObjType.removeLocalVolatile();
3641
51
    }
3642
3643
    // If this is our last pass, check that the final object type is OK.
3644
19.4k
    if (I == N || 
(704
I == N - 1704
&&
ObjType->isAnyComplexType()423
)) {
3645
      // Accesses to volatile objects are prohibited.
3646
18.7k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3647
0
        if (Info.getLangOpts().CPlusPlus) {
3648
0
          int DiagKind;
3649
0
          SourceLocation Loc;
3650
0
          const NamedDecl *Decl = nullptr;
3651
0
          if (VolatileField) {
3652
0
            DiagKind = 2;
3653
0
            Loc = VolatileField->getLocation();
3654
0
            Decl = VolatileField;
3655
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656
0
            DiagKind = 1;
3657
0
            Loc = VD->getLocation();
3658
0
            Decl = VD;
3659
0
          } else {
3660
0
            DiagKind = 0;
3661
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662
0
              Loc = E->getExprLoc();
3663
0
          }
3664
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665
0
              << handler.AccessKind << DiagKind << Decl;
3666
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667
0
        } else {
3668
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669
0
        }
3670
0
        return handler.failed();
3671
0
      }
3672
3673
      // If we are reading an object of class type, there may still be more
3674
      // things we need to check: if there are any mutable subobjects, we
3675
      // cannot perform this read. (This only happens when performing a trivial
3676
      // copy or assignment.)
3677
18.7k
      if (ObjType->isRecordType() &&
3678
18.7k
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3679
18.7k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3680
0
        return handler.failed();
3681
18.7k
    }
3682
3683
19.4k
    if (I == N) {
3684
18.7k
      if (!handler.found(*O, ObjType))
3685
0
        return false;
3686
3687
      // If we modified a bit-field, truncate it to the right width.
3688
18.7k
      if (isModification(handler.AccessKind) &&
3689
18.7k
          
LastField34
&&
LastField->isBitField()6
&&
3690
18.7k
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3691
0
        return false;
3692
3693
18.7k
      return true;
3694
18.7k
    }
3695
3696
704
    LastField = nullptr;
3697
704
    if (ObjType->isArrayType()) {
3698
      // Next subobject is an array element.
3699
64
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700
64
      assert(CAT && "vla in literal type?");
3701
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702
64
      if (CAT->getSize().ule(Index)) {
3703
        // Note, it should not be possible to form a pointer with a valid
3704
        // designator which points more than one past the end of the array.
3705
0
        if (Info.getLangOpts().CPlusPlus11)
3706
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707
0
            << handler.AccessKind;
3708
0
        else
3709
0
          Info.FFDiag(E);
3710
0
        return handler.failed();
3711
0
      }
3712
3713
64
      ObjType = CAT->getElementType();
3714
3715
64
      if (O->getArrayInitializedElts() > Index)
3716
64
        O = &O->getArrayInitializedElt(Index);
3717
0
      else if (!isRead(handler.AccessKind)