Coverage Report

Created: 2021-01-23 06:44

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