Coverage Report

Created: 2022-07-16 07:03

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