Coverage Report

Created: 2019-07-24 05:18

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