Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/AST/DeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//
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 C++ related Decl classes.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/DeclCXX.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/ASTUnresolvedSet.h"
18
#include "clang/AST/Attr.h"
19
#include "clang/AST/CXXInheritance.h"
20
#include "clang/AST/DeclBase.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/DeclarationName.h"
23
#include "clang/AST/Expr.h"
24
#include "clang/AST/ExprCXX.h"
25
#include "clang/AST/LambdaCapture.h"
26
#include "clang/AST/NestedNameSpecifier.h"
27
#include "clang/AST/ODRHash.h"
28
#include "clang/AST/Type.h"
29
#include "clang/AST/TypeLoc.h"
30
#include "clang/AST/UnresolvedSet.h"
31
#include "clang/Basic/Diagnostic.h"
32
#include "clang/Basic/IdentifierTable.h"
33
#include "clang/Basic/LLVM.h"
34
#include "clang/Basic/LangOptions.h"
35
#include "clang/Basic/OperatorKinds.h"
36
#include "clang/Basic/PartialDiagnostic.h"
37
#include "clang/Basic/SourceLocation.h"
38
#include "clang/Basic/Specifiers.h"
39
#include "clang/Basic/TargetInfo.h"
40
#include "llvm/ADT/SmallPtrSet.h"
41
#include "llvm/ADT/SmallVector.h"
42
#include "llvm/ADT/iterator_range.h"
43
#include "llvm/Support/Casting.h"
44
#include "llvm/Support/ErrorHandling.h"
45
#include "llvm/Support/Format.h"
46
#include "llvm/Support/raw_ostream.h"
47
#include <algorithm>
48
#include <cassert>
49
#include <cstddef>
50
#include <cstdint>
51
52
using namespace clang;
53
54
//===----------------------------------------------------------------------===//
55
// Decl Allocation/Deallocation Method Implementations
56
//===----------------------------------------------------------------------===//
57
58
0
void AccessSpecDecl::anchor() {}
59
60
0
AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
61
0
  return new (C, ID) AccessSpecDecl(EmptyShell());
62
0
}
63
64
0
void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
65
0
  ExternalASTSource *Source = C.getExternalSource();
66
0
  assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");
67
0
  assert(Source && "getFromExternalSource with no external source");
68
69
0
  for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
70
0
    I.setDecl(cast<NamedDecl>(Source->GetExternalDecl(
71
0
        reinterpret_cast<uintptr_t>(I.getDecl()) >> 2)));
72
0
  Impl.Decls.setLazy(false);
73
0
}
74
75
CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
76
    : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
77
      Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
78
      Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),
79
      HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),
80
      HasPrivateFields(false), HasProtectedFields(false),
81
      HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
82
      HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),
83
      HasUninitializedReferenceMember(false), HasUninitializedFields(false),
84
      HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),
85
      HasInheritedAssignment(false),
86
      NeedOverloadResolutionForCopyConstructor(false),
87
      NeedOverloadResolutionForMoveConstructor(false),
88
      NeedOverloadResolutionForCopyAssignment(false),
89
      NeedOverloadResolutionForMoveAssignment(false),
90
      NeedOverloadResolutionForDestructor(false),
91
      DefaultedCopyConstructorIsDeleted(false),
92
      DefaultedMoveConstructorIsDeleted(false),
93
      DefaultedCopyAssignmentIsDeleted(false),
94
      DefaultedMoveAssignmentIsDeleted(false),
95
      DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),
96
      HasTrivialSpecialMembersForCall(SMF_All),
97
      DeclaredNonTrivialSpecialMembers(0),
98
      DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),
99
      HasConstexprNonCopyMoveConstructor(false),
100
      HasDefaultedDefaultConstructor(false),
101
      DefaultedDefaultConstructorIsConstexpr(true),
102
      HasConstexprDefaultConstructor(false),
103
      DefaultedDestructorIsConstexpr(true),
104
      HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),
105
      UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
106
      ImplicitCopyConstructorCanHaveConstParamForVBase(true),
107
      ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),
108
      ImplicitCopyAssignmentHasConstParam(true),
109
      HasDeclaredCopyConstructorWithConstParam(false),
110
      HasDeclaredCopyAssignmentWithConstParam(false),
111
      IsAnyDestructorNoReturn(false), IsLambda(false),
112
      IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),
113
46
      HasODRHash(false), Definition(D) {}
114
115
0
CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
116
0
  return Bases.get(Definition->getASTContext().getExternalSource());
117
0
}
118
119
0
CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
120
0
  return VBases.get(Definition->getASTContext().getExternalSource());
121
0
}
122
123
CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
124
                             DeclContext *DC, SourceLocation StartLoc,
125
                             SourceLocation IdLoc, IdentifierInfo *Id,
126
                             CXXRecordDecl *PrevDecl)
127
    : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
128
      DefinitionData(PrevDecl ? PrevDecl->DefinitionData
129
46
                              : nullptr) {}
130
131
CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
132
                                     DeclContext *DC, SourceLocation StartLoc,
133
                                     SourceLocation IdLoc, IdentifierInfo *Id,
134
                                     CXXRecordDecl *PrevDecl,
135
46
                                     bool DelayTypeCreation) {
136
46
  auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
137
46
                                      PrevDecl);
138
46
  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
139
140
  // FIXME: DelayTypeCreation seems like such a hack
141
46
  if (!DelayTypeCreation)
142
46
    C.getTypeDeclType(R, PrevDecl);
143
46
  return R;
144
46
}
145
146
CXXRecordDecl *
147
CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
148
                            TypeSourceInfo *Info, SourceLocation Loc,
149
                            unsigned DependencyKind, bool IsGeneric,
150
0
                            LambdaCaptureDefault CaptureDefault) {
151
0
  auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc,
152
0
                                      Loc, nullptr, nullptr);
153
0
  R->setBeingDefined(true);
154
0
  R->DefinitionData = new (C) struct LambdaDefinitionData(
155
0
      R, Info, DependencyKind, IsGeneric, CaptureDefault);
156
0
  R->setMayHaveOutOfDateDef(false);
157
0
  R->setImplicit(true);
158
159
0
  C.getTypeDeclType(R, /*PrevDecl=*/nullptr);
160
0
  return R;
161
0
}
162
163
CXXRecordDecl *
164
0
CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
165
0
  auto *R = new (C, ID)
166
0
      CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr,
167
0
                    SourceLocation(), SourceLocation(), nullptr, nullptr);
168
0
  R->setMayHaveOutOfDateDef(false);
169
0
  return R;
170
0
}
171
172
/// Determine whether a class has a repeated base class. This is intended for
173
/// use when determining if a class is standard-layout, so makes no attempt to
174
/// handle virtual bases.
175
0
static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
176
0
  llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
177
0
  SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
178
0
  while (!WorkList.empty()) {
179
0
    const CXXRecordDecl *RD = WorkList.pop_back_val();
180
0
    if (RD->getTypeForDecl()->isDependentType())
181
0
      continue;
182
0
    for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {
183
0
      if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {
184
0
        if (!SeenBaseTypes.insert(B).second)
185
0
          return true;
186
0
        WorkList.push_back(B);
187
0
      }
188
0
    }
189
0
  }
190
0
  return false;
191
0
}
192
193
void
194
CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
195
0
                        unsigned NumBases) {
196
0
  ASTContext &C = getASTContext();
197
198
0
  if (!data().Bases.isOffset() && data().NumBases > 0)
199
0
    C.Deallocate(data().getBases());
200
201
0
  if (NumBases) {
202
0
    if (!C.getLangOpts().CPlusPlus17) {
203
      // C++ [dcl.init.aggr]p1:
204
      //   An aggregate is [...] a class with [...] no base classes [...].
205
0
      data().Aggregate = false;
206
0
    }
207
208
    // C++ [class]p4:
209
    //   A POD-struct is an aggregate class...
210
0
    data().PlainOldData = false;
211
0
  }
212
213
  // The set of seen virtual base types.
214
0
  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
215
216
  // The virtual bases of this class.
217
0
  SmallVector<const CXXBaseSpecifier *, 8> VBases;
218
219
0
  data().Bases = new(C) CXXBaseSpecifier [NumBases];
220
0
  data().NumBases = NumBases;
221
0
  for (unsigned i = 0; i < NumBases; ++i) {
222
0
    data().getBases()[i] = *Bases[i];
223
    // Keep track of inherited vbases for this base class.
224
0
    const CXXBaseSpecifier *Base = Bases[i];
225
0
    QualType BaseType = Base->getType();
226
    // Skip dependent types; we can't do any checking on them now.
227
0
    if (BaseType->isDependentType())
228
0
      continue;
229
0
    auto *BaseClassDecl =
230
0
        cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
231
232
    // C++2a [class]p7:
233
    //   A standard-layout class is a class that:
234
    //    [...]
235
    //    -- has all non-static data members and bit-fields in the class and
236
    //       its base classes first declared in the same class
237
0
    if (BaseClassDecl->data().HasBasesWithFields ||
238
0
        !BaseClassDecl->field_empty()) {
239
0
      if (data().HasBasesWithFields)
240
        // Two bases have members or bit-fields: not standard-layout.
241
0
        data().IsStandardLayout = false;
242
0
      data().HasBasesWithFields = true;
243
0
    }
244
245
    // C++11 [class]p7:
246
    //   A standard-layout class is a class that:
247
    //     -- [...] has [...] at most one base class with non-static data
248
    //        members
249
0
    if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||
250
0
        BaseClassDecl->hasDirectFields()) {
251
0
      if (data().HasBasesWithNonStaticDataMembers)
252
0
        data().IsCXX11StandardLayout = false;
253
0
      data().HasBasesWithNonStaticDataMembers = true;
254
0
    }
255
256
0
    if (!BaseClassDecl->isEmpty()) {
257
      // C++14 [meta.unary.prop]p4:
258
      //   T is a class type [...] with [...] no base class B for which
259
      //   is_empty<B>::value is false.
260
0
      data().Empty = false;
261
0
    }
262
263
    // C++1z [dcl.init.agg]p1:
264
    //   An aggregate is a class with [...] no private or protected base classes
265
0
    if (Base->getAccessSpecifier() != AS_public) {
266
0
      data().Aggregate = false;
267
268
      // C++20 [temp.param]p7:
269
      //   A structural type is [...] a literal class type with [...] all base
270
      //   classes [...] public
271
0
      data().StructuralIfLiteral = false;
272
0
    }
273
274
    // C++ [class.virtual]p1:
275
    //   A class that declares or inherits a virtual function is called a
276
    //   polymorphic class.
277
0
    if (BaseClassDecl->isPolymorphic()) {
278
0
      data().Polymorphic = true;
279
280
      //   An aggregate is a class with [...] no virtual functions.
281
0
      data().Aggregate = false;
282
0
    }
283
284
    // C++0x [class]p7:
285
    //   A standard-layout class is a class that: [...]
286
    //    -- has no non-standard-layout base classes
287
0
    if (!BaseClassDecl->isStandardLayout())
288
0
      data().IsStandardLayout = false;
289
0
    if (!BaseClassDecl->isCXX11StandardLayout())
290
0
      data().IsCXX11StandardLayout = false;
291
292
    // Record if this base is the first non-literal field or base.
293
0
    if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
294
0
      data().HasNonLiteralTypeFieldsOrBases = true;
295
296
    // Now go through all virtual bases of this base and add them.
297
0
    for (const auto &VBase : BaseClassDecl->vbases()) {
298
      // Add this base if it's not already in the list.
299
0
      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {
300
0
        VBases.push_back(&VBase);
301
302
        // C++11 [class.copy]p8:
303
        //   The implicitly-declared copy constructor for a class X will have
304
        //   the form 'X::X(const X&)' if each [...] virtual base class B of X
305
        //   has a copy constructor whose first parameter is of type
306
        //   'const B&' or 'const volatile B&' [...]
307
0
        if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())
308
0
          if (!VBaseDecl->hasCopyConstructorWithConstParam())
309
0
            data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
310
311
        // C++1z [dcl.init.agg]p1:
312
        //   An aggregate is a class with [...] no virtual base classes
313
0
        data().Aggregate = false;
314
0
      }
315
0
    }
316
317
0
    if (Base->isVirtual()) {
318
      // Add this base if it's not already in the list.
319
0
      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)
320
0
        VBases.push_back(Base);
321
322
      // C++14 [meta.unary.prop] is_empty:
323
      //   T is a class type, but not a union type, with ... no virtual base
324
      //   classes
325
0
      data().Empty = false;
326
327
      // C++1z [dcl.init.agg]p1:
328
      //   An aggregate is a class with [...] no virtual base classes
329
0
      data().Aggregate = false;
330
331
      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
332
      //   A [default constructor, copy/move constructor, or copy/move assignment
333
      //   operator for a class X] is trivial [...] if:
334
      //    -- class X has [...] no virtual base classes
335
0
      data().HasTrivialSpecialMembers &= SMF_Destructor;
336
0
      data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
337
338
      // C++0x [class]p7:
339
      //   A standard-layout class is a class that: [...]
340
      //    -- has [...] no virtual base classes
341
0
      data().IsStandardLayout = false;
342
0
      data().IsCXX11StandardLayout = false;
343
344
      // C++20 [dcl.constexpr]p3:
345
      //   In the definition of a constexpr function [...]
346
      //    -- if the function is a constructor or destructor,
347
      //       its class shall not have any virtual base classes
348
0
      data().DefaultedDefaultConstructorIsConstexpr = false;
349
0
      data().DefaultedDestructorIsConstexpr = false;
350
351
      // C++1z [class.copy]p8:
352
      //   The implicitly-declared copy constructor for a class X will have
353
      //   the form 'X::X(const X&)' if each potentially constructed subobject
354
      //   has a copy constructor whose first parameter is of type
355
      //   'const B&' or 'const volatile B&' [...]
356
0
      if (!BaseClassDecl->hasCopyConstructorWithConstParam())
357
0
        data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
358
0
    } else {
359
      // C++ [class.ctor]p5:
360
      //   A default constructor is trivial [...] if:
361
      //    -- all the direct base classes of its class have trivial default
362
      //       constructors.
363
0
      if (!BaseClassDecl->hasTrivialDefaultConstructor())
364
0
        data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
365
366
      // C++0x [class.copy]p13:
367
      //   A copy/move constructor for class X is trivial if [...]
368
      //    [...]
369
      //    -- the constructor selected to copy/move each direct base class
370
      //       subobject is trivial, and
371
0
      if (!BaseClassDecl->hasTrivialCopyConstructor())
372
0
        data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
373
374
0
      if (!BaseClassDecl->hasTrivialCopyConstructorForCall())
375
0
        data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
376
377
      // If the base class doesn't have a simple move constructor, we'll eagerly
378
      // declare it and perform overload resolution to determine which function
379
      // it actually calls. If it does have a simple move constructor, this
380
      // check is correct.
381
0
      if (!BaseClassDecl->hasTrivialMoveConstructor())
382
0
        data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
383
384
0
      if (!BaseClassDecl->hasTrivialMoveConstructorForCall())
385
0
        data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
386
387
      // C++0x [class.copy]p27:
388
      //   A copy/move assignment operator for class X is trivial if [...]
389
      //    [...]
390
      //    -- the assignment operator selected to copy/move each direct base
391
      //       class subobject is trivial, and
392
0
      if (!BaseClassDecl->hasTrivialCopyAssignment())
393
0
        data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
394
      // If the base class doesn't have a simple move assignment, we'll eagerly
395
      // declare it and perform overload resolution to determine which function
396
      // it actually calls. If it does have a simple move assignment, this
397
      // check is correct.
398
0
      if (!BaseClassDecl->hasTrivialMoveAssignment())
399
0
        data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
400
401
      // C++11 [class.ctor]p6:
402
      //   If that user-written default constructor would satisfy the
403
      //   requirements of a constexpr constructor, the implicitly-defined
404
      //   default constructor is constexpr.
405
0
      if (!BaseClassDecl->hasConstexprDefaultConstructor())
406
0
        data().DefaultedDefaultConstructorIsConstexpr = false;
407
408
      // C++1z [class.copy]p8:
409
      //   The implicitly-declared copy constructor for a class X will have
410
      //   the form 'X::X(const X&)' if each potentially constructed subobject
411
      //   has a copy constructor whose first parameter is of type
412
      //   'const B&' or 'const volatile B&' [...]
413
0
      if (!BaseClassDecl->hasCopyConstructorWithConstParam())
414
0
        data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
415
0
    }
416
417
    // C++ [class.ctor]p3:
418
    //   A destructor is trivial if all the direct base classes of its class
419
    //   have trivial destructors.
420
0
    if (!BaseClassDecl->hasTrivialDestructor())
421
0
      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
422
423
0
    if (!BaseClassDecl->hasTrivialDestructorForCall())
424
0
      data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
425
426
0
    if (!BaseClassDecl->hasIrrelevantDestructor())
427
0
      data().HasIrrelevantDestructor = false;
428
429
0
    if (BaseClassDecl->isAnyDestructorNoReturn())
430
0
      data().IsAnyDestructorNoReturn = true;
431
432
    // C++11 [class.copy]p18:
433
    //   The implicitly-declared copy assignment operator for a class X will
434
    //   have the form 'X& X::operator=(const X&)' if each direct base class B
435
    //   of X has a copy assignment operator whose parameter is of type 'const
436
    //   B&', 'const volatile B&', or 'B' [...]
437
0
    if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
438
0
      data().ImplicitCopyAssignmentHasConstParam = false;
439
440
    // A class has an Objective-C object member if... or any of its bases
441
    // has an Objective-C object member.
442
0
    if (BaseClassDecl->hasObjectMember())
443
0
      setHasObjectMember(true);
444
445
0
    if (BaseClassDecl->hasVolatileMember())
446
0
      setHasVolatileMember(true);
447
448
0
    if (BaseClassDecl->getArgPassingRestrictions() ==
449
0
        RecordArgPassingKind::CanNeverPassInRegs)
450
0
      setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
451
452
    // Keep track of the presence of mutable fields.
453
0
    if (BaseClassDecl->hasMutableFields())
454
0
      data().HasMutableFields = true;
455
456
0
    if (BaseClassDecl->hasUninitializedReferenceMember())
457
0
      data().HasUninitializedReferenceMember = true;
458
459
0
    if (!BaseClassDecl->allowConstDefaultInit())
460
0
      data().HasUninitializedFields = true;
461
462
0
    addedClassSubobject(BaseClassDecl);
463
0
  }
464
465
  // C++2a [class]p7:
466
  //   A class S is a standard-layout class if it:
467
  //     -- has at most one base class subobject of any given type
468
  //
469
  // Note that we only need to check this for classes with more than one base
470
  // class. If there's only one base class, and it's standard layout, then
471
  // we know there are no repeated base classes.
472
0
  if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))
473
0
    data().IsStandardLayout = false;
474
475
0
  if (VBases.empty()) {
476
0
    data().IsParsingBaseSpecifiers = false;
477
0
    return;
478
0
  }
479
480
  // Create base specifier for any direct or indirect virtual bases.
481
0
  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
482
0
  data().NumVBases = VBases.size();
483
0
  for (int I = 0, E = VBases.size(); I != E; ++I) {
484
0
    QualType Type = VBases[I]->getType();
485
0
    if (!Type->isDependentType())
486
0
      addedClassSubobject(Type->getAsCXXRecordDecl());
487
0
    data().getVBases()[I] = *VBases[I];
488
0
  }
489
490
0
  data().IsParsingBaseSpecifiers = false;
491
0
}
492
493
0
unsigned CXXRecordDecl::getODRHash() const {
494
0
  assert(hasDefinition() && "ODRHash only for records with definitions");
495
496
  // Previously calculated hash is stored in DefinitionData.
497
0
  if (DefinitionData->HasODRHash)
498
0
    return DefinitionData->ODRHash;
499
500
  // Only calculate hash on first call of getODRHash per record.
501
0
  ODRHash Hash;
502
0
  Hash.AddCXXRecordDecl(getDefinition());
503
0
  DefinitionData->HasODRHash = true;
504
0
  DefinitionData->ODRHash = Hash.CalculateHash();
505
506
0
  return DefinitionData->ODRHash;
507
0
}
508
509
0
void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
510
  // C++11 [class.copy]p11:
511
  //   A defaulted copy/move constructor for a class X is defined as
512
  //   deleted if X has:
513
  //    -- a direct or virtual base class B that cannot be copied/moved [...]
514
  //    -- a non-static data member of class type M (or array thereof)
515
  //       that cannot be copied or moved [...]
516
0
  if (!Subobj->hasSimpleCopyConstructor())
517
0
    data().NeedOverloadResolutionForCopyConstructor = true;
518
0
  if (!Subobj->hasSimpleMoveConstructor())
519
0
    data().NeedOverloadResolutionForMoveConstructor = true;
520
521
  // C++11 [class.copy]p23:
522
  //   A defaulted copy/move assignment operator for a class X is defined as
523
  //   deleted if X has:
524
  //    -- a direct or virtual base class B that cannot be copied/moved [...]
525
  //    -- a non-static data member of class type M (or array thereof)
526
  //        that cannot be copied or moved [...]
527
0
  if (!Subobj->hasSimpleCopyAssignment())
528
0
    data().NeedOverloadResolutionForCopyAssignment = true;
529
0
  if (!Subobj->hasSimpleMoveAssignment())
530
0
    data().NeedOverloadResolutionForMoveAssignment = true;
531
532
  // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
533
  //   A defaulted [ctor or dtor] for a class X is defined as
534
  //   deleted if X has:
535
  //    -- any direct or virtual base class [...] has a type with a destructor
536
  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
537
  //    -- any non-static data member has a type with a destructor
538
  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
539
0
  if (!Subobj->hasSimpleDestructor()) {
540
0
    data().NeedOverloadResolutionForCopyConstructor = true;
541
0
    data().NeedOverloadResolutionForMoveConstructor = true;
542
0
    data().NeedOverloadResolutionForDestructor = true;
543
0
  }
544
545
  // C++2a [dcl.constexpr]p4:
546
  //   The definition of a constexpr destructor [shall] satisfy the
547
  //   following requirement:
548
  //   -- for every subobject of class type or (possibly multi-dimensional)
549
  //      array thereof, that class type shall have a constexpr destructor
550
0
  if (!Subobj->hasConstexprDestructor())
551
0
    data().DefaultedDestructorIsConstexpr = false;
552
553
  // C++20 [temp.param]p7:
554
  //   A structural type is [...] a literal class type [for which] the types
555
  //   of all base classes and non-static data members are structural types or
556
  //   (possibly multi-dimensional) array thereof
557
0
  if (!Subobj->data().StructuralIfLiteral)
558
0
    data().StructuralIfLiteral = false;
559
0
}
560
561
0
bool CXXRecordDecl::hasConstexprDestructor() const {
562
0
  auto *Dtor = getDestructor();
563
0
  return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
564
0
}
565
566
0
bool CXXRecordDecl::hasAnyDependentBases() const {
567
0
  if (!isDependentContext())
568
0
    return false;
569
570
0
  return !forallBases([](const CXXRecordDecl *) { return true; });
571
0
}
572
573
0
bool CXXRecordDecl::isTriviallyCopyable() const {
574
  // C++0x [class]p5:
575
  //   A trivially copyable class is a class that:
576
  //   -- has no non-trivial copy constructors,
577
0
  if (hasNonTrivialCopyConstructor()) return false;
578
  //   -- has no non-trivial move constructors,
579
0
  if (hasNonTrivialMoveConstructor()) return false;
580
  //   -- has no non-trivial copy assignment operators,
581
0
  if (hasNonTrivialCopyAssignment()) return false;
582
  //   -- has no non-trivial move assignment operators, and
583
0
  if (hasNonTrivialMoveAssignment()) return false;
584
  //   -- has a trivial destructor.
585
0
  if (!hasTrivialDestructor()) return false;
586
587
0
  return true;
588
0
}
589
590
0
bool CXXRecordDecl::isTriviallyCopyConstructible() const {
591
592
  //   A trivially copy constructible class is a class that:
593
  //   -- has no non-trivial copy constructors,
594
0
  if (hasNonTrivialCopyConstructor())
595
0
    return false;
596
  //   -- has a trivial destructor.
597
0
  if (!hasTrivialDestructor())
598
0
    return false;
599
600
0
  return true;
601
0
}
602
603
0
void CXXRecordDecl::markedVirtualFunctionPure() {
604
  // C++ [class.abstract]p2:
605
  //   A class is abstract if it has at least one pure virtual function.
606
0
  data().Abstract = true;
607
0
}
608
609
bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(
610
0
    ASTContext &Ctx, const CXXRecordDecl *XFirst) {
611
0
  if (!getNumBases())
612
0
    return false;
613
614
0
  llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;
615
0
  llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;
616
0
  SmallVector<const CXXRecordDecl*, 8> WorkList;
617
618
  // Visit a type that we have determined is an element of M(S).
619
0
  auto Visit = [&](const CXXRecordDecl *RD) -> bool {
620
0
    RD = RD->getCanonicalDecl();
621
622
    // C++2a [class]p8:
623
    //   A class S is a standard-layout class if it [...] has no element of the
624
    //   set M(S) of types as a base class.
625
    //
626
    // If we find a subobject of an empty type, it might also be a base class,
627
    // so we'll need to walk the base classes to check.
628
0
    if (!RD->data().HasBasesWithFields) {
629
      // Walk the bases the first time, stopping if we find the type. Build a
630
      // set of them so we don't need to walk them again.
631
0
      if (Bases.empty()) {
632
0
        bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {
633
0
          Base = Base->getCanonicalDecl();
634
0
          if (RD == Base)
635
0
            return false;
636
0
          Bases.insert(Base);
637
0
          return true;
638
0
        });
639
0
        if (RDIsBase)
640
0
          return true;
641
0
      } else {
642
0
        if (Bases.count(RD))
643
0
          return true;
644
0
      }
645
0
    }
646
647
0
    if (M.insert(RD).second)
648
0
      WorkList.push_back(RD);
649
0
    return false;
650
0
  };
651
652
0
  if (Visit(XFirst))
653
0
    return true;
654
655
0
  while (!WorkList.empty()) {
656
0
    const CXXRecordDecl *X = WorkList.pop_back_val();
657
658
    // FIXME: We don't check the bases of X. That matches the standard, but
659
    // that sure looks like a wording bug.
660
661
    //   -- If X is a non-union class type with a non-static data member
662
    //      [recurse to each field] that is either of zero size or is the
663
    //      first non-static data member of X
664
    //   -- If X is a union type, [recurse to union members]
665
0
    bool IsFirstField = true;
666
0
    for (auto *FD : X->fields()) {
667
      // FIXME: Should we really care about the type of the first non-static
668
      // data member of a non-union if there are preceding unnamed bit-fields?
669
0
      if (FD->isUnnamedBitfield())
670
0
        continue;
671
672
0
      if (!IsFirstField && !FD->isZeroSize(Ctx))
673
0
        continue;
674
675
      //   -- If X is n array type, [visit the element type]
676
0
      QualType T = Ctx.getBaseElementType(FD->getType());
677
0
      if (auto *RD = T->getAsCXXRecordDecl())
678
0
        if (Visit(RD))
679
0
          return true;
680
681
0
      if (!X->isUnion())
682
0
        IsFirstField = false;
683
0
    }
684
0
  }
685
686
0
  return false;
687
0
}
688
689
0
bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
690
0
  assert(isLambda() && "not a lambda");
691
692
  // C++2a [expr.prim.lambda.capture]p11:
693
  //   The closure type associated with a lambda-expression has no default
694
  //   constructor if the lambda-expression has a lambda-capture and a
695
  //   defaulted default constructor otherwise. It has a deleted copy
696
  //   assignment operator if the lambda-expression has a lambda-capture and
697
  //   defaulted copy and move assignment operators otherwise.
698
  //
699
  // C++17 [expr.prim.lambda]p21:
700
  //   The closure type associated with a lambda-expression has no default
701
  //   constructor and a deleted copy assignment operator.
702
0
  if (!isCapturelessLambda())
703
0
    return false;
704
0
  return getASTContext().getLangOpts().CPlusPlus20;
705
0
}
706
707
184
void CXXRecordDecl::addedMember(Decl *D) {
708
184
  if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) &&
709
184
      (!isa<TagDecl>(D) ||
710
0
       cast<TagDecl>(D)->getTagKind() == TagTypeKind::Class ||
711
0
       cast<TagDecl>(D)->getTagKind() == TagTypeKind::Interface))
712
0
    data().HasOnlyCMembers = false;
713
714
  // Ignore friends and invalid declarations.
715
184
  if (D->getFriendObjectKind() || D->isInvalidDecl())
716
0
    return;
717
718
184
  auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
719
184
  if (FunTmpl)
720
0
    D = FunTmpl->getTemplatedDecl();
721
722
  // FIXME: Pass NamedDecl* to addedMember?
723
184
  Decl *DUnderlying = D;
724
184
  if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {
725
184
    DUnderlying = ND->getUnderlyingDecl();
726
184
    if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))
727
0
      DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();
728
184
  }
729
730
184
  if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
731
0
    if (Method->isVirtual()) {
732
      // C++ [dcl.init.aggr]p1:
733
      //   An aggregate is an array or a class with [...] no virtual functions.
734
0
      data().Aggregate = false;
735
736
      // C++ [class]p4:
737
      //   A POD-struct is an aggregate class...
738
0
      data().PlainOldData = false;
739
740
      // C++14 [meta.unary.prop]p4:
741
      //   T is a class type [...] with [...] no virtual member functions...
742
0
      data().Empty = false;
743
744
      // C++ [class.virtual]p1:
745
      //   A class that declares or inherits a virtual function is called a
746
      //   polymorphic class.
747
0
      data().Polymorphic = true;
748
749
      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
750
      //   A [default constructor, copy/move constructor, or copy/move
751
      //   assignment operator for a class X] is trivial [...] if:
752
      //    -- class X has no virtual functions [...]
753
0
      data().HasTrivialSpecialMembers &= SMF_Destructor;
754
0
      data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
755
756
      // C++0x [class]p7:
757
      //   A standard-layout class is a class that: [...]
758
      //    -- has no virtual functions
759
0
      data().IsStandardLayout = false;
760
0
      data().IsCXX11StandardLayout = false;
761
0
    }
762
0
  }
763
764
  // Notify the listener if an implicit member was added after the definition
765
  // was completed.
766
184
  if (!isBeingDefined() && D->isImplicit())
767
0
    if (ASTMutationListener *L = getASTMutationListener())
768
0
      L->AddedCXXImplicitMember(data().Definition, D);
769
770
  // The kind of special member this declaration is, if any.
771
184
  unsigned SMKind = 0;
772
773
  // Handle constructors.
774
184
  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
775
0
    if (Constructor->isInheritingConstructor()) {
776
      // Ignore constructor shadow declarations. They are lazily created and
777
      // so shouldn't affect any properties of the class.
778
0
    } else {
779
0
      if (!Constructor->isImplicit()) {
780
        // Note that we have a user-declared constructor.
781
0
        data().UserDeclaredConstructor = true;
782
783
0
        const TargetInfo &TI = getASTContext().getTargetInfo();
784
0
        if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) ||
785
0
            !TI.areDefaultedSMFStillPOD(getLangOpts())) {
786
          // C++ [class]p4:
787
          //   A POD-struct is an aggregate class [...]
788
          // Since the POD bit is meant to be C++03 POD-ness, clear it even if
789
          // the type is technically an aggregate in C++0x since it wouldn't be
790
          // in 03.
791
0
          data().PlainOldData = false;
792
0
        }
793
0
      }
794
795
0
      if (Constructor->isDefaultConstructor()) {
796
0
        SMKind |= SMF_DefaultConstructor;
797
798
0
        if (Constructor->isUserProvided())
799
0
          data().UserProvidedDefaultConstructor = true;
800
0
        if (Constructor->isConstexpr())
801
0
          data().HasConstexprDefaultConstructor = true;
802
0
        if (Constructor->isDefaulted())
803
0
          data().HasDefaultedDefaultConstructor = true;
804
0
      }
805
806
0
      if (!FunTmpl) {
807
0
        unsigned Quals;
808
0
        if (Constructor->isCopyConstructor(Quals)) {
809
0
          SMKind |= SMF_CopyConstructor;
810
811
0
          if (Quals & Qualifiers::Const)
812
0
            data().HasDeclaredCopyConstructorWithConstParam = true;
813
0
        } else if (Constructor->isMoveConstructor())
814
0
          SMKind |= SMF_MoveConstructor;
815
0
      }
816
817
      // C++11 [dcl.init.aggr]p1: DR1518
818
      //   An aggregate is an array or a class with no user-provided [or]
819
      //   explicit [...] constructors
820
      // C++20 [dcl.init.aggr]p1:
821
      //   An aggregate is an array or a class with no user-declared [...]
822
      //   constructors
823
0
      if (getASTContext().getLangOpts().CPlusPlus20
824
0
              ? !Constructor->isImplicit()
825
0
              : (Constructor->isUserProvided() || Constructor->isExplicit()))
826
0
        data().Aggregate = false;
827
0
    }
828
0
  }
829
830
  // Handle constructors, including those inherited from base classes.
831
184
  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {
832
    // Record if we see any constexpr constructors which are neither copy
833
    // nor move constructors.
834
    // C++1z [basic.types]p10:
835
    //   [...] has at least one constexpr constructor or constructor template
836
    //   (possibly inherited from a base class) that is not a copy or move
837
    //   constructor [...]
838
0
    if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
839
0
      data().HasConstexprNonCopyMoveConstructor = true;
840
0
    if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor())
841
0
      data().HasInheritedDefaultConstructor = true;
842
0
  }
843
844
  // Handle member functions.
845
184
  if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
846
0
    if (isa<CXXDestructorDecl>(D))
847
0
      SMKind |= SMF_Destructor;
848
849
0
    if (Method->isCopyAssignmentOperator()) {
850
0
      SMKind |= SMF_CopyAssignment;
851
852
0
      const auto *ParamTy =
853
0
          Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>();
854
0
      if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
855
0
        data().HasDeclaredCopyAssignmentWithConstParam = true;
856
0
    }
857
858
0
    if (Method->isMoveAssignmentOperator())
859
0
      SMKind |= SMF_MoveAssignment;
860
861
    // Keep the list of conversion functions up-to-date.
862
0
    if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {
863
      // FIXME: We use the 'unsafe' accessor for the access specifier here,
864
      // because Sema may not have set it yet. That's really just a misdesign
865
      // in Sema. However, LLDB *will* have set the access specifier correctly,
866
      // and adds declarations after the class is technically completed,
867
      // so completeDefinition()'s overriding of the access specifiers doesn't
868
      // work.
869
0
      AccessSpecifier AS = Conversion->getAccessUnsafe();
870
871
0
      if (Conversion->getPrimaryTemplate()) {
872
        // We don't record specializations.
873
0
      } else {
874
0
        ASTContext &Ctx = getASTContext();
875
0
        ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);
876
0
        NamedDecl *Primary =
877
0
            FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);
878
0
        if (Primary->getPreviousDecl())
879
0
          Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),
880
0
                              Primary, AS);
881
0
        else
882
0
          Conversions.addDecl(Ctx, Primary, AS);
883
0
      }
884
0
    }
885
886
0
    if (SMKind) {
887
      // If this is the first declaration of a special member, we no longer have
888
      // an implicit trivial special member.
889
0
      data().HasTrivialSpecialMembers &=
890
0
          data().DeclaredSpecialMembers | ~SMKind;
891
0
      data().HasTrivialSpecialMembersForCall &=
892
0
          data().DeclaredSpecialMembers | ~SMKind;
893
894
      // Note when we have declared a declared special member, and suppress the
895
      // implicit declaration of this special member.
896
0
      data().DeclaredSpecialMembers |= SMKind;
897
0
      if (!Method->isImplicit()) {
898
0
        data().UserDeclaredSpecialMembers |= SMKind;
899
900
0
        const TargetInfo &TI = getASTContext().getTargetInfo();
901
0
        if ((!Method->isDeleted() && !Method->isDefaulted() &&
902
0
             SMKind != SMF_MoveAssignment) ||
903
0
            !TI.areDefaultedSMFStillPOD(getLangOpts())) {
904
          // C++03 [class]p4:
905
          //   A POD-struct is an aggregate class that has [...] no user-defined
906
          //   copy assignment operator and no user-defined destructor.
907
          //
908
          // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
909
          // aggregates could not have any constructors, clear it even for an
910
          // explicitly defaulted or deleted constructor.
911
          // type is technically an aggregate in C++0x since it wouldn't be in
912
          // 03.
913
          //
914
          // Also, a user-declared move assignment operator makes a class
915
          // non-POD. This is an extension in C++03.
916
0
          data().PlainOldData = false;
917
0
        }
918
0
      }
919
      // When instantiating a class, we delay updating the destructor and
920
      // triviality properties of the class until selecting a destructor and
921
      // computing the eligibility of its special member functions. This is
922
      // because there might be function constraints that we need to evaluate
923
      // and compare later in the instantiation.
924
0
      if (!Method->isIneligibleOrNotSelected()) {
925
0
        addedEligibleSpecialMemberFunction(Method, SMKind);
926
0
      }
927
0
    }
928
929
0
    return;
930
0
  }
931
932
  // Handle non-static data members.
933
184
  if (const auto *Field = dyn_cast<FieldDecl>(D)) {
934
184
    ASTContext &Context = getASTContext();
935
936
    // C++2a [class]p7:
937
    //   A standard-layout class is a class that:
938
    //    [...]
939
    //    -- has all non-static data members and bit-fields in the class and
940
    //       its base classes first declared in the same class
941
184
    if (data().HasBasesWithFields)
942
0
      data().IsStandardLayout = false;
943
944
    // C++ [class.bit]p2:
945
    //   A declaration for a bit-field that omits the identifier declares an
946
    //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
947
    //   initialized.
948
184
    if (Field->isUnnamedBitfield()) {
949
      // C++ [meta.unary.prop]p4: [LWG2358]
950
      //   T is a class type [...] with [...] no unnamed bit-fields of non-zero
951
      //   length
952
0
      if (data().Empty && !Field->isZeroLengthBitField(Context) &&
953
0
          Context.getLangOpts().getClangABICompat() >
954
0
              LangOptions::ClangABI::Ver6)
955
0
        data().Empty = false;
956
0
      return;
957
0
    }
958
959
    // C++11 [class]p7:
960
    //   A standard-layout class is a class that:
961
    //    -- either has no non-static data members in the most derived class
962
    //       [...] or has no base classes with non-static data members
963
184
    if (data().HasBasesWithNonStaticDataMembers)
964
0
      data().IsCXX11StandardLayout = false;
965
966
    // C++ [dcl.init.aggr]p1:
967
    //   An aggregate is an array or a class (clause 9) with [...] no
968
    //   private or protected non-static data members (clause 11).
969
    //
970
    // A POD must be an aggregate.
971
184
    if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
972
0
      data().Aggregate = false;
973
0
      data().PlainOldData = false;
974
975
      // C++20 [temp.param]p7:
976
      //   A structural type is [...] a literal class type [for which] all
977
      //   non-static data members are public
978
0
      data().StructuralIfLiteral = false;
979
0
    }
980
981
    // Track whether this is the first field. We use this when checking
982
    // whether the class is standard-layout below.
983
184
    bool IsFirstField = !data().HasPrivateFields &&
984
184
                        !data().HasProtectedFields && !data().HasPublicFields;
985
986
    // C++0x [class]p7:
987
    //   A standard-layout class is a class that:
988
    //    [...]
989
    //    -- has the same access control for all non-static data members,
990
184
    switch (D->getAccess()) {
991
0
    case AS_private:    data().HasPrivateFields = true;   break;
992
0
    case AS_protected:  data().HasProtectedFields = true; break;
993
184
    case AS_public:     data().HasPublicFields = true;    break;
994
0
    case AS_none:       llvm_unreachable("Invalid access specifier");
995
184
    };
996
184
    if ((data().HasPrivateFields + data().HasProtectedFields +
997
184
         data().HasPublicFields) > 1) {
998
0
      data().IsStandardLayout = false;
999
0
      data().IsCXX11StandardLayout = false;
1000
0
    }
1001
1002
    // Keep track of the presence of mutable fields.
1003
184
    if (Field->isMutable()) {
1004
0
      data().HasMutableFields = true;
1005
1006
      // C++20 [temp.param]p7:
1007
      //   A structural type is [...] a literal class type [for which] all
1008
      //   non-static data members are public
1009
0
      data().StructuralIfLiteral = false;
1010
0
    }
1011
1012
    // C++11 [class.union]p8, DR1460:
1013
    //   If X is a union, a non-static data member of X that is not an anonymous
1014
    //   union is a variant member of X.
1015
184
    if (isUnion() && !Field->isAnonymousStructOrUnion())
1016
0
      data().HasVariantMembers = true;
1017
1018
    // C++0x [class]p9:
1019
    //   A POD struct is a class that is both a trivial class and a
1020
    //   standard-layout class, and has no non-static data members of type
1021
    //   non-POD struct, non-POD union (or array of such types).
1022
    //
1023
    // Automatic Reference Counting: the presence of a member of Objective-C pointer type
1024
    // that does not explicitly have no lifetime makes the class a non-POD.
1025
184
    QualType T = Context.getBaseElementType(Field->getType());
1026
184
    if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
1027
0
      if (T.hasNonTrivialObjCLifetime()) {
1028
        // Objective-C Automatic Reference Counting:
1029
        //   If a class has a non-static data member of Objective-C pointer
1030
        //   type (or array thereof), it is a non-POD type and its
1031
        //   default constructor (if any), copy constructor, move constructor,
1032
        //   copy assignment operator, move assignment operator, and destructor are
1033
        //   non-trivial.
1034
0
        setHasObjectMember(true);
1035
0
        struct DefinitionData &Data = data();
1036
0
        Data.PlainOldData = false;
1037
0
        Data.HasTrivialSpecialMembers = 0;
1038
1039
        // __strong or __weak fields do not make special functions non-trivial
1040
        // for the purpose of calls.
1041
0
        Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();
1042
0
        if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)
1043
0
          data().HasTrivialSpecialMembersForCall = 0;
1044
1045
        // Structs with __weak fields should never be passed directly.
1046
0
        if (LT == Qualifiers::OCL_Weak)
1047
0
          setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
1048
1049
0
        Data.HasIrrelevantDestructor = false;
1050
1051
0
        if (isUnion()) {
1052
0
          data().DefaultedCopyConstructorIsDeleted = true;
1053
0
          data().DefaultedMoveConstructorIsDeleted = true;
1054
0
          data().DefaultedCopyAssignmentIsDeleted = true;
1055
0
          data().DefaultedMoveAssignmentIsDeleted = true;
1056
0
          data().DefaultedDestructorIsDeleted = true;
1057
0
          data().NeedOverloadResolutionForCopyConstructor = true;
1058
0
          data().NeedOverloadResolutionForMoveConstructor = true;
1059
0
          data().NeedOverloadResolutionForCopyAssignment = true;
1060
0
          data().NeedOverloadResolutionForMoveAssignment = true;
1061
0
          data().NeedOverloadResolutionForDestructor = true;
1062
0
        }
1063
0
      } else if (!Context.getLangOpts().ObjCAutoRefCount) {
1064
0
        setHasObjectMember(true);
1065
0
      }
1066
184
    } else if (!T.isCXX98PODType(Context))
1067
0
      data().PlainOldData = false;
1068
1069
184
    if (T->isReferenceType()) {
1070
0
      if (!Field->hasInClassInitializer())
1071
0
        data().HasUninitializedReferenceMember = true;
1072
1073
      // C++0x [class]p7:
1074
      //   A standard-layout class is a class that:
1075
      //    -- has no non-static data members of type [...] reference,
1076
0
      data().IsStandardLayout = false;
1077
0
      data().IsCXX11StandardLayout = false;
1078
1079
      // C++1z [class.copy.ctor]p10:
1080
      //   A defaulted copy constructor for a class X is defined as deleted if X has:
1081
      //    -- a non-static data member of rvalue reference type
1082
0
      if (T->isRValueReferenceType())
1083
0
        data().DefaultedCopyConstructorIsDeleted = true;
1084
0
    }
1085
1086
184
    if (!Field->hasInClassInitializer() && !Field->isMutable()) {
1087
184
      if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
1088
0
        if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
1089
0
          data().HasUninitializedFields = true;
1090
184
      } else {
1091
184
        data().HasUninitializedFields = true;
1092
184
      }
1093
184
    }
1094
1095
    // Record if this field is the first non-literal or volatile field or base.
1096
184
    if (!T->isLiteralType(Context) || T.isVolatileQualified())
1097
0
      data().HasNonLiteralTypeFieldsOrBases = true;
1098
1099
184
    if (Field->hasInClassInitializer() ||
1100
184
        (Field->isAnonymousStructOrUnion() &&
1101
184
         Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
1102
0
      data().HasInClassInitializer = true;
1103
1104
      // C++11 [class]p5:
1105
      //   A default constructor is trivial if [...] no non-static data member
1106
      //   of its class has a brace-or-equal-initializer.
1107
0
      data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1108
1109
      // C++11 [dcl.init.aggr]p1:
1110
      //   An aggregate is a [...] class with [...] no
1111
      //   brace-or-equal-initializers for non-static data members.
1112
      //
1113
      // This rule was removed in C++14.
1114
0
      if (!getASTContext().getLangOpts().CPlusPlus14)
1115
0
        data().Aggregate = false;
1116
1117
      // C++11 [class]p10:
1118
      //   A POD struct is [...] a trivial class.
1119
0
      data().PlainOldData = false;
1120
0
    }
1121
1122
    // C++11 [class.copy]p23:
1123
    //   A defaulted copy/move assignment operator for a class X is defined
1124
    //   as deleted if X has:
1125
    //    -- a non-static data member of reference type
1126
184
    if (T->isReferenceType()) {
1127
0
      data().DefaultedCopyAssignmentIsDeleted = true;
1128
0
      data().DefaultedMoveAssignmentIsDeleted = true;
1129
0
    }
1130
1131
    // Bitfields of length 0 are also zero-sized, but we already bailed out for
1132
    // those because they are always unnamed.
1133
184
    bool IsZeroSize = Field->isZeroSize(Context);
1134
1135
184
    if (const auto *RecordTy = T->getAs<RecordType>()) {
1136
0
      auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
1137
0
      if (FieldRec->getDefinition()) {
1138
0
        addedClassSubobject(FieldRec);
1139
1140
        // We may need to perform overload resolution to determine whether a
1141
        // field can be moved if it's const or volatile qualified.
1142
0
        if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {
1143
          // We need to care about 'const' for the copy constructor because an
1144
          // implicit copy constructor might be declared with a non-const
1145
          // parameter.
1146
0
          data().NeedOverloadResolutionForCopyConstructor = true;
1147
0
          data().NeedOverloadResolutionForMoveConstructor = true;
1148
0
          data().NeedOverloadResolutionForCopyAssignment = true;
1149
0
          data().NeedOverloadResolutionForMoveAssignment = true;
1150
0
        }
1151
1152
        // C++11 [class.ctor]p5, C++11 [class.copy]p11:
1153
        //   A defaulted [special member] for a class X is defined as
1154
        //   deleted if:
1155
        //    -- X is a union-like class that has a variant member with a
1156
        //       non-trivial [corresponding special member]
1157
0
        if (isUnion()) {
1158
0
          if (FieldRec->hasNonTrivialCopyConstructor())
1159
0
            data().DefaultedCopyConstructorIsDeleted = true;
1160
0
          if (FieldRec->hasNonTrivialMoveConstructor())
1161
0
            data().DefaultedMoveConstructorIsDeleted = true;
1162
0
          if (FieldRec->hasNonTrivialCopyAssignment())
1163
0
            data().DefaultedCopyAssignmentIsDeleted = true;
1164
0
          if (FieldRec->hasNonTrivialMoveAssignment())
1165
0
            data().DefaultedMoveAssignmentIsDeleted = true;
1166
0
          if (FieldRec->hasNonTrivialDestructor())
1167
0
            data().DefaultedDestructorIsDeleted = true;
1168
0
        }
1169
1170
        // For an anonymous union member, our overload resolution will perform
1171
        // overload resolution for its members.
1172
0
        if (Field->isAnonymousStructOrUnion()) {
1173
0
          data().NeedOverloadResolutionForCopyConstructor |=
1174
0
              FieldRec->data().NeedOverloadResolutionForCopyConstructor;
1175
0
          data().NeedOverloadResolutionForMoveConstructor |=
1176
0
              FieldRec->data().NeedOverloadResolutionForMoveConstructor;
1177
0
          data().NeedOverloadResolutionForCopyAssignment |=
1178
0
              FieldRec->data().NeedOverloadResolutionForCopyAssignment;
1179
0
          data().NeedOverloadResolutionForMoveAssignment |=
1180
0
              FieldRec->data().NeedOverloadResolutionForMoveAssignment;
1181
0
          data().NeedOverloadResolutionForDestructor |=
1182
0
              FieldRec->data().NeedOverloadResolutionForDestructor;
1183
0
        }
1184
1185
        // C++0x [class.ctor]p5:
1186
        //   A default constructor is trivial [...] if:
1187
        //    -- for all the non-static data members of its class that are of
1188
        //       class type (or array thereof), each such class has a trivial
1189
        //       default constructor.
1190
0
        if (!FieldRec->hasTrivialDefaultConstructor())
1191
0
          data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1192
1193
        // C++0x [class.copy]p13:
1194
        //   A copy/move constructor for class X is trivial if [...]
1195
        //    [...]
1196
        //    -- for each non-static data member of X that is of class type (or
1197
        //       an array thereof), the constructor selected to copy/move that
1198
        //       member is trivial;
1199
0
        if (!FieldRec->hasTrivialCopyConstructor())
1200
0
          data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
1201
1202
0
        if (!FieldRec->hasTrivialCopyConstructorForCall())
1203
0
          data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
1204
1205
        // If the field doesn't have a simple move constructor, we'll eagerly
1206
        // declare the move constructor for this class and we'll decide whether
1207
        // it's trivial then.
1208
0
        if (!FieldRec->hasTrivialMoveConstructor())
1209
0
          data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
1210
1211
0
        if (!FieldRec->hasTrivialMoveConstructorForCall())
1212
0
          data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
1213
1214
        // C++0x [class.copy]p27:
1215
        //   A copy/move assignment operator for class X is trivial if [...]
1216
        //    [...]
1217
        //    -- for each non-static data member of X that is of class type (or
1218
        //       an array thereof), the assignment operator selected to
1219
        //       copy/move that member is trivial;
1220
0
        if (!FieldRec->hasTrivialCopyAssignment())
1221
0
          data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
1222
        // If the field doesn't have a simple move assignment, we'll eagerly
1223
        // declare the move assignment for this class and we'll decide whether
1224
        // it's trivial then.
1225
0
        if (!FieldRec->hasTrivialMoveAssignment())
1226
0
          data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
1227
1228
0
        if (!FieldRec->hasTrivialDestructor())
1229
0
          data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1230
0
        if (!FieldRec->hasTrivialDestructorForCall())
1231
0
          data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1232
0
        if (!FieldRec->hasIrrelevantDestructor())
1233
0
          data().HasIrrelevantDestructor = false;
1234
0
        if (FieldRec->isAnyDestructorNoReturn())
1235
0
          data().IsAnyDestructorNoReturn = true;
1236
0
        if (FieldRec->hasObjectMember())
1237
0
          setHasObjectMember(true);
1238
0
        if (FieldRec->hasVolatileMember())
1239
0
          setHasVolatileMember(true);
1240
0
        if (FieldRec->getArgPassingRestrictions() ==
1241
0
            RecordArgPassingKind::CanNeverPassInRegs)
1242
0
          setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
1243
1244
        // C++0x [class]p7:
1245
        //   A standard-layout class is a class that:
1246
        //    -- has no non-static data members of type non-standard-layout
1247
        //       class (or array of such types) [...]
1248
0
        if (!FieldRec->isStandardLayout())
1249
0
          data().IsStandardLayout = false;
1250
0
        if (!FieldRec->isCXX11StandardLayout())
1251
0
          data().IsCXX11StandardLayout = false;
1252
1253
        // C++2a [class]p7:
1254
        //   A standard-layout class is a class that:
1255
        //    [...]
1256
        //    -- has no element of the set M(S) of types as a base class.
1257
0
        if (data().IsStandardLayout &&
1258
0
            (isUnion() || IsFirstField || IsZeroSize) &&
1259
0
            hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))
1260
0
          data().IsStandardLayout = false;
1261
1262
        // C++11 [class]p7:
1263
        //   A standard-layout class is a class that:
1264
        //    -- has no base classes of the same type as the first non-static
1265
        //       data member
1266
0
        if (data().IsCXX11StandardLayout && IsFirstField) {
1267
          // FIXME: We should check all base classes here, not just direct
1268
          // base classes.
1269
0
          for (const auto &BI : bases()) {
1270
0
            if (Context.hasSameUnqualifiedType(BI.getType(), T)) {
1271
0
              data().IsCXX11StandardLayout = false;
1272
0
              break;
1273
0
            }
1274
0
          }
1275
0
        }
1276
1277
        // Keep track of the presence of mutable fields.
1278
0
        if (FieldRec->hasMutableFields())
1279
0
          data().HasMutableFields = true;
1280
1281
0
        if (Field->isMutable()) {
1282
          // Our copy constructor/assignment might call something other than
1283
          // the subobject's copy constructor/assignment if it's mutable and of
1284
          // class type.
1285
0
          data().NeedOverloadResolutionForCopyConstructor = true;
1286
0
          data().NeedOverloadResolutionForCopyAssignment = true;
1287
0
        }
1288
1289
        // C++11 [class.copy]p13:
1290
        //   If the implicitly-defined constructor would satisfy the
1291
        //   requirements of a constexpr constructor, the implicitly-defined
1292
        //   constructor is constexpr.
1293
        // C++11 [dcl.constexpr]p4:
1294
        //    -- every constructor involved in initializing non-static data
1295
        //       members [...] shall be a constexpr constructor
1296
0
        if (!Field->hasInClassInitializer() &&
1297
0
            !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
1298
          // The standard requires any in-class initializer to be a constant
1299
          // expression. We consider this to be a defect.
1300
0
          data().DefaultedDefaultConstructorIsConstexpr = false;
1301
1302
        // C++11 [class.copy]p8:
1303
        //   The implicitly-declared copy constructor for a class X will have
1304
        //   the form 'X::X(const X&)' if each potentially constructed subobject
1305
        //   of a class type M (or array thereof) has a copy constructor whose
1306
        //   first parameter is of type 'const M&' or 'const volatile M&'.
1307
0
        if (!FieldRec->hasCopyConstructorWithConstParam())
1308
0
          data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
1309
1310
        // C++11 [class.copy]p18:
1311
        //   The implicitly-declared copy assignment oeprator for a class X will
1312
        //   have the form 'X& X::operator=(const X&)' if [...] for all the
1313
        //   non-static data members of X that are of a class type M (or array
1314
        //   thereof), each such class type has a copy assignment operator whose
1315
        //   parameter is of type 'const M&', 'const volatile M&' or 'M'.
1316
0
        if (!FieldRec->hasCopyAssignmentWithConstParam())
1317
0
          data().ImplicitCopyAssignmentHasConstParam = false;
1318
1319
0
        if (FieldRec->hasUninitializedReferenceMember() &&
1320
0
            !Field->hasInClassInitializer())
1321
0
          data().HasUninitializedReferenceMember = true;
1322
1323
        // C++11 [class.union]p8, DR1460:
1324
        //   a non-static data member of an anonymous union that is a member of
1325
        //   X is also a variant member of X.
1326
0
        if (FieldRec->hasVariantMembers() &&
1327
0
            Field->isAnonymousStructOrUnion())
1328
0
          data().HasVariantMembers = true;
1329
0
      }
1330
184
    } else {
1331
      // Base element type of field is a non-class type.
1332
184
      if (!T->isLiteralType(Context) ||
1333
184
          (!Field->hasInClassInitializer() && !isUnion() &&
1334
184
           !Context.getLangOpts().CPlusPlus20))
1335
184
        data().DefaultedDefaultConstructorIsConstexpr = false;
1336
1337
      // C++11 [class.copy]p23:
1338
      //   A defaulted copy/move assignment operator for a class X is defined
1339
      //   as deleted if X has:
1340
      //    -- a non-static data member of const non-class type (or array
1341
      //       thereof)
1342
184
      if (T.isConstQualified()) {
1343
0
        data().DefaultedCopyAssignmentIsDeleted = true;
1344
0
        data().DefaultedMoveAssignmentIsDeleted = true;
1345
0
      }
1346
1347
      // C++20 [temp.param]p7:
1348
      //   A structural type is [...] a literal class type [for which] the
1349
      //   types of all non-static data members are structural types or
1350
      //   (possibly multidimensional) array thereof
1351
      // We deal with class types elsewhere.
1352
184
      if (!T->isStructuralType())
1353
0
        data().StructuralIfLiteral = false;
1354
184
    }
1355
1356
    // C++14 [meta.unary.prop]p4:
1357
    //   T is a class type [...] with [...] no non-static data members other
1358
    //   than subobjects of zero size
1359
184
    if (data().Empty && !IsZeroSize)
1360
46
      data().Empty = false;
1361
184
  }
1362
1363
  // Handle using declarations of conversion functions.
1364
184
  if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {
1365
0
    if (Shadow->getDeclName().getNameKind()
1366
0
          == DeclarationName::CXXConversionFunctionName) {
1367
0
      ASTContext &Ctx = getASTContext();
1368
0
      data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());
1369
0
    }
1370
0
  }
1371
1372
184
  if (const auto *Using = dyn_cast<UsingDecl>(D)) {
1373
0
    if (Using->getDeclName().getNameKind() ==
1374
0
        DeclarationName::CXXConstructorName) {
1375
0
      data().HasInheritedConstructor = true;
1376
      // C++1z [dcl.init.aggr]p1:
1377
      //  An aggregate is [...] a class [...] with no inherited constructors
1378
0
      data().Aggregate = false;
1379
0
    }
1380
1381
0
    if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)
1382
0
      data().HasInheritedAssignment = true;
1383
0
  }
1384
184
}
1385
1386
0
bool CXXRecordDecl::isLiteral() const {
1387
0
  const LangOptions &LangOpts = getLangOpts();
1388
0
  if (!(LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1389
0
                             : hasTrivialDestructor()))
1390
0
    return false;
1391
1392
0
  if (hasNonLiteralTypeFieldsOrBases()) {
1393
    // CWG2598
1394
    // is an aggregate union type that has either no variant
1395
    // members or at least one variant member of non-volatile literal type,
1396
0
    if (!isUnion())
1397
0
      return false;
1398
0
    bool HasAtLeastOneLiteralMember =
1399
0
        fields().empty() || any_of(fields(), [this](const FieldDecl *D) {
1400
0
          return !D->getType().isVolatileQualified() &&
1401
0
                 D->getType()->isLiteralType(getASTContext());
1402
0
        });
1403
0
    if (!HasAtLeastOneLiteralMember)
1404
0
      return false;
1405
0
  }
1406
1407
0
  return isAggregate() || (isLambda() && LangOpts.CPlusPlus17) ||
1408
0
         hasConstexprNonCopyMoveConstructor() || hasTrivialDefaultConstructor();
1409
0
}
1410
1411
0
void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) {
1412
0
  DD->setIneligibleOrNotSelected(false);
1413
0
  addedEligibleSpecialMemberFunction(DD, SMF_Destructor);
1414
0
}
1415
1416
void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD,
1417
0
                                                       unsigned SMKind) {
1418
  // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is
1419
  // a function template, but this needs CWG attention before we break ABI.
1420
  // See https://github.com/llvm/llvm-project/issues/59206
1421
1422
0
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1423
0
    if (DD->isUserProvided())
1424
0
      data().HasIrrelevantDestructor = false;
1425
    // If the destructor is explicitly defaulted and not trivial or not public
1426
    // or if the destructor is deleted, we clear HasIrrelevantDestructor in
1427
    // finishedDefaultedOrDeletedMember.
1428
1429
    // C++11 [class.dtor]p5:
1430
    //   A destructor is trivial if [...] the destructor is not virtual.
1431
0
    if (DD->isVirtual()) {
1432
0
      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1433
0
      data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1434
0
    }
1435
1436
0
    if (DD->isNoReturn())
1437
0
      data().IsAnyDestructorNoReturn = true;
1438
0
  }
1439
1440
0
  if (!MD->isImplicit() && !MD->isUserProvided()) {
1441
    // This method is user-declared but not user-provided. We can't work
1442
    // out whether it's trivial yet (not until we get to the end of the
1443
    // class). We'll handle this method in
1444
    // finishedDefaultedOrDeletedMember.
1445
0
  } else if (MD->isTrivial()) {
1446
0
    data().HasTrivialSpecialMembers |= SMKind;
1447
0
    data().HasTrivialSpecialMembersForCall |= SMKind;
1448
0
  } else if (MD->isTrivialForCall()) {
1449
0
    data().HasTrivialSpecialMembersForCall |= SMKind;
1450
0
    data().DeclaredNonTrivialSpecialMembers |= SMKind;
1451
0
  } else {
1452
0
    data().DeclaredNonTrivialSpecialMembers |= SMKind;
1453
    // If this is a user-provided function, do not set
1454
    // DeclaredNonTrivialSpecialMembersForCall here since we don't know
1455
    // yet whether the method would be considered non-trivial for the
1456
    // purpose of calls (attribute "trivial_abi" can be dropped from the
1457
    // class later, which can change the special method's triviality).
1458
0
    if (!MD->isUserProvided())
1459
0
      data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1460
0
  }
1461
0
}
1462
1463
0
void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
1464
0
  assert(!D->isImplicit() && !D->isUserProvided());
1465
1466
  // The kind of special member this declaration is, if any.
1467
0
  unsigned SMKind = 0;
1468
1469
0
  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1470
0
    if (Constructor->isDefaultConstructor()) {
1471
0
      SMKind |= SMF_DefaultConstructor;
1472
0
      if (Constructor->isConstexpr())
1473
0
        data().HasConstexprDefaultConstructor = true;
1474
0
    }
1475
0
    if (Constructor->isCopyConstructor())
1476
0
      SMKind |= SMF_CopyConstructor;
1477
0
    else if (Constructor->isMoveConstructor())
1478
0
      SMKind |= SMF_MoveConstructor;
1479
0
    else if (Constructor->isConstexpr())
1480
      // We may now know that the constructor is constexpr.
1481
0
      data().HasConstexprNonCopyMoveConstructor = true;
1482
0
  } else if (isa<CXXDestructorDecl>(D)) {
1483
0
    SMKind |= SMF_Destructor;
1484
0
    if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())
1485
0
      data().HasIrrelevantDestructor = false;
1486
0
  } else if (D->isCopyAssignmentOperator())
1487
0
    SMKind |= SMF_CopyAssignment;
1488
0
  else if (D->isMoveAssignmentOperator())
1489
0
    SMKind |= SMF_MoveAssignment;
1490
1491
  // Update which trivial / non-trivial special members we have.
1492
  // addedMember will have skipped this step for this member.
1493
0
  if (!D->isIneligibleOrNotSelected()) {
1494
0
    if (D->isTrivial())
1495
0
      data().HasTrivialSpecialMembers |= SMKind;
1496
0
    else
1497
0
      data().DeclaredNonTrivialSpecialMembers |= SMKind;
1498
0
  }
1499
0
}
1500
1501
void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx,
1502
0
                                                         Capture *CaptureList) {
1503
0
  Captures.push_back(CaptureList);
1504
0
  if (Captures.size() == 2) {
1505
    // The TinyPtrVector member now needs destruction.
1506
0
    Ctx.addDestruction(&Captures);
1507
0
  }
1508
0
}
1509
1510
void CXXRecordDecl::setCaptures(ASTContext &Context,
1511
0
                                ArrayRef<LambdaCapture> Captures) {
1512
0
  CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();
1513
1514
  // Copy captures.
1515
0
  Data.NumCaptures = Captures.size();
1516
0
  Data.NumExplicitCaptures = 0;
1517
0
  auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *
1518
0
                                                      Captures.size());
1519
0
  Data.AddCaptureList(Context, ToCapture);
1520
0
  for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
1521
0
    if (Captures[I].isExplicit())
1522
0
      ++Data.NumExplicitCaptures;
1523
1524
0
    new (ToCapture) LambdaCapture(Captures[I]);
1525
0
    ToCapture++;
1526
0
  }
1527
1528
0
  if (!lambdaIsDefaultConstructibleAndAssignable())
1529
0
    Data.DefaultedCopyAssignmentIsDeleted = true;
1530
0
}
1531
1532
0
void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {
1533
0
  unsigned SMKind = 0;
1534
1535
0
  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1536
0
    if (Constructor->isCopyConstructor())
1537
0
      SMKind = SMF_CopyConstructor;
1538
0
    else if (Constructor->isMoveConstructor())
1539
0
      SMKind = SMF_MoveConstructor;
1540
0
  } else if (isa<CXXDestructorDecl>(D))
1541
0
    SMKind = SMF_Destructor;
1542
1543
0
  if (D->isTrivialForCall())
1544
0
    data().HasTrivialSpecialMembersForCall |= SMKind;
1545
0
  else
1546
0
    data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1547
0
}
1548
1549
0
bool CXXRecordDecl::isCLike() const {
1550
0
  if (getTagKind() == TagTypeKind::Class ||
1551
0
      getTagKind() == TagTypeKind::Interface ||
1552
0
      !TemplateOrInstantiation.isNull())
1553
0
    return false;
1554
0
  if (!hasDefinition())
1555
0
    return true;
1556
1557
0
  return isPOD() && data().HasOnlyCMembers;
1558
0
}
1559
1560
0
bool CXXRecordDecl::isGenericLambda() const {
1561
0
  if (!isLambda()) return false;
1562
0
  return getLambdaData().IsGenericLambda;
1563
0
}
1564
1565
#ifndef NDEBUG
1566
0
static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
1567
0
  for (auto *D : R)
1568
0
    if (!declaresSameEntity(D, R.front()))
1569
0
      return false;
1570
0
  return true;
1571
0
}
1572
#endif
1573
1574
0
static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {
1575
0
  if (!RD.isLambda()) return nullptr;
1576
0
  DeclarationName Name =
1577
0
    RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
1578
0
  DeclContext::lookup_result Calls = RD.lookup(Name);
1579
1580
0
  assert(!Calls.empty() && "Missing lambda call operator!");
1581
0
  assert(allLookupResultsAreTheSame(Calls) &&
1582
0
         "More than one lambda call operator!");
1583
0
  return Calls.front();
1584
0
}
1585
1586
0
FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
1587
0
  NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1588
0
  return  dyn_cast_or_null<FunctionTemplateDecl>(CallOp);
1589
0
}
1590
1591
0
CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {
1592
0
  NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1593
1594
0
  if (CallOp == nullptr)
1595
0
    return nullptr;
1596
1597
0
  if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))
1598
0
    return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());
1599
1600
0
  return cast<CXXMethodDecl>(CallOp);
1601
0
}
1602
1603
0
CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
1604
0
  CXXMethodDecl *CallOp = getLambdaCallOperator();
1605
0
  CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();
1606
0
  return getLambdaStaticInvoker(CC);
1607
0
}
1608
1609
static DeclContext::lookup_result
1610
0
getLambdaStaticInvokers(const CXXRecordDecl &RD) {
1611
0
  assert(RD.isLambda() && "Must be a lambda");
1612
0
  DeclarationName Name =
1613
0
      &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());
1614
0
  return RD.lookup(Name);
1615
0
}
1616
1617
0
static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {
1618
0
  if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND))
1619
0
    return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());
1620
0
  return cast<CXXMethodDecl>(ND);
1621
0
}
1622
1623
0
CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {
1624
0
  if (!isLambda())
1625
0
    return nullptr;
1626
0
  DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this);
1627
1628
0
  for (NamedDecl *ND : Invoker) {
1629
0
    const auto *FTy =
1630
0
        cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>();
1631
0
    if (FTy->getCallConv() == CC)
1632
0
      return getInvokerAsMethod(ND);
1633
0
  }
1634
1635
0
  return nullptr;
1636
0
}
1637
1638
void CXXRecordDecl::getCaptureFields(
1639
    llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,
1640
0
    FieldDecl *&ThisCapture) const {
1641
0
  Captures.clear();
1642
0
  ThisCapture = nullptr;
1643
1644
0
  LambdaDefinitionData &Lambda = getLambdaData();
1645
0
  for (const LambdaCapture *List : Lambda.Captures) {
1646
0
    RecordDecl::field_iterator Field = field_begin();
1647
0
    for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures;
1648
0
         C != CEnd; ++C, ++Field) {
1649
0
      if (C->capturesThis())
1650
0
        ThisCapture = *Field;
1651
0
      else if (C->capturesVariable())
1652
0
        Captures[C->getCapturedVar()] = *Field;
1653
0
    }
1654
0
    assert(Field == field_end());
1655
0
  }
1656
0
}
1657
1658
TemplateParameterList *
1659
0
CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
1660
0
  if (!isGenericLambda()) return nullptr;
1661
0
  CXXMethodDecl *CallOp = getLambdaCallOperator();
1662
0
  if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
1663
0
    return Tmpl->getTemplateParameters();
1664
0
  return nullptr;
1665
0
}
1666
1667
ArrayRef<NamedDecl *>
1668
0
CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
1669
0
  TemplateParameterList *List = getGenericLambdaTemplateParameterList();
1670
0
  if (!List)
1671
0
    return {};
1672
1673
0
  assert(std::is_partitioned(List->begin(), List->end(),
1674
0
                             [](const NamedDecl *D) { return !D->isImplicit(); })
1675
0
         && "Explicit template params should be ordered before implicit ones");
1676
1677
0
  const auto ExplicitEnd = llvm::partition_point(
1678
0
      *List, [](const NamedDecl *D) { return !D->isImplicit(); });
1679
0
  return llvm::ArrayRef(List->begin(), ExplicitEnd);
1680
0
}
1681
1682
0
Decl *CXXRecordDecl::getLambdaContextDecl() const {
1683
0
  assert(isLambda() && "Not a lambda closure type!");
1684
0
  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1685
0
  return getLambdaData().ContextDecl.get(Source);
1686
0
}
1687
1688
0
void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) {
1689
0
  assert(isLambda() && "Not a lambda closure type!");
1690
0
  getLambdaData().ManglingNumber = Numbering.ManglingNumber;
1691
0
  if (Numbering.DeviceManglingNumber)
1692
0
    getASTContext().DeviceLambdaManglingNumbers[this] =
1693
0
        Numbering.DeviceManglingNumber;
1694
0
  getLambdaData().IndexInContext = Numbering.IndexInContext;
1695
0
  getLambdaData().ContextDecl = Numbering.ContextDecl;
1696
0
  getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage;
1697
0
}
1698
1699
0
unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {
1700
0
  assert(isLambda() && "Not a lambda closure type!");
1701
0
  return getASTContext().DeviceLambdaManglingNumbers.lookup(this);
1702
0
}
1703
1704
0
static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1705
0
  QualType T =
1706
0
      cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())
1707
0
          ->getConversionType();
1708
0
  return Context.getCanonicalType(T);
1709
0
}
1710
1711
/// Collect the visible conversions of a base class.
1712
///
1713
/// \param Record a base class of the class we're considering
1714
/// \param InVirtual whether this base class is a virtual base (or a base
1715
///   of a virtual base)
1716
/// \param Access the access along the inheritance path to this base
1717
/// \param ParentHiddenTypes the conversions provided by the inheritors
1718
///   of this base
1719
/// \param Output the set to which to add conversions from non-virtual bases
1720
/// \param VOutput the set to which to add conversions from virtual bases
1721
/// \param HiddenVBaseCs the set of conversions which were hidden in a
1722
///   virtual base along some inheritance path
1723
static void CollectVisibleConversions(
1724
    ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,
1725
    AccessSpecifier Access,
1726
    const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1727
    ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,
1728
0
    llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {
1729
  // The set of types which have conversions in this class or its
1730
  // subclasses.  As an optimization, we don't copy the derived set
1731
  // unless it might change.
1732
0
  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1733
0
  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1734
1735
  // Collect the direct conversions and figure out which conversions
1736
  // will be hidden in the subclasses.
1737
0
  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1738
0
  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1739
0
  if (ConvI != ConvE) {
1740
0
    HiddenTypesBuffer = ParentHiddenTypes;
1741
0
    HiddenTypes = &HiddenTypesBuffer;
1742
1743
0
    for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
1744
0
      CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1745
0
      bool Hidden = ParentHiddenTypes.count(ConvType);
1746
0
      if (!Hidden)
1747
0
        HiddenTypesBuffer.insert(ConvType);
1748
1749
      // If this conversion is hidden and we're in a virtual base,
1750
      // remember that it's hidden along some inheritance path.
1751
0
      if (Hidden && InVirtual)
1752
0
        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1753
1754
      // If this conversion isn't hidden, add it to the appropriate output.
1755
0
      else if (!Hidden) {
1756
0
        AccessSpecifier IAccess
1757
0
          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1758
1759
0
        if (InVirtual)
1760
0
          VOutput.addDecl(I.getDecl(), IAccess);
1761
0
        else
1762
0
          Output.addDecl(Context, I.getDecl(), IAccess);
1763
0
      }
1764
0
    }
1765
0
  }
1766
1767
  // Collect information recursively from any base classes.
1768
0
  for (const auto &I : Record->bases()) {
1769
0
    const auto *RT = I.getType()->getAs<RecordType>();
1770
0
    if (!RT) continue;
1771
1772
0
    AccessSpecifier BaseAccess
1773
0
      = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());
1774
0
    bool BaseInVirtual = InVirtual || I.isVirtual();
1775
1776
0
    auto *Base = cast<CXXRecordDecl>(RT->getDecl());
1777
0
    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1778
0
                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1779
0
  }
1780
0
}
1781
1782
/// Collect the visible conversions of a class.
1783
///
1784
/// This would be extremely straightforward if it weren't for virtual
1785
/// bases.  It might be worth special-casing that, really.
1786
static void CollectVisibleConversions(ASTContext &Context,
1787
                                      const CXXRecordDecl *Record,
1788
0
                                      ASTUnresolvedSet &Output) {
1789
  // The collection of all conversions in virtual bases that we've
1790
  // found.  These will be added to the output as long as they don't
1791
  // appear in the hidden-conversions set.
1792
0
  UnresolvedSet<8> VBaseCs;
1793
1794
  // The set of conversions in virtual bases that we've determined to
1795
  // be hidden.
1796
0
  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1797
1798
  // The set of types hidden by classes derived from this one.
1799
0
  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1800
1801
  // Go ahead and collect the direct conversions and add them to the
1802
  // hidden-types set.
1803
0
  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1804
0
  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1805
0
  Output.append(Context, ConvI, ConvE);
1806
0
  for (; ConvI != ConvE; ++ConvI)
1807
0
    HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1808
1809
  // Recursively collect conversions from base classes.
1810
0
  for (const auto &I : Record->bases()) {
1811
0
    const auto *RT = I.getType()->getAs<RecordType>();
1812
0
    if (!RT) continue;
1813
1814
0
    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1815
0
                              I.isVirtual(), I.getAccessSpecifier(),
1816
0
                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1817
0
  }
1818
1819
  // Add any unhidden conversions provided by virtual bases.
1820
0
  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1821
0
         I != E; ++I) {
1822
0
    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1823
0
      Output.addDecl(Context, I.getDecl(), I.getAccess());
1824
0
  }
1825
0
}
1826
1827
/// getVisibleConversionFunctions - get all conversion functions visible
1828
/// in current class; including conversion function templates.
1829
llvm::iterator_range<CXXRecordDecl::conversion_iterator>
1830
0
CXXRecordDecl::getVisibleConversionFunctions() const {
1831
0
  ASTContext &Ctx = getASTContext();
1832
1833
0
  ASTUnresolvedSet *Set;
1834
0
  if (bases_begin() == bases_end()) {
1835
    // If root class, all conversions are visible.
1836
0
    Set = &data().Conversions.get(Ctx);
1837
0
  } else {
1838
0
    Set = &data().VisibleConversions.get(Ctx);
1839
    // If visible conversion list is not evaluated, evaluate it.
1840
0
    if (!data().ComputedVisibleConversions) {
1841
0
      CollectVisibleConversions(Ctx, this, *Set);
1842
0
      data().ComputedVisibleConversions = true;
1843
0
    }
1844
0
  }
1845
0
  return llvm::make_range(Set->begin(), Set->end());
1846
0
}
1847
1848
0
void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1849
  // This operation is O(N) but extremely rare.  Sema only uses it to
1850
  // remove UsingShadowDecls in a class that were followed by a direct
1851
  // declaration, e.g.:
1852
  //   class A : B {
1853
  //     using B::operator int;
1854
  //     operator int();
1855
  //   };
1856
  // This is uncommon by itself and even more uncommon in conjunction
1857
  // with sufficiently large numbers of directly-declared conversions
1858
  // that asymptotic behavior matters.
1859
1860
0
  ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());
1861
0
  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1862
0
    if (Convs[I].getDecl() == ConvDecl) {
1863
0
      Convs.erase(I);
1864
0
      assert(!llvm::is_contained(Convs, ConvDecl) &&
1865
0
             "conversion was found multiple times in unresolved set");
1866
0
      return;
1867
0
    }
1868
0
  }
1869
1870
0
  llvm_unreachable("conversion not found in set!");
1871
0
}
1872
1873
0
CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1874
0
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1875
0
    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1876
1877
0
  return nullptr;
1878
0
}
1879
1880
0
MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1881
0
  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1882
0
}
1883
1884
void
1885
CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1886
0
                                             TemplateSpecializationKind TSK) {
1887
0
  assert(TemplateOrInstantiation.isNull() &&
1888
0
         "Previous template or instantiation?");
1889
0
  assert(!isa<ClassTemplatePartialSpecializationDecl>(this));
1890
0
  TemplateOrInstantiation
1891
0
    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1892
0
}
1893
1894
4.72k
ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
1895
4.72k
  return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();
1896
4.72k
}
1897
1898
0
void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
1899
0
  TemplateOrInstantiation = Template;
1900
0
}
1901
1902
0
TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1903
0
  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))
1904
0
    return Spec->getSpecializationKind();
1905
1906
0
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1907
0
    return MSInfo->getTemplateSpecializationKind();
1908
1909
0
  return TSK_Undeclared;
1910
0
}
1911
1912
void
1913
0
CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1914
0
  if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1915
0
    Spec->setSpecializationKind(TSK);
1916
0
    return;
1917
0
  }
1918
1919
0
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1920
0
    MSInfo->setTemplateSpecializationKind(TSK);
1921
0
    return;
1922
0
  }
1923
1924
0
  llvm_unreachable("Not a class template or member class specialization");
1925
0
}
1926
1927
0
const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {
1928
0
  auto GetDefinitionOrSelf =
1929
0
      [](const CXXRecordDecl *D) -> const CXXRecordDecl * {
1930
0
    if (auto *Def = D->getDefinition())
1931
0
      return Def;
1932
0
    return D;
1933
0
  };
1934
1935
  // If it's a class template specialization, find the template or partial
1936
  // specialization from which it was instantiated.
1937
0
  if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1938
0
    auto From = TD->getInstantiatedFrom();
1939
0
    if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) {
1940
0
      while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
1941
0
        if (NewCTD->isMemberSpecialization())
1942
0
          break;
1943
0
        CTD = NewCTD;
1944
0
      }
1945
0
      return GetDefinitionOrSelf(CTD->getTemplatedDecl());
1946
0
    }
1947
0
    if (auto *CTPSD =
1948
0
            From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
1949
0
      while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
1950
0
        if (NewCTPSD->isMemberSpecialization())
1951
0
          break;
1952
0
        CTPSD = NewCTPSD;
1953
0
      }
1954
0
      return GetDefinitionOrSelf(CTPSD);
1955
0
    }
1956
0
  }
1957
1958
0
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1959
0
    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
1960
0
      const CXXRecordDecl *RD = this;
1961
0
      while (auto *NewRD = RD->getInstantiatedFromMemberClass())
1962
0
        RD = NewRD;
1963
0
      return GetDefinitionOrSelf(RD);
1964
0
    }
1965
0
  }
1966
1967
0
  assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&
1968
0
         "couldn't find pattern for class template instantiation");
1969
0
  return nullptr;
1970
0
}
1971
1972
0
CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1973
0
  ASTContext &Context = getASTContext();
1974
0
  QualType ClassType = Context.getTypeDeclType(this);
1975
1976
0
  DeclarationName Name
1977
0
    = Context.DeclarationNames.getCXXDestructorName(
1978
0
                                          Context.getCanonicalType(ClassType));
1979
1980
0
  DeclContext::lookup_result R = lookup(Name);
1981
1982
  // If a destructor was marked as not selected, we skip it. We don't always
1983
  // have a selected destructor: dependent types, unnamed structs.
1984
0
  for (auto *Decl : R) {
1985
0
    auto* DD = dyn_cast<CXXDestructorDecl>(Decl);
1986
0
    if (DD && !DD->isIneligibleOrNotSelected())
1987
0
      return DD;
1988
0
  }
1989
0
  return nullptr;
1990
0
}
1991
1992
0
static bool isDeclContextInNamespace(const DeclContext *DC) {
1993
0
  while (!DC->isTranslationUnit()) {
1994
0
    if (DC->isNamespace())
1995
0
      return true;
1996
0
    DC = DC->getParent();
1997
0
  }
1998
0
  return false;
1999
0
}
2000
2001
0
bool CXXRecordDecl::isInterfaceLike() const {
2002
0
  assert(hasDefinition() && "checking for interface-like without a definition");
2003
  // All __interfaces are inheritently interface-like.
2004
0
  if (isInterface())
2005
0
    return true;
2006
2007
  // Interface-like types cannot have a user declared constructor, destructor,
2008
  // friends, VBases, conversion functions, or fields.  Additionally, lambdas
2009
  // cannot be interface types.
2010
0
  if (isLambda() || hasUserDeclaredConstructor() ||
2011
0
      hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||
2012
0
      getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)
2013
0
    return false;
2014
2015
  // No interface-like type can have a method with a definition.
2016
0
  for (const auto *const Method : methods())
2017
0
    if (Method->isDefined() && !Method->isImplicit())
2018
0
      return false;
2019
2020
  // Check "Special" types.
2021
0
  const auto *Uuid = getAttr<UuidAttr>();
2022
  // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an
2023
  // extern C++ block directly in the TU.  These are only valid if in one
2024
  // of these two situations.
2025
0
  if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&
2026
0
      !isDeclContextInNamespace(getDeclContext()) &&
2027
0
      ((getName() == "IUnknown" &&
2028
0
        Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||
2029
0
       (getName() == "IDispatch" &&
2030
0
        Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {
2031
0
    if (getNumBases() > 0)
2032
0
      return false;
2033
0
    return true;
2034
0
  }
2035
2036
  // FIXME: Any access specifiers is supposed to make this no longer interface
2037
  // like.
2038
2039
  // If this isn't a 'special' type, it must have a single interface-like base.
2040
0
  if (getNumBases() != 1)
2041
0
    return false;
2042
2043
0
  const auto BaseSpec = *bases_begin();
2044
0
  if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)
2045
0
    return false;
2046
0
  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
2047
0
  if (Base->isInterface() || !Base->isInterfaceLike())
2048
0
    return false;
2049
0
  return true;
2050
0
}
2051
2052
46
void CXXRecordDecl::completeDefinition() {
2053
46
  completeDefinition(nullptr);
2054
46
}
2055
2056
46
void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
2057
46
  RecordDecl::completeDefinition();
2058
2059
  // If the class may be abstract (but hasn't been marked as such), check for
2060
  // any pure final overriders.
2061
46
  if (mayBeAbstract()) {
2062
0
    CXXFinalOverriderMap MyFinalOverriders;
2063
0
    if (!FinalOverriders) {
2064
0
      getFinalOverriders(MyFinalOverriders);
2065
0
      FinalOverriders = &MyFinalOverriders;
2066
0
    }
2067
2068
0
    bool Done = false;
2069
0
    for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
2070
0
                                     MEnd = FinalOverriders->end();
2071
0
         M != MEnd && !Done; ++M) {
2072
0
      for (OverridingMethods::iterator SO = M->second.begin(),
2073
0
                                    SOEnd = M->second.end();
2074
0
           SO != SOEnd && !Done; ++SO) {
2075
0
        assert(SO->second.size() > 0 &&
2076
0
               "All virtual functions have overriding virtual functions");
2077
2078
        // C++ [class.abstract]p4:
2079
        //   A class is abstract if it contains or inherits at least one
2080
        //   pure virtual function for which the final overrider is pure
2081
        //   virtual.
2082
0
        if (SO->second.front().Method->isPure()) {
2083
0
          data().Abstract = true;
2084
0
          Done = true;
2085
0
          break;
2086
0
        }
2087
0
      }
2088
0
    }
2089
0
  }
2090
2091
  // Set access bits correctly on the directly-declared conversions.
2092
46
  for (conversion_iterator I = conversion_begin(), E = conversion_end();
2093
46
       I != E; ++I)
2094
0
    I.setAccess((*I)->getAccess());
2095
46
}
2096
2097
46
bool CXXRecordDecl::mayBeAbstract() const {
2098
46
  if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
2099
46
      isDependentContext())
2100
46
    return false;
2101
2102
0
  for (const auto &B : bases()) {
2103
0
    const auto *BaseDecl =
2104
0
        cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());
2105
0
    if (BaseDecl->isAbstract())
2106
0
      return true;
2107
0
  }
2108
2109
0
  return false;
2110
0
}
2111
2112
0
bool CXXRecordDecl::isEffectivelyFinal() const {
2113
0
  auto *Def = getDefinition();
2114
0
  if (!Def)
2115
0
    return false;
2116
0
  if (Def->hasAttr<FinalAttr>())
2117
0
    return true;
2118
0
  if (const auto *Dtor = Def->getDestructor())
2119
0
    if (Dtor->hasAttr<FinalAttr>())
2120
0
      return true;
2121
0
  return false;
2122
0
}
2123
2124
0
void CXXDeductionGuideDecl::anchor() {}
2125
2126
0
bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {
2127
0
  if ((getKind() != Other.getKind() ||
2128
0
       getKind() == ExplicitSpecKind::Unresolved)) {
2129
0
    if (getKind() == ExplicitSpecKind::Unresolved &&
2130
0
        Other.getKind() == ExplicitSpecKind::Unresolved) {
2131
0
      ODRHash SelfHash, OtherHash;
2132
0
      SelfHash.AddStmt(getExpr());
2133
0
      OtherHash.AddStmt(Other.getExpr());
2134
0
      return SelfHash.CalculateHash() == OtherHash.CalculateHash();
2135
0
    } else
2136
0
      return false;
2137
0
  }
2138
0
  return true;
2139
0
}
2140
2141
0
ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {
2142
0
  switch (Function->getDeclKind()) {
2143
0
  case Decl::Kind::CXXConstructor:
2144
0
    return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();
2145
0
  case Decl::Kind::CXXConversion:
2146
0
    return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();
2147
0
  case Decl::Kind::CXXDeductionGuide:
2148
0
    return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();
2149
0
  default:
2150
0
    return {};
2151
0
  }
2152
0
}
2153
2154
CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(
2155
    ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2156
    ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2157
    TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor,
2158
0
    DeductionCandidate Kind) {
2159
0
  return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T,
2160
0
                                           TInfo, EndLocation, Ctor, Kind);
2161
0
}
2162
2163
CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C,
2164
0
                                                                 unsigned ID) {
2165
0
  return new (C, ID) CXXDeductionGuideDecl(
2166
0
      C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(),
2167
0
      QualType(), nullptr, SourceLocation(), nullptr,
2168
0
      DeductionCandidate::Normal);
2169
0
}
2170
2171
RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
2172
0
    ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
2173
0
  return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
2174
0
}
2175
2176
RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C,
2177
0
                                                               unsigned ID) {
2178
0
  return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
2179
0
}
2180
2181
0
void CXXMethodDecl::anchor() {}
2182
2183
0
bool CXXMethodDecl::isStatic() const {
2184
0
  const CXXMethodDecl *MD = getCanonicalDecl();
2185
2186
0
  if (MD->getStorageClass() == SC_Static)
2187
0
    return true;
2188
2189
0
  OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
2190
0
  return isStaticOverloadedOperator(OOK);
2191
0
}
2192
2193
static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
2194
0
                                 const CXXMethodDecl *BaseMD) {
2195
0
  for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {
2196
0
    if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
2197
0
      return true;
2198
0
    if (recursivelyOverrides(MD, BaseMD))
2199
0
      return true;
2200
0
  }
2201
0
  return false;
2202
0
}
2203
2204
CXXMethodDecl *
2205
CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2206
0
                                                     bool MayBeBase) {
2207
0
  if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
2208
0
    return this;
2209
2210
  // Lookup doesn't work for destructors, so handle them separately.
2211
0
  if (isa<CXXDestructorDecl>(this)) {
2212
0
    CXXMethodDecl *MD = RD->getDestructor();
2213
0
    if (MD) {
2214
0
      if (recursivelyOverrides(MD, this))
2215
0
        return MD;
2216
0
      if (MayBeBase && recursivelyOverrides(this, MD))
2217
0
        return MD;
2218
0
    }
2219
0
    return nullptr;
2220
0
  }
2221
2222
0
  for (auto *ND : RD->lookup(getDeclName())) {
2223
0
    auto *MD = dyn_cast<CXXMethodDecl>(ND);
2224
0
    if (!MD)
2225
0
      continue;
2226
0
    if (recursivelyOverrides(MD, this))
2227
0
      return MD;
2228
0
    if (MayBeBase && recursivelyOverrides(this, MD))
2229
0
      return MD;
2230
0
  }
2231
2232
0
  return nullptr;
2233
0
}
2234
2235
CXXMethodDecl *
2236
CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2237
0
                                             bool MayBeBase) {
2238
0
  if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))
2239
0
    return MD;
2240
2241
0
  llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;
2242
0
  auto AddFinalOverrider = [&](CXXMethodDecl *D) {
2243
    // If this function is overridden by a candidate final overrider, it is not
2244
    // a final overrider.
2245
0
    for (CXXMethodDecl *OtherD : FinalOverriders) {
2246
0
      if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))
2247
0
        return;
2248
0
    }
2249
2250
    // Other candidate final overriders might be overridden by this function.
2251
0
    llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) {
2252
0
      return recursivelyOverrides(D, OtherD);
2253
0
    });
2254
2255
0
    FinalOverriders.push_back(D);
2256
0
  };
2257
2258
0
  for (const auto &I : RD->bases()) {
2259
0
    const RecordType *RT = I.getType()->getAs<RecordType>();
2260
0
    if (!RT)
2261
0
      continue;
2262
0
    const auto *Base = cast<CXXRecordDecl>(RT->getDecl());
2263
0
    if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))
2264
0
      AddFinalOverrider(D);
2265
0
  }
2266
2267
0
  return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;
2268
0
}
2269
2270
CXXMethodDecl *
2271
CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2272
                      const DeclarationNameInfo &NameInfo, QualType T,
2273
                      TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
2274
                      bool isInline, ConstexprSpecKind ConstexprKind,
2275
                      SourceLocation EndLocation,
2276
0
                      Expr *TrailingRequiresClause) {
2277
0
  return new (C, RD) CXXMethodDecl(
2278
0
      CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
2279
0
      isInline, ConstexprKind, EndLocation, TrailingRequiresClause);
2280
0
}
2281
2282
0
CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2283
0
  return new (C, ID) CXXMethodDecl(
2284
0
      CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(),
2285
0
      QualType(), nullptr, SC_None, false, false,
2286
0
      ConstexprSpecKind::Unspecified, SourceLocation(), nullptr);
2287
0
}
2288
2289
CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
2290
0
                                                     bool IsAppleKext) {
2291
0
  assert(isVirtual() && "this method is expected to be virtual");
2292
2293
  // When building with -fapple-kext, all calls must go through the vtable since
2294
  // the kernel linker can do runtime patching of vtables.
2295
0
  if (IsAppleKext)
2296
0
    return nullptr;
2297
2298
  // If the member function is marked 'final', we know that it can't be
2299
  // overridden and can therefore devirtualize it unless it's pure virtual.
2300
0
  if (hasAttr<FinalAttr>())
2301
0
    return isPure() ? nullptr : this;
2302
2303
  // If Base is unknown, we cannot devirtualize.
2304
0
  if (!Base)
2305
0
    return nullptr;
2306
2307
  // If the base expression (after skipping derived-to-base conversions) is a
2308
  // class prvalue, then we can devirtualize.
2309
0
  Base = Base->getBestDynamicClassTypeExpr();
2310
0
  if (Base->isPRValue() && Base->getType()->isRecordType())
2311
0
    return this;
2312
2313
  // If we don't even know what we would call, we can't devirtualize.
2314
0
  const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2315
0
  if (!BestDynamicDecl)
2316
0
    return nullptr;
2317
2318
  // There may be a method corresponding to MD in a derived class.
2319
0
  CXXMethodDecl *DevirtualizedMethod =
2320
0
      getCorrespondingMethodInClass(BestDynamicDecl);
2321
2322
  // If there final overrider in the dynamic type is ambiguous, we can't
2323
  // devirtualize this call.
2324
0
  if (!DevirtualizedMethod)
2325
0
    return nullptr;
2326
2327
  // If that method is pure virtual, we can't devirtualize. If this code is
2328
  // reached, the result would be UB, not a direct call to the derived class
2329
  // function, and we can't assume the derived class function is defined.
2330
0
  if (DevirtualizedMethod->isPure())
2331
0
    return nullptr;
2332
2333
  // If that method is marked final, we can devirtualize it.
2334
0
  if (DevirtualizedMethod->hasAttr<FinalAttr>())
2335
0
    return DevirtualizedMethod;
2336
2337
  // Similarly, if the class itself or its destructor is marked 'final',
2338
  // the class can't be derived from and we can therefore devirtualize the
2339
  // member function call.
2340
0
  if (BestDynamicDecl->isEffectivelyFinal())
2341
0
    return DevirtualizedMethod;
2342
2343
0
  if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
2344
0
    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2345
0
      if (VD->getType()->isRecordType())
2346
        // This is a record decl. We know the type and can devirtualize it.
2347
0
        return DevirtualizedMethod;
2348
2349
0
    return nullptr;
2350
0
  }
2351
2352
  // We can devirtualize calls on an object accessed by a class member access
2353
  // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2354
  // a derived class object constructed in the same location.
2355
0
  if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
2356
0
    const ValueDecl *VD = ME->getMemberDecl();
2357
0
    return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
2358
0
  }
2359
2360
  // Likewise for calls on an object accessed by a (non-reference) pointer to
2361
  // member access.
2362
0
  if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2363
0
    if (BO->isPtrMemOp()) {
2364
0
      auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2365
0
      if (MPT->getPointeeType()->isRecordType())
2366
0
        return DevirtualizedMethod;
2367
0
    }
2368
0
  }
2369
2370
  // We can't devirtualize the call.
2371
0
  return nullptr;
2372
0
}
2373
2374
bool CXXMethodDecl::isUsualDeallocationFunction(
2375
0
    SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
2376
0
  assert(PreventedBy.empty() && "PreventedBy is expected to be empty");
2377
0
  if (getOverloadedOperator() != OO_Delete &&
2378
0
      getOverloadedOperator() != OO_Array_Delete)
2379
0
    return false;
2380
2381
  // C++ [basic.stc.dynamic.deallocation]p2:
2382
  //   A template instance is never a usual deallocation function,
2383
  //   regardless of its signature.
2384
0
  if (getPrimaryTemplate())
2385
0
    return false;
2386
2387
  // C++ [basic.stc.dynamic.deallocation]p2:
2388
  //   If a class T has a member deallocation function named operator delete
2389
  //   with exactly one parameter, then that function is a usual (non-placement)
2390
  //   deallocation function. [...]
2391
0
  if (getNumParams() == 1)
2392
0
    return true;
2393
0
  unsigned UsualParams = 1;
2394
2395
  // C++ P0722:
2396
  //   A destroying operator delete is a usual deallocation function if
2397
  //   removing the std::destroying_delete_t parameter and changing the
2398
  //   first parameter type from T* to void* results in the signature of
2399
  //   a usual deallocation function.
2400
0
  if (isDestroyingOperatorDelete())
2401
0
    ++UsualParams;
2402
2403
  // C++ <=14 [basic.stc.dynamic.deallocation]p2:
2404
  //   [...] If class T does not declare such an operator delete but does
2405
  //   declare a member deallocation function named operator delete with
2406
  //   exactly two parameters, the second of which has type std::size_t (18.1),
2407
  //   then this function is a usual deallocation function.
2408
  //
2409
  // C++17 says a usual deallocation function is one with the signature
2410
  //   (void* [, size_t] [, std::align_val_t] [, ...])
2411
  // and all such functions are usual deallocation functions. It's not clear
2412
  // that allowing varargs functions was intentional.
2413
0
  ASTContext &Context = getASTContext();
2414
0
  if (UsualParams < getNumParams() &&
2415
0
      Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),
2416
0
                                     Context.getSizeType()))
2417
0
    ++UsualParams;
2418
2419
0
  if (UsualParams < getNumParams() &&
2420
0
      getParamDecl(UsualParams)->getType()->isAlignValT())
2421
0
    ++UsualParams;
2422
2423
0
  if (UsualParams != getNumParams())
2424
0
    return false;
2425
2426
  // In C++17 onwards, all potential usual deallocation functions are actual
2427
  // usual deallocation functions. Honor this behavior when post-C++14
2428
  // deallocation functions are offered as extensions too.
2429
  // FIXME(EricWF): Destroying Delete should be a language option. How do we
2430
  // handle when destroying delete is used prior to C++17?
2431
0
  if (Context.getLangOpts().CPlusPlus17 ||
2432
0
      Context.getLangOpts().AlignedAllocation ||
2433
0
      isDestroyingOperatorDelete())
2434
0
    return true;
2435
2436
  // This function is a usual deallocation function if there are no
2437
  // single-parameter deallocation functions of the same kind.
2438
0
  DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
2439
0
  bool Result = true;
2440
0
  for (const auto *D : R) {
2441
0
    if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2442
0
      if (FD->getNumParams() == 1) {
2443
0
        PreventedBy.push_back(FD);
2444
0
        Result = false;
2445
0
      }
2446
0
    }
2447
0
  }
2448
0
  return Result;
2449
0
}
2450
2451
0
bool CXXMethodDecl::isExplicitObjectMemberFunction() const {
2452
  // C++2b [dcl.fct]p6:
2453
  // An explicit object member function is a non-static member
2454
  // function with an explicit object parameter
2455
0
  return !isStatic() && hasCXXExplicitFunctionObjectParameter();
2456
0
}
2457
2458
0
bool CXXMethodDecl::isImplicitObjectMemberFunction() const {
2459
0
  return !isStatic() && !hasCXXExplicitFunctionObjectParameter();
2460
0
}
2461
2462
0
bool CXXMethodDecl::isCopyAssignmentOperator() const {
2463
  // C++0x [class.copy]p17:
2464
  //  A user-declared copy assignment operator X::operator= is a non-static
2465
  //  non-template member function of class X with exactly one parameter of
2466
  //  type X, X&, const X&, volatile X& or const volatile X&.
2467
0
  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
2468
0
      /*non-static*/ isStatic() ||
2469
2470
0
      /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2471
0
      getNumExplicitParams() != 1)
2472
0
    return false;
2473
2474
0
  QualType ParamType = getNonObjectParameter(0)->getType();
2475
0
  if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
2476
0
    ParamType = Ref->getPointeeType();
2477
2478
0
  ASTContext &Context = getASTContext();
2479
0
  QualType ClassType
2480
0
    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2481
0
  return Context.hasSameUnqualifiedType(ClassType, ParamType);
2482
0
}
2483
2484
0
bool CXXMethodDecl::isMoveAssignmentOperator() const {
2485
  // C++0x [class.copy]p19:
2486
  //  A user-declared move assignment operator X::operator= is a non-static
2487
  //  non-template member function of class X with exactly one parameter of type
2488
  //  X&&, const X&&, volatile X&&, or const volatile X&&.
2489
0
  if (getOverloadedOperator() != OO_Equal || isStatic() ||
2490
0
      getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2491
0
      getNumExplicitParams() != 1)
2492
0
    return false;
2493
2494
0
  QualType ParamType = getNonObjectParameter(0)->getType();
2495
0
  if (!ParamType->isRValueReferenceType())
2496
0
    return false;
2497
0
  ParamType = ParamType->getPointeeType();
2498
2499
0
  ASTContext &Context = getASTContext();
2500
0
  QualType ClassType
2501
0
    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2502
0
  return Context.hasSameUnqualifiedType(ClassType, ParamType);
2503
0
}
2504
2505
0
void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
2506
0
  assert(MD->isCanonicalDecl() && "Method is not canonical!");
2507
0
  assert(!MD->getParent()->isDependentContext() &&
2508
0
         "Can't add an overridden method to a class template!");
2509
0
  assert(MD->isVirtual() && "Method is not virtual!");
2510
2511
0
  getASTContext().addOverriddenMethod(this, MD);
2512
0
}
2513
2514
0
CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
2515
0
  if (isa<CXXConstructorDecl>(this)) return nullptr;
2516
0
  return getASTContext().overridden_methods_begin(this);
2517
0
}
2518
2519
0
CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
2520
0
  if (isa<CXXConstructorDecl>(this)) return nullptr;
2521
0
  return getASTContext().overridden_methods_end(this);
2522
0
}
2523
2524
0
unsigned CXXMethodDecl::size_overridden_methods() const {
2525
0
  if (isa<CXXConstructorDecl>(this)) return 0;
2526
0
  return getASTContext().overridden_methods_size(this);
2527
0
}
2528
2529
CXXMethodDecl::overridden_method_range
2530
0
CXXMethodDecl::overridden_methods() const {
2531
0
  if (isa<CXXConstructorDecl>(this))
2532
0
    return overridden_method_range(nullptr, nullptr);
2533
0
  return getASTContext().overridden_methods(this);
2534
0
}
2535
2536
static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
2537
0
                                  const CXXRecordDecl *Decl) {
2538
0
  QualType ClassTy = C.getTypeDeclType(Decl);
2539
0
  return C.getQualifiedType(ClassTy, FPT->getMethodQuals());
2540
0
}
2541
2542
QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
2543
0
                                    const CXXRecordDecl *Decl) {
2544
0
  ASTContext &C = Decl->getASTContext();
2545
0
  QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
2546
0
  return C.getLangOpts().HLSL ? C.getLValueReferenceType(ObjectTy)
2547
0
                              : C.getPointerType(ObjectTy);
2548
0
}
2549
2550
0
QualType CXXMethodDecl::getThisType() const {
2551
  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
2552
  // If the member function is declared const, the type of this is const X*,
2553
  // if the member function is declared volatile, the type of this is
2554
  // volatile X*, and if the member function is declared const volatile,
2555
  // the type of this is const volatile X*.
2556
0
  assert(isInstance() && "No 'this' for static methods!");
2557
0
  return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
2558
0
                                    getParent());
2559
0
}
2560
2561
0
QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const {
2562
0
  if (isExplicitObjectMemberFunction())
2563
0
    return parameters()[0]->getType();
2564
2565
0
  ASTContext &C = getParentASTContext();
2566
0
  const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2567
0
  QualType Type = ::getThisObjectType(C, FPT, getParent());
2568
0
  RefQualifierKind RK = FPT->getRefQualifier();
2569
0
  if (RK == RefQualifierKind::RQ_RValue)
2570
0
    return C.getRValueReferenceType(Type);
2571
0
  return C.getLValueReferenceType(Type);
2572
0
}
2573
2574
0
bool CXXMethodDecl::hasInlineBody() const {
2575
  // If this function is a template instantiation, look at the template from
2576
  // which it was instantiated.
2577
0
  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
2578
0
  if (!CheckFn)
2579
0
    CheckFn = this;
2580
2581
0
  const FunctionDecl *fn;
2582
0
  return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&
2583
0
         (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
2584
0
}
2585
2586
0
bool CXXMethodDecl::isLambdaStaticInvoker() const {
2587
0
  const CXXRecordDecl *P = getParent();
2588
0
  return P->isLambda() && getDeclName().isIdentifier() &&
2589
0
         getName() == getLambdaStaticInvokerName();
2590
0
}
2591
2592
CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2593
                                       TypeSourceInfo *TInfo, bool IsVirtual,
2594
                                       SourceLocation L, Expr *Init,
2595
                                       SourceLocation R,
2596
                                       SourceLocation EllipsisLoc)
2597
    : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),
2598
      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
2599
0
      IsWritten(false), SourceOrder(0) {}
2600
2601
CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2602
                                       SourceLocation MemberLoc,
2603
                                       SourceLocation L, Expr *Init,
2604
                                       SourceLocation R)
2605
    : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2606
      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2607
0
      IsWritten(false), SourceOrder(0) {}
2608
2609
CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2610
                                       IndirectFieldDecl *Member,
2611
                                       SourceLocation MemberLoc,
2612
                                       SourceLocation L, Expr *Init,
2613
                                       SourceLocation R)
2614
    : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2615
      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2616
0
      IsWritten(false), SourceOrder(0) {}
2617
2618
CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2619
                                       TypeSourceInfo *TInfo,
2620
                                       SourceLocation L, Expr *Init,
2621
                                       SourceLocation R)
2622
    : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
2623
0
      IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
2624
2625
0
int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
2626
0
  return Context.getAllocator()
2627
0
                .identifyKnownAlignedObject<CXXCtorInitializer>(this);
2628
0
}
2629
2630
0
TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
2631
0
  if (isBaseInitializer())
2632
0
    return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
2633
0
  else
2634
0
    return {};
2635
0
}
2636
2637
0
const Type *CXXCtorInitializer::getBaseClass() const {
2638
0
  if (isBaseInitializer())
2639
0
    return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
2640
0
  else
2641
0
    return nullptr;
2642
0
}
2643
2644
0
SourceLocation CXXCtorInitializer::getSourceLocation() const {
2645
0
  if (isInClassMemberInitializer())
2646
0
    return getAnyMember()->getLocation();
2647
2648
0
  if (isAnyMemberInitializer())
2649
0
    return getMemberLocation();
2650
2651
0
  if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())
2652
0
    return TSInfo->getTypeLoc().getBeginLoc();
2653
2654
0
  return {};
2655
0
}
2656
2657
0
SourceRange CXXCtorInitializer::getSourceRange() const {
2658
0
  if (isInClassMemberInitializer()) {
2659
0
    FieldDecl *D = getAnyMember();
2660
0
    if (Expr *I = D->getInClassInitializer())
2661
0
      return I->getSourceRange();
2662
0
    return {};
2663
0
  }
2664
2665
0
  return SourceRange(getSourceLocation(), getRParenLoc());
2666
0
}
2667
2668
CXXConstructorDecl::CXXConstructorDecl(
2669
    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2670
    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2671
    ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2672
    bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2673
    InheritedConstructor Inherited, Expr *TrailingRequiresClause)
2674
    : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2675
                    SC_None, UsesFPIntrin, isInline, ConstexprKind,
2676
0
                    SourceLocation(), TrailingRequiresClause) {
2677
0
  setNumCtorInitializers(0);
2678
0
  setInheritingConstructor(static_cast<bool>(Inherited));
2679
0
  setImplicit(isImplicitlyDeclared);
2680
0
  CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
2681
0
  if (Inherited)
2682
0
    *getTrailingObjects<InheritedConstructor>() = Inherited;
2683
0
  setExplicitSpecifier(ES);
2684
0
}
2685
2686
0
void CXXConstructorDecl::anchor() {}
2687
2688
CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
2689
                                                           unsigned ID,
2690
0
                                                           uint64_t AllocKind) {
2691
0
  bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
2692
0
  bool isInheritingConstructor =
2693
0
      static_cast<bool>(AllocKind & TAKInheritsConstructor);
2694
0
  unsigned Extra =
2695
0
      additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2696
0
          isInheritingConstructor, hasTrailingExplicit);
2697
0
  auto *Result = new (C, ID, Extra) CXXConstructorDecl(
2698
0
      C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2699
0
      ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,
2700
0
      InheritedConstructor(), nullptr);
2701
0
  Result->setInheritingConstructor(isInheritingConstructor);
2702
0
  Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
2703
0
      hasTrailingExplicit;
2704
0
  Result->setExplicitSpecifier(ExplicitSpecifier());
2705
0
  return Result;
2706
0
}
2707
2708
CXXConstructorDecl *CXXConstructorDecl::Create(
2709
    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2710
    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2711
    ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2712
    bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2713
0
    InheritedConstructor Inherited, Expr *TrailingRequiresClause) {
2714
0
  assert(NameInfo.getName().getNameKind()
2715
0
         == DeclarationName::CXXConstructorName &&
2716
0
         "Name must refer to a constructor");
2717
0
  unsigned Extra =
2718
0
      additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2719
0
          Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);
2720
0
  return new (C, RD, Extra) CXXConstructorDecl(
2721
0
      C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,
2722
0
      isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);
2723
0
}
2724
2725
0
CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
2726
0
  return CtorInitializers.get(getASTContext().getExternalSource());
2727
0
}
2728
2729
0
CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
2730
0
  assert(isDelegatingConstructor() && "Not a delegating constructor!");
2731
0
  Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
2732
0
  if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
2733
0
    return Construct->getConstructor();
2734
2735
0
  return nullptr;
2736
0
}
2737
2738
0
bool CXXConstructorDecl::isDefaultConstructor() const {
2739
  // C++ [class.default.ctor]p1:
2740
  //   A default constructor for a class X is a constructor of class X for
2741
  //   which each parameter that is not a function parameter pack has a default
2742
  //   argument (including the case of a constructor with no parameters)
2743
0
  return getMinRequiredArguments() == 0;
2744
0
}
2745
2746
bool
2747
0
CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
2748
0
  return isCopyOrMoveConstructor(TypeQuals) &&
2749
0
         getParamDecl(0)->getType()->isLValueReferenceType();
2750
0
}
2751
2752
0
bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
2753
0
  return isCopyOrMoveConstructor(TypeQuals) &&
2754
0
         getParamDecl(0)->getType()->isRValueReferenceType();
2755
0
}
2756
2757
/// Determine whether this is a copy or move constructor.
2758
0
bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
2759
  // C++ [class.copy]p2:
2760
  //   A non-template constructor for class X is a copy constructor
2761
  //   if its first parameter is of type X&, const X&, volatile X& or
2762
  //   const volatile X&, and either there are no other parameters
2763
  //   or else all other parameters have default arguments (8.3.6).
2764
  // C++0x [class.copy]p3:
2765
  //   A non-template constructor for class X is a move constructor if its
2766
  //   first parameter is of type X&&, const X&&, volatile X&&, or
2767
  //   const volatile X&&, and either there are no other parameters or else
2768
  //   all other parameters have default arguments.
2769
0
  if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
2770
0
      getDescribedFunctionTemplate() != nullptr)
2771
0
    return false;
2772
2773
0
  const ParmVarDecl *Param = getParamDecl(0);
2774
2775
  // Do we have a reference type?
2776
0
  const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
2777
0
  if (!ParamRefType)
2778
0
    return false;
2779
2780
  // Is it a reference to our class type?
2781
0
  ASTContext &Context = getASTContext();
2782
2783
0
  CanQualType PointeeType
2784
0
    = Context.getCanonicalType(ParamRefType->getPointeeType());
2785
0
  CanQualType ClassTy
2786
0
    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2787
0
  if (PointeeType.getUnqualifiedType() != ClassTy)
2788
0
    return false;
2789
2790
  // FIXME: other qualifiers?
2791
2792
  // We have a copy or move constructor.
2793
0
  TypeQuals = PointeeType.getCVRQualifiers();
2794
0
  return true;
2795
0
}
2796
2797
0
bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
2798
  // C++ [class.conv.ctor]p1:
2799
  //   A constructor declared without the function-specifier explicit
2800
  //   that can be called with a single parameter specifies a
2801
  //   conversion from the type of its first parameter to the type of
2802
  //   its class. Such a constructor is called a converting
2803
  //   constructor.
2804
0
  if (isExplicit() && !AllowExplicit)
2805
0
    return false;
2806
2807
  // FIXME: This has nothing to do with the definition of converting
2808
  // constructor, but is convenient for how we use this function in overload
2809
  // resolution.
2810
0
  return getNumParams() == 0
2811
0
             ? getType()->castAs<FunctionProtoType>()->isVariadic()
2812
0
             : getMinRequiredArguments() <= 1;
2813
0
}
2814
2815
0
bool CXXConstructorDecl::isSpecializationCopyingObject() const {
2816
0
  if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
2817
0
    return false;
2818
2819
0
  const ParmVarDecl *Param = getParamDecl(0);
2820
2821
0
  ASTContext &Context = getASTContext();
2822
0
  CanQualType ParamType = Context.getCanonicalType(Param->getType());
2823
2824
  // Is it the same as our class type?
2825
0
  CanQualType ClassTy
2826
0
    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2827
0
  if (ParamType.getUnqualifiedType() != ClassTy)
2828
0
    return false;
2829
2830
0
  return true;
2831
0
}
2832
2833
0
void CXXDestructorDecl::anchor() {}
2834
2835
CXXDestructorDecl *
2836
0
CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2837
0
  return new (C, ID) CXXDestructorDecl(
2838
0
      C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2839
0
      false, false, false, ConstexprSpecKind::Unspecified, nullptr);
2840
0
}
2841
2842
CXXDestructorDecl *CXXDestructorDecl::Create(
2843
    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2844
    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2845
    bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
2846
0
    ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) {
2847
0
  assert(NameInfo.getName().getNameKind()
2848
0
         == DeclarationName::CXXDestructorName &&
2849
0
         "Name must refer to a destructor");
2850
0
  return new (C, RD) CXXDestructorDecl(
2851
0
      C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,
2852
0
      isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);
2853
0
}
2854
2855
0
void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
2856
0
  auto *First = cast<CXXDestructorDecl>(getFirstDecl());
2857
0
  if (OD && !First->OperatorDelete) {
2858
0
    First->OperatorDelete = OD;
2859
0
    First->OperatorDeleteThisArg = ThisArg;
2860
0
    if (auto *L = getASTMutationListener())
2861
0
      L->ResolvedOperatorDelete(First, OD, ThisArg);
2862
0
  }
2863
0
}
2864
2865
0
void CXXConversionDecl::anchor() {}
2866
2867
CXXConversionDecl *
2868
0
CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2869
0
  return new (C, ID) CXXConversionDecl(
2870
0
      C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2871
0
      false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
2872
0
      SourceLocation(), nullptr);
2873
0
}
2874
2875
CXXConversionDecl *CXXConversionDecl::Create(
2876
    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2877
    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2878
    bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
2879
    ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2880
0
    Expr *TrailingRequiresClause) {
2881
0
  assert(NameInfo.getName().getNameKind()
2882
0
         == DeclarationName::CXXConversionFunctionName &&
2883
0
         "Name must refer to a conversion function");
2884
0
  return new (C, RD) CXXConversionDecl(
2885
0
      C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,
2886
0
      ConstexprKind, EndLocation, TrailingRequiresClause);
2887
0
}
2888
2889
0
bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
2890
0
  return isImplicit() && getParent()->isLambda() &&
2891
0
         getConversionType()->isBlockPointerType();
2892
0
}
2893
2894
LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2895
                                 SourceLocation LangLoc,
2896
                                 LinkageSpecLanguageIDs lang, bool HasBraces)
2897
    : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2898
0
      ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
2899
0
  setLanguage(lang);
2900
0
  LinkageSpecDeclBits.HasBraces = HasBraces;
2901
0
}
2902
2903
0
void LinkageSpecDecl::anchor() {}
2904
2905
LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC,
2906
                                         SourceLocation ExternLoc,
2907
                                         SourceLocation LangLoc,
2908
                                         LinkageSpecLanguageIDs Lang,
2909
0
                                         bool HasBraces) {
2910
0
  return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
2911
0
}
2912
2913
LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
2914
0
                                                     unsigned ID) {
2915
0
  return new (C, ID)
2916
0
      LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(),
2917
0
                      LinkageSpecLanguageIDs::C, false);
2918
0
}
2919
2920
0
void UsingDirectiveDecl::anchor() {}
2921
2922
UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
2923
                                               SourceLocation L,
2924
                                               SourceLocation NamespaceLoc,
2925
                                           NestedNameSpecifierLoc QualifierLoc,
2926
                                               SourceLocation IdentLoc,
2927
                                               NamedDecl *Used,
2928
0
                                               DeclContext *CommonAncestor) {
2929
0
  if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))
2930
0
    Used = NS->getOriginalNamespace();
2931
0
  return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
2932
0
                                        IdentLoc, Used, CommonAncestor);
2933
0
}
2934
2935
UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
2936
0
                                                           unsigned ID) {
2937
0
  return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
2938
0
                                        SourceLocation(),
2939
0
                                        NestedNameSpecifierLoc(),
2940
0
                                        SourceLocation(), nullptr, nullptr);
2941
0
}
2942
2943
0
NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
2944
0
  if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
2945
0
    return NA->getNamespace();
2946
0
  return cast_or_null<NamespaceDecl>(NominatedNamespace);
2947
0
}
2948
2949
NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
2950
                             SourceLocation StartLoc, SourceLocation IdLoc,
2951
                             IdentifierInfo *Id, NamespaceDecl *PrevDecl,
2952
                             bool Nested)
2953
    : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
2954
0
      redeclarable_base(C), LocStart(StartLoc) {
2955
0
  unsigned Flags = 0;
2956
0
  if (Inline)
2957
0
    Flags |= F_Inline;
2958
0
  if (Nested)
2959
0
    Flags |= F_Nested;
2960
0
  AnonOrFirstNamespaceAndFlags = {nullptr, Flags};
2961
0
  setPreviousDecl(PrevDecl);
2962
2963
0
  if (PrevDecl)
2964
0
    AnonOrFirstNamespaceAndFlags.setPointer(PrevDecl->getOriginalNamespace());
2965
0
}
2966
2967
NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2968
                                     bool Inline, SourceLocation StartLoc,
2969
                                     SourceLocation IdLoc, IdentifierInfo *Id,
2970
0
                                     NamespaceDecl *PrevDecl, bool Nested) {
2971
0
  return new (C, DC)
2972
0
      NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested);
2973
0
}
2974
2975
0
NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2976
0
  return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
2977
0
                                   SourceLocation(), nullptr, nullptr, false);
2978
0
}
2979
2980
0
NamespaceDecl *NamespaceDecl::getOriginalNamespace() {
2981
0
  if (isFirstDecl())
2982
0
    return this;
2983
2984
0
  return AnonOrFirstNamespaceAndFlags.getPointer();
2985
0
}
2986
2987
0
const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const {
2988
0
  if (isFirstDecl())
2989
0
    return this;
2990
2991
0
  return AnonOrFirstNamespaceAndFlags.getPointer();
2992
0
}
2993
2994
0
bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); }
2995
2996
0
NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
2997
0
  return getNextRedeclaration();
2998
0
}
2999
3000
0
NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
3001
0
  return getPreviousDecl();
3002
0
}
3003
3004
0
NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
3005
0
  return getMostRecentDecl();
3006
0
}
3007
3008
0
void NamespaceAliasDecl::anchor() {}
3009
3010
0
NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
3011
0
  return getNextRedeclaration();
3012
0
}
3013
3014
0
NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
3015
0
  return getPreviousDecl();
3016
0
}
3017
3018
0
NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
3019
0
  return getMostRecentDecl();
3020
0
}
3021
3022
NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
3023
                                               SourceLocation UsingLoc,
3024
                                               SourceLocation AliasLoc,
3025
                                               IdentifierInfo *Alias,
3026
                                           NestedNameSpecifierLoc QualifierLoc,
3027
                                               SourceLocation IdentLoc,
3028
0
                                               NamedDecl *Namespace) {
3029
  // FIXME: Preserve the aliased namespace as written.
3030
0
  if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
3031
0
    Namespace = NS->getOriginalNamespace();
3032
0
  return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
3033
0
                                        QualifierLoc, IdentLoc, Namespace);
3034
0
}
3035
3036
NamespaceAliasDecl *
3037
0
NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3038
0
  return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
3039
0
                                        SourceLocation(), nullptr,
3040
0
                                        NestedNameSpecifierLoc(),
3041
0
                                        SourceLocation(), nullptr);
3042
0
}
3043
3044
0
void LifetimeExtendedTemporaryDecl::anchor() {}
3045
3046
/// Retrieve the storage duration for the materialized temporary.
3047
0
StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
3048
0
  const ValueDecl *ExtendingDecl = getExtendingDecl();
3049
0
  if (!ExtendingDecl)
3050
0
    return SD_FullExpression;
3051
  // FIXME: This is not necessarily correct for a temporary materialized
3052
  // within a default initializer.
3053
0
  if (isa<FieldDecl>(ExtendingDecl))
3054
0
    return SD_Automatic;
3055
  // FIXME: This only works because storage class specifiers are not allowed
3056
  // on decomposition declarations.
3057
0
  if (isa<BindingDecl>(ExtendingDecl))
3058
0
    return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
3059
0
                                                                 : SD_Static;
3060
0
  return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
3061
0
}
3062
3063
0
APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
3064
0
  assert(getStorageDuration() == SD_Static &&
3065
0
         "don't need to cache the computed value for this temporary");
3066
0
  if (MayCreate && !Value) {
3067
0
    Value = (new (getASTContext()) APValue);
3068
0
    getASTContext().addDestruction(Value);
3069
0
  }
3070
0
  assert(Value && "may not be null");
3071
0
  return Value;
3072
0
}
3073
3074
0
void UsingShadowDecl::anchor() {}
3075
3076
UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
3077
                                 SourceLocation Loc, DeclarationName Name,
3078
                                 BaseUsingDecl *Introducer, NamedDecl *Target)
3079
    : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
3080
0
      UsingOrNextShadow(Introducer) {
3081
0
  if (Target) {
3082
0
    assert(!isa<UsingShadowDecl>(Target));
3083
0
    setTargetDecl(Target);
3084
0
  }
3085
0
  setImplicit();
3086
0
}
3087
3088
UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
3089
    : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
3090
0
      redeclarable_base(C) {}
3091
3092
UsingShadowDecl *
3093
0
UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3094
0
  return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
3095
0
}
3096
3097
0
BaseUsingDecl *UsingShadowDecl::getIntroducer() const {
3098
0
  const UsingShadowDecl *Shadow = this;
3099
0
  while (const auto *NextShadow =
3100
0
             dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
3101
0
    Shadow = NextShadow;
3102
0
  return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow);
3103
0
}
3104
3105
0
void ConstructorUsingShadowDecl::anchor() {}
3106
3107
ConstructorUsingShadowDecl *
3108
ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
3109
                                   SourceLocation Loc, UsingDecl *Using,
3110
0
                                   NamedDecl *Target, bool IsVirtual) {
3111
0
  return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
3112
0
                                                IsVirtual);
3113
0
}
3114
3115
ConstructorUsingShadowDecl *
3116
0
ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3117
0
  return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
3118
0
}
3119
3120
0
CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
3121
0
  return getIntroducer()->getQualifier()->getAsRecordDecl();
3122
0
}
3123
3124
0
void BaseUsingDecl::anchor() {}
3125
3126
0
void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {
3127
0
  assert(!llvm::is_contained(shadows(), S) && "declaration already in set");
3128
0
  assert(S->getIntroducer() == this);
3129
3130
0
  if (FirstUsingShadow.getPointer())
3131
0
    S->UsingOrNextShadow = FirstUsingShadow.getPointer();
3132
0
  FirstUsingShadow.setPointer(S);
3133
0
}
3134
3135
0
void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {
3136
0
  assert(llvm::is_contained(shadows(), S) && "declaration not in set");
3137
0
  assert(S->getIntroducer() == this);
3138
3139
  // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
3140
3141
0
  if (FirstUsingShadow.getPointer() == S) {
3142
0
    FirstUsingShadow.setPointer(
3143
0
      dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
3144
0
    S->UsingOrNextShadow = this;
3145
0
    return;
3146
0
  }
3147
3148
0
  UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
3149
0
  while (Prev->UsingOrNextShadow != S)
3150
0
    Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
3151
0
  Prev->UsingOrNextShadow = S->UsingOrNextShadow;
3152
0
  S->UsingOrNextShadow = this;
3153
0
}
3154
3155
0
void UsingDecl::anchor() {}
3156
3157
UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
3158
                             NestedNameSpecifierLoc QualifierLoc,
3159
                             const DeclarationNameInfo &NameInfo,
3160
0
                             bool HasTypename) {
3161
0
  return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
3162
0
}
3163
3164
0
UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3165
0
  return new (C, ID) UsingDecl(nullptr, SourceLocation(),
3166
0
                               NestedNameSpecifierLoc(), DeclarationNameInfo(),
3167
0
                               false);
3168
0
}
3169
3170
0
SourceRange UsingDecl::getSourceRange() const {
3171
0
  SourceLocation Begin = isAccessDeclaration()
3172
0
    ? getQualifierLoc().getBeginLoc() : UsingLocation;
3173
0
  return SourceRange(Begin, getNameInfo().getEndLoc());
3174
0
}
3175
3176
0
void UsingEnumDecl::anchor() {}
3177
3178
UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,
3179
                                     SourceLocation UL,
3180
                                     SourceLocation EL,
3181
                                     SourceLocation NL,
3182
0
                                     TypeSourceInfo *EnumType) {
3183
0
  assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl()));
3184
0
  return new (C, DC)
3185
0
      UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType);
3186
0
}
3187
3188
0
UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3189
0
  return new (C, ID)
3190
0
      UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),
3191
0
                    SourceLocation(), SourceLocation(), nullptr);
3192
0
}
3193
3194
0
SourceRange UsingEnumDecl::getSourceRange() const {
3195
0
  return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc());
3196
0
}
3197
3198
0
void UsingPackDecl::anchor() {}
3199
3200
UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
3201
                                     NamedDecl *InstantiatedFrom,
3202
0
                                     ArrayRef<NamedDecl *> UsingDecls) {
3203
0
  size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());
3204
0
  return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
3205
0
}
3206
3207
UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3208
0
                                                 unsigned NumExpansions) {
3209
0
  size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);
3210
0
  auto *Result =
3211
0
      new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, std::nullopt);
3212
0
  Result->NumExpansions = NumExpansions;
3213
0
  auto *Trail = Result->getTrailingObjects<NamedDecl *>();
3214
0
  for (unsigned I = 0; I != NumExpansions; ++I)
3215
0
    new (Trail + I) NamedDecl*(nullptr);
3216
0
  return Result;
3217
0
}
3218
3219
0
void UnresolvedUsingValueDecl::anchor() {}
3220
3221
UnresolvedUsingValueDecl *
3222
UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
3223
                                 SourceLocation UsingLoc,
3224
                                 NestedNameSpecifierLoc QualifierLoc,
3225
                                 const DeclarationNameInfo &NameInfo,
3226
0
                                 SourceLocation EllipsisLoc) {
3227
0
  return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
3228
0
                                              QualifierLoc, NameInfo,
3229
0
                                              EllipsisLoc);
3230
0
}
3231
3232
UnresolvedUsingValueDecl *
3233
0
UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3234
0
  return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
3235
0
                                              SourceLocation(),
3236
0
                                              NestedNameSpecifierLoc(),
3237
0
                                              DeclarationNameInfo(),
3238
0
                                              SourceLocation());
3239
0
}
3240
3241
0
SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
3242
0
  SourceLocation Begin = isAccessDeclaration()
3243
0
    ? getQualifierLoc().getBeginLoc() : UsingLocation;
3244
0
  return SourceRange(Begin, getNameInfo().getEndLoc());
3245
0
}
3246
3247
0
void UnresolvedUsingTypenameDecl::anchor() {}
3248
3249
UnresolvedUsingTypenameDecl *
3250
UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
3251
                                    SourceLocation UsingLoc,
3252
                                    SourceLocation TypenameLoc,
3253
                                    NestedNameSpecifierLoc QualifierLoc,
3254
                                    SourceLocation TargetNameLoc,
3255
                                    DeclarationName TargetName,
3256
0
                                    SourceLocation EllipsisLoc) {
3257
0
  return new (C, DC) UnresolvedUsingTypenameDecl(
3258
0
      DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
3259
0
      TargetName.getAsIdentifierInfo(), EllipsisLoc);
3260
0
}
3261
3262
UnresolvedUsingTypenameDecl *
3263
0
UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3264
0
  return new (C, ID) UnresolvedUsingTypenameDecl(
3265
0
      nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
3266
0
      SourceLocation(), nullptr, SourceLocation());
3267
0
}
3268
3269
UnresolvedUsingIfExistsDecl *
3270
UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,
3271
0
                                    SourceLocation Loc, DeclarationName Name) {
3272
0
  return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);
3273
0
}
3274
3275
UnresolvedUsingIfExistsDecl *
3276
0
UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) {
3277
0
  return new (Ctx, ID)
3278
0
      UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());
3279
0
}
3280
3281
UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,
3282
                                                         SourceLocation Loc,
3283
                                                         DeclarationName Name)
3284
0
    : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}
3285
3286
0
void UnresolvedUsingIfExistsDecl::anchor() {}
3287
3288
0
void StaticAssertDecl::anchor() {}
3289
3290
StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
3291
                                           SourceLocation StaticAssertLoc,
3292
                                           Expr *AssertExpr, Expr *Message,
3293
                                           SourceLocation RParenLoc,
3294
0
                                           bool Failed) {
3295
0
  return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
3296
0
                                      RParenLoc, Failed);
3297
0
}
3298
3299
StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
3300
0
                                                       unsigned ID) {
3301
0
  return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
3302
0
                                      nullptr, SourceLocation(), false);
3303
0
}
3304
3305
17
VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
3306
17
  assert((isa<VarDecl, BindingDecl>(this)) &&
3307
17
         "expected a VarDecl or a BindingDecl");
3308
17
  if (auto *Var = llvm::dyn_cast<VarDecl>(this))
3309
17
    return Var;
3310
0
  if (auto *BD = llvm::dyn_cast<BindingDecl>(this))
3311
0
    return llvm::dyn_cast<VarDecl>(BD->getDecomposedDecl());
3312
0
  return nullptr;
3313
0
}
3314
3315
0
void BindingDecl::anchor() {}
3316
3317
BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
3318
0
                                 SourceLocation IdLoc, IdentifierInfo *Id) {
3319
0
  return new (C, DC) BindingDecl(DC, IdLoc, Id);
3320
0
}
3321
3322
0
BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3323
0
  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
3324
0
}
3325
3326
0
VarDecl *BindingDecl::getHoldingVar() const {
3327
0
  Expr *B = getBinding();
3328
0
  if (!B)
3329
0
    return nullptr;
3330
0
  auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());
3331
0
  if (!DRE)
3332
0
    return nullptr;
3333
3334
0
  auto *VD = cast<VarDecl>(DRE->getDecl());
3335
0
  assert(VD->isImplicit() && "holding var for binding decl not implicit");
3336
0
  return VD;
3337
0
}
3338
3339
0
void DecompositionDecl::anchor() {}
3340
3341
DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
3342
                                             SourceLocation StartLoc,
3343
                                             SourceLocation LSquareLoc,
3344
                                             QualType T, TypeSourceInfo *TInfo,
3345
                                             StorageClass SC,
3346
0
                                             ArrayRef<BindingDecl *> Bindings) {
3347
0
  size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());
3348
0
  return new (C, DC, Extra)
3349
0
      DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
3350
0
}
3351
3352
DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
3353
                                                         unsigned ID,
3354
0
                                                         unsigned NumBindings) {
3355
0
  size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);
3356
0
  auto *Result = new (C, ID, Extra)
3357
0
      DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
3358
0
                        QualType(), nullptr, StorageClass(), std::nullopt);
3359
  // Set up and clean out the bindings array.
3360
0
  Result->NumBindings = NumBindings;
3361
0
  auto *Trail = Result->getTrailingObjects<BindingDecl *>();
3362
0
  for (unsigned I = 0; I != NumBindings; ++I)
3363
0
    new (Trail + I) BindingDecl*(nullptr);
3364
0
  return Result;
3365
0
}
3366
3367
void DecompositionDecl::printName(llvm::raw_ostream &OS,
3368
0
                                  const PrintingPolicy &Policy) const {
3369
0
  OS << '[';
3370
0
  bool Comma = false;
3371
0
  for (const auto *B : bindings()) {
3372
0
    if (Comma)
3373
0
      OS << ", ";
3374
0
    B->printName(OS, Policy);
3375
0
    Comma = true;
3376
0
  }
3377
0
  OS << ']';
3378
0
}
3379
3380
0
void MSPropertyDecl::anchor() {}
3381
3382
MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
3383
                                       SourceLocation L, DeclarationName N,
3384
                                       QualType T, TypeSourceInfo *TInfo,
3385
                                       SourceLocation StartL,
3386
                                       IdentifierInfo *Getter,
3387
0
                                       IdentifierInfo *Setter) {
3388
0
  return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
3389
0
}
3390
3391
MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3392
0
                                                   unsigned ID) {
3393
0
  return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
3394
0
                                    DeclarationName(), QualType(), nullptr,
3395
0
                                    SourceLocation(), nullptr, nullptr);
3396
0
}
3397
3398
0
void MSGuidDecl::anchor() {}
3399
3400
MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
3401
    : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
3402
0
      PartVal(P) {}
3403
3404
0
MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
3405
0
  DeclContext *DC = C.getTranslationUnitDecl();
3406
0
  return new (C, DC) MSGuidDecl(DC, T, P);
3407
0
}
3408
3409
0
MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3410
0
  return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
3411
0
}
3412
3413
void MSGuidDecl::printName(llvm::raw_ostream &OS,
3414
0
                           const PrintingPolicy &) const {
3415
0
  OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",
3416
0
                     PartVal.Part1, PartVal.Part2, PartVal.Part3);
3417
0
  unsigned I = 0;
3418
0
  for (uint8_t Byte : PartVal.Part4And5) {
3419
0
    OS << llvm::format("%02" PRIx8, Byte);
3420
0
    if (++I == 2)
3421
0
      OS << '-';
3422
0
  }
3423
0
  OS << '}';
3424
0
}
3425
3426
/// Determine if T is a valid 'struct _GUID' of the shape that we expect.
3427
0
static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
3428
  // FIXME: We only need to check this once, not once each time we compute a
3429
  // GUID APValue.
3430
0
  using MatcherRef = llvm::function_ref<bool(QualType)>;
3431
3432
0
  auto IsInt = [&Ctx](unsigned N) {
3433
0
    return [&Ctx, N](QualType T) {
3434
0
      return T->isUnsignedIntegerOrEnumerationType() &&
3435
0
             Ctx.getIntWidth(T) == N;
3436
0
    };
3437
0
  };
3438
3439
0
  auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
3440
0
    return [&Ctx, Elem, N](QualType T) {
3441
0
      const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
3442
0
      return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
3443
0
    };
3444
0
  };
3445
3446
0
  auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
3447
0
    return [Fields](QualType T) {
3448
0
      const RecordDecl *RD = T->getAsRecordDecl();
3449
0
      if (!RD || RD->isUnion())
3450
0
        return false;
3451
0
      RD = RD->getDefinition();
3452
0
      if (!RD)
3453
0
        return false;
3454
0
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3455
0
        if (CXXRD->getNumBases())
3456
0
          return false;
3457
0
      auto MatcherIt = Fields.begin();
3458
0
      for (const FieldDecl *FD : RD->fields()) {
3459
0
        if (FD->isUnnamedBitfield()) continue;
3460
0
        if (FD->isBitField() || MatcherIt == Fields.end() ||
3461
0
            !(*MatcherIt)(FD->getType()))
3462
0
          return false;
3463
0
        ++MatcherIt;
3464
0
      }
3465
0
      return MatcherIt == Fields.end();
3466
0
    };
3467
0
  };
3468
3469
  // We expect an {i32, i16, i16, [8 x i8]}.
3470
0
  return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
3471
0
}
3472
3473
0
APValue &MSGuidDecl::getAsAPValue() const {
3474
0
  if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
3475
0
    using llvm::APInt;
3476
0
    using llvm::APSInt;
3477
0
    APVal = APValue(APValue::UninitStruct(), 0, 4);
3478
0
    APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
3479
0
    APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
3480
0
    APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
3481
0
    APValue &Arr = APVal.getStructField(3) =
3482
0
        APValue(APValue::UninitArray(), 8, 8);
3483
0
    for (unsigned I = 0; I != 8; ++I) {
3484
0
      Arr.getArrayInitializedElt(I) =
3485
0
          APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
3486
0
    }
3487
    // Register this APValue to be destroyed if necessary. (Note that the
3488
    // MSGuidDecl destructor is never run.)
3489
0
    getASTContext().addDestruction(&APVal);
3490
0
  }
3491
3492
0
  return APVal;
3493
0
}
3494
3495
0
void UnnamedGlobalConstantDecl::anchor() {}
3496
3497
UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C,
3498
                                                     DeclContext *DC,
3499
                                                     QualType Ty,
3500
                                                     const APValue &Val)
3501
    : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(),
3502
                DeclarationName(), Ty),
3503
0
      Value(Val) {
3504
  // Cleanup the embedded APValue if required (note that our destructor is never
3505
  // run)
3506
0
  if (Value.needsCleanup())
3507
0
    C.addDestruction(&Value);
3508
0
}
3509
3510
UnnamedGlobalConstantDecl *
3511
UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T,
3512
0
                                  const APValue &Value) {
3513
0
  DeclContext *DC = C.getTranslationUnitDecl();
3514
0
  return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value);
3515
0
}
3516
3517
UnnamedGlobalConstantDecl *
3518
0
UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3519
0
  return new (C, ID)
3520
0
      UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue());
3521
0
}
3522
3523
void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS,
3524
0
                                          const PrintingPolicy &) const {
3525
0
  OS << "unnamed-global-constant";
3526
0
}
3527
3528
0
static const char *getAccessName(AccessSpecifier AS) {
3529
0
  switch (AS) {
3530
0
    case AS_none:
3531
0
      llvm_unreachable("Invalid access specifier!");
3532
0
    case AS_public:
3533
0
      return "public";
3534
0
    case AS_private:
3535
0
      return "private";
3536
0
    case AS_protected:
3537
0
      return "protected";
3538
0
  }
3539
0
  llvm_unreachable("Invalid access specifier!");
3540
0
}
3541
3542
const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
3543
0
                                             AccessSpecifier AS) {
3544
0
  return DB << getAccessName(AS);
3545
0
}