Coverage Report

Created: 2020-09-19 12:23

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