Coverage Report

Created: 2022-05-17 06:19

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