summaryrefslogtreecommitdiffstats
path: root/clang/lib/InstallAPI/Visitor.cpp
blob: b4ed5974a05704bbb54a139e8d181220555f5e9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//===- Visitor.cpp ---------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang/InstallAPI/Visitor.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/Basic/Linkage.h"
#include "clang/InstallAPI/FrontendRecords.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"

using namespace llvm;
using namespace llvm::MachO;

namespace {
enum class CXXLinkage {
  ExternalLinkage,
  LinkOnceODRLinkage,
  WeakODRLinkage,
  PrivateLinkage,
};
}

namespace clang::installapi {

// Exported NamedDecl needs to have external linkage and
// default visibility from LinkageComputer.
static bool isExported(const NamedDecl *D) {
  auto LV = D->getLinkageAndVisibility();
  return isExternallyVisible(LV.getLinkage()) &&
         (LV.getVisibility() == DefaultVisibility);
}

static bool isInlined(const FunctionDecl *D) {
  bool HasInlineAttribute = false;
  bool NoCXXAttr =
      (!D->getASTContext().getLangOpts().CPlusPlus &&
       !D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft() &&
       !D->hasAttr<DLLExportAttr>());

  // Check all redeclarations to find an inline attribute or keyword.
  for (const auto *RD : D->redecls()) {
    if (!RD->isInlined())
      continue;
    HasInlineAttribute = true;
    if (!(NoCXXAttr || RD->hasAttr<GNUInlineAttr>()))
      continue;
    if (RD->doesThisDeclarationHaveABody() &&
        RD->isInlineDefinitionExternallyVisible())
      return false;
  }

  if (!HasInlineAttribute)
    return false;

  return true;
}

static SymbolFlags getFlags(bool WeakDef, bool ThreadLocal = false) {
  SymbolFlags Result = SymbolFlags::None;
  if (WeakDef)
    Result |= SymbolFlags::WeakDefined;
  if (ThreadLocal)
    Result |= SymbolFlags::ThreadLocalValue;

  return Result;
}

void InstallAPIVisitor::HandleTranslationUnit(ASTContext &ASTCtx) {
  if (ASTCtx.getDiagnostics().hasErrorOccurred())
    return;

  auto *D = ASTCtx.getTranslationUnitDecl();
  TraverseDecl(D);
}

std::string InstallAPIVisitor::getMangledName(const NamedDecl *D) const {
  SmallString<256> Name;
  if (MC->shouldMangleDeclName(D)) {
    raw_svector_ostream NStream(Name);
    MC->mangleName(D, NStream);
  } else
    Name += D->getNameAsString();

  return getBackendMangledName(Name);
}

std::string InstallAPIVisitor::getBackendMangledName(Twine Name) const {
  SmallString<256> FinalName;
  Mangler::getNameWithPrefix(FinalName, Name, DataLayout(Layout));
  return std::string(FinalName);
}

std::optional<HeaderType>
InstallAPIVisitor::getAccessForDecl(const NamedDecl *D) const {
  SourceLocation Loc = D->getLocation();
  if (Loc.isInvalid())
    return std::nullopt;

  // If the loc refers to a macro expansion, InstallAPI needs to first get the
  // file location of the expansion.
  auto FileLoc = SrcMgr.getFileLoc(Loc);
  FileID ID = SrcMgr.getFileID(FileLoc);
  if (ID.isInvalid())
    return std::nullopt;

  const FileEntry *FE = SrcMgr.getFileEntryForID(ID);
  if (!FE)
    return std::nullopt;

  auto Header = Ctx.findAndRecordFile(FE, PP);
  if (!Header.has_value())
    return std::nullopt;

  HeaderType Access = Header.value();
  assert(Access != HeaderType::Unknown && "unexpected access level for global");
  return Access;
}

/// Check if the interface itself or any of its super classes have an
/// exception attribute. InstallAPI needs to export an additional symbol
/// ("OBJC_EHTYPE_$CLASS_NAME") if any of the classes have the exception
/// attribute.
static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *D) {
  for (; D != nullptr; D = D->getSuperClass())
    if (D->hasAttr<ObjCExceptionAttr>())
      return true;

  return false;
}
void InstallAPIVisitor::recordObjCInstanceVariables(
    const ASTContext &ASTCtx, ObjCContainerRecord *Record, StringRef SuperClass,
    const llvm::iterator_range<
        DeclContext::specific_decl_iterator<ObjCIvarDecl>>
        Ivars) {
  RecordLinkage Linkage = RecordLinkage::Exported;
  const RecordLinkage ContainerLinkage = Record->getLinkage();
  // If fragile, set to unknown.
  if (ASTCtx.getLangOpts().ObjCRuntime.isFragile())
    Linkage = RecordLinkage::Unknown;
  // Linkage should be inherited from container.
  else if (ContainerLinkage != RecordLinkage::Unknown)
    Linkage = ContainerLinkage;
  for (const auto *IV : Ivars) {
    auto Access = getAccessForDecl(IV);
    if (!Access)
      continue;
    StringRef Name = IV->getName();
    const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(IV);
    auto AC = IV->getCanonicalAccessControl();
    Ctx.Slice->addObjCIVar(Record, Name, Linkage, Avail, IV, *Access, AC);
  }
}

bool InstallAPIVisitor::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
  // Skip forward declaration for classes (@class)
  if (!D->isThisDeclarationADefinition())
    return true;

  // Skip over declarations that access could not be collected for.
  auto Access = getAccessForDecl(D);
  if (!Access)
    return true;

  StringRef Name = D->getObjCRuntimeNameAsString();
  const RecordLinkage Linkage =
      isExported(D) ? RecordLinkage::Exported : RecordLinkage::Internal;
  const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(D);
  const bool IsEHType =
      (!D->getASTContext().getLangOpts().ObjCRuntime.isFragile() &&
       hasObjCExceptionAttribute(D));

  ObjCInterfaceRecord *Class =
      Ctx.Slice->addObjCInterface(Name, Linkage, Avail, D, *Access, IsEHType);

  // Get base class.
  StringRef SuperClassName;
  if (const auto *SuperClass = D->getSuperClass())
    SuperClassName = SuperClass->getObjCRuntimeNameAsString();

  recordObjCInstanceVariables(D->getASTContext(), Class, SuperClassName,
                              D->ivars());
  return true;
}

bool InstallAPIVisitor::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
  StringRef CategoryName = D->getName();
  // Skip over declarations that access could not be collected for.
  auto Access = getAccessForDecl(D);
  if (!Access)
    return true;
  const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(D);
  const ObjCInterfaceDecl *InterfaceD = D->getClassInterface();
  const StringRef InterfaceName = InterfaceD->getName();

  ObjCCategoryRecord *Category = Ctx.Slice->addObjCCategory(
      InterfaceName, CategoryName, Avail, D, *Access);
  recordObjCInstanceVariables(D->getASTContext(), Category, InterfaceName,
                              D->ivars());
  return true;
}

bool InstallAPIVisitor::VisitVarDecl(const VarDecl *D) {
  // Skip function parameters.
  if (isa<ParmVarDecl>(D))
    return true;

  // Skip variables in records. They are handled seperately for C++.
  if (D->getDeclContext()->isRecord())
    return true;

  // Skip anything inside functions or methods.
  if (!D->isDefinedOutsideFunctionOrMethod())
    return true;

  // If this is a template but not specialization or instantiation, skip.
  if (D->getASTContext().getTemplateOrSpecializationInfo(D) &&
      D->getTemplateSpecializationKind() == TSK_Undeclared)
    return true;

  // Skip over declarations that access could not collected for.
  auto Access = getAccessForDecl(D);
  if (!Access)
    return true;

  const RecordLinkage Linkage =
      isExported(D) ? RecordLinkage::Exported : RecordLinkage::Internal;
  const bool WeakDef = D->hasAttr<WeakAttr>();
  const bool ThreadLocal = D->getTLSKind() != VarDecl::TLS_None;
  const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(D);
  Ctx.Slice->addGlobal(getMangledName(D), Linkage, GlobalRecord::Kind::Variable,
                       Avail, D, *Access, getFlags(WeakDef, ThreadLocal));
  return true;
}

bool InstallAPIVisitor::VisitFunctionDecl(const FunctionDecl *D) {
  if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(D)) {
    // Skip member function in class templates.
    if (M->getParent()->getDescribedClassTemplate() != nullptr)
      return true;

    // Skip methods in CXX RecordDecls.
    for (auto P : D->getASTContext().getParents(*M)) {
      if (P.get<CXXRecordDecl>())
        return true;
    }

    // Skip CXX ConstructorDecls and DestructorDecls.
    if (isa<CXXConstructorDecl>(M) || isa<CXXDestructorDecl>(M))
      return true;
  }

  // Skip templated functions.
  switch (D->getTemplatedKind()) {
  case FunctionDecl::TK_NonTemplate:
  case FunctionDecl::TK_DependentNonTemplate:
    break;
  case FunctionDecl::TK_MemberSpecialization:
  case FunctionDecl::TK_FunctionTemplateSpecialization:
    if (auto *TempInfo = D->getTemplateSpecializationInfo()) {
      if (!TempInfo->isExplicitInstantiationOrSpecialization())
        return true;
    }
    break;
  case FunctionDecl::TK_FunctionTemplate:
  case FunctionDecl::TK_DependentFunctionTemplateSpecialization:
    return true;
  }

  auto Access = getAccessForDecl(D);
  if (!Access)
    return true;
  auto Name = getMangledName(D);
  const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(D);
  const bool ExplicitInstantiation = D->getTemplateSpecializationKind() ==
                                     TSK_ExplicitInstantiationDeclaration;
  const bool WeakDef = ExplicitInstantiation || D->hasAttr<WeakAttr>();
  const bool Inlined = isInlined(D);
  const RecordLinkage Linkage = (Inlined || !isExported(D))
                                    ? RecordLinkage::Internal
                                    : RecordLinkage::Exported;
  Ctx.Slice->addGlobal(Name, Linkage, GlobalRecord::Kind::Function, Avail, D,
                       *Access, getFlags(WeakDef), Inlined);
  return true;
}

static bool hasVTable(const CXXRecordDecl *D) {
  // Check if vtable symbols should be emitted, only dynamic classes need
  // vtables.
  if (!D->hasDefinition() || !D->isDynamicClass())
    return false;

  assert(D->isExternallyVisible() && "Should be externally visible");
  assert(D->isCompleteDefinition() && "Only works on complete definitions");

  const CXXMethodDecl *KeyFunctionD =
      D->getASTContext().getCurrentKeyFunction(D);
  // If this class has a key function, then there is a vtable, possibly internal
  // though.
  if (KeyFunctionD) {
    switch (KeyFunctionD->getTemplateSpecializationKind()) {
    case TSK_Undeclared:
    case TSK_ExplicitSpecialization:
    case TSK_ImplicitInstantiation:
    case TSK_ExplicitInstantiationDefinition:
      return true;
    case TSK_ExplicitInstantiationDeclaration:
      llvm_unreachable(
          "Unexpected TemplateSpecializationKind for key function");
    }
  } else if (D->isAbstract()) {
    // If the class is abstract and it doesn't have a key function, it is a
    // 'pure' virtual class. It doesn't need a vtable.
    return false;
  }

  switch (D->getTemplateSpecializationKind()) {
  case TSK_Undeclared:
  case TSK_ExplicitSpecialization:
  case TSK_ImplicitInstantiation:
    return false;

  case TSK_ExplicitInstantiationDeclaration:
  case TSK_ExplicitInstantiationDefinition:
    return true;
  }

  llvm_unreachable("Invalid TemplateSpecializationKind!");
}

static CXXLinkage getVTableLinkage(const CXXRecordDecl *D) {
  assert((D->hasDefinition() && D->isDynamicClass()) && "Record has no vtable");
  assert(D->isExternallyVisible() && "Record should be externally visible");
  if (D->getVisibility() == HiddenVisibility)
    return CXXLinkage::PrivateLinkage;

  const CXXMethodDecl *KeyFunctionD =
      D->getASTContext().getCurrentKeyFunction(D);
  if (KeyFunctionD) {
    // If this class has a key function, use that to determine the
    // linkage of the vtable.
    switch (KeyFunctionD->getTemplateSpecializationKind()) {
    case TSK_Undeclared:
    case TSK_ExplicitSpecialization:
      if (isInlined(KeyFunctionD))
        return CXXLinkage::LinkOnceODRLinkage;
      return CXXLinkage::ExternalLinkage;
    case TSK_ImplicitInstantiation:
      llvm_unreachable("No external vtable for implicit instantiations");
    case TSK_ExplicitInstantiationDefinition:
      return CXXLinkage::WeakODRLinkage;
    case TSK_ExplicitInstantiationDeclaration:
      llvm_unreachable(
          "Unexpected TemplateSpecializationKind for key function");
    }
  }

  switch (D->getTemplateSpecializationKind()) {
  case TSK_Undeclared:
  case TSK_ExplicitSpecialization:
  case TSK_ImplicitInstantiation:
    return CXXLinkage::LinkOnceODRLinkage;
  case TSK_ExplicitInstantiationDeclaration:
  case TSK_ExplicitInstantiationDefinition:
    return CXXLinkage::WeakODRLinkage;
  }

  llvm_unreachable("Invalid TemplateSpecializationKind!");
}

static bool isRTTIWeakDef(const CXXRecordDecl *D) {
  if (D->hasAttr<WeakAttr>())
    return true;

  if (D->isAbstract() && D->getASTContext().getCurrentKeyFunction(D) == nullptr)
    return true;

  if (D->isDynamicClass())
    return getVTableLinkage(D) != CXXLinkage::ExternalLinkage;

  return false;
}

static bool hasRTTI(const CXXRecordDecl *D) {
  if (!D->getASTContext().getLangOpts().RTTI)
    return false;

  if (!D->hasDefinition())
    return false;

  if (!D->isDynamicClass())
    return false;

  // Don't emit weak-def RTTI information. InstallAPI cannot reliably determine
  // if the final binary will have those weak defined RTTI symbols. This depends
  // on the optimization level and if the class has been instantiated and used.
  //
  // Luckily, the Apple static linker doesn't need those weak defined RTTI
  // symbols for linking. They are only needed by the runtime linker. That means
  // they can be safely dropped.
  if (isRTTIWeakDef(D))
    return false;

  return true;
}

std::string
InstallAPIVisitor::getMangledCXXRTTIName(const CXXRecordDecl *D) const {
  SmallString<256> Name;
  raw_svector_ostream NameStream(Name);
  MC->mangleCXXRTTIName(QualType(D->getTypeForDecl(), 0), NameStream);

  return getBackendMangledName(Name);
}

std::string InstallAPIVisitor::getMangledCXXRTTI(const CXXRecordDecl *D) const {
  SmallString<256> Name;
  raw_svector_ostream NameStream(Name);
  MC->mangleCXXRTTI(QualType(D->getTypeForDecl(), 0), NameStream);

  return getBackendMangledName(Name);
}

std::string
InstallAPIVisitor::getMangledCXXVTableName(const CXXRecordDecl *D) const {
  SmallString<256> Name;
  raw_svector_ostream NameStream(Name);
  MC->mangleCXXVTable(D, NameStream);

  return getBackendMangledName(Name);
}

std::string
InstallAPIVisitor::getMangledCXXThunk(const GlobalDecl &D,
                                      const ThunkInfo &Thunk) const {
  SmallString<256> Name;
  raw_svector_ostream NameStream(Name);
  const auto *Method = cast<CXXMethodDecl>(D.getDecl());
  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Method))
    MC->mangleCXXDtorThunk(Dtor, D.getDtorType(), Thunk.This, NameStream);
  else
    MC->mangleThunk(Method, Thunk, NameStream);

  return getBackendMangledName(Name);
}

std::string InstallAPIVisitor::getMangledCtorDtor(const CXXMethodDecl *D,
                                                  int Type) const {
  SmallString<256> Name;
  raw_svector_ostream NameStream(Name);
  GlobalDecl GD;
  if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(D))
    GD = GlobalDecl(Ctor, CXXCtorType(Type));
  else {
    const auto *Dtor = cast<CXXDestructorDecl>(D);
    GD = GlobalDecl(Dtor, CXXDtorType(Type));
  }
  MC->mangleName(GD, NameStream);
  return getBackendMangledName(Name);
}

void InstallAPIVisitor::emitVTableSymbols(const CXXRecordDecl *D,
                                          const AvailabilityInfo &Avail,
                                          const HeaderType Access,
                                          bool EmittedVTable) {
  if (hasVTable(D)) {
    EmittedVTable = true;
    const CXXLinkage VTableLinkage = getVTableLinkage(D);
    if (VTableLinkage == CXXLinkage::ExternalLinkage ||
        VTableLinkage == CXXLinkage::WeakODRLinkage) {
      const std::string Name = getMangledCXXVTableName(D);
      const bool WeakDef = VTableLinkage == CXXLinkage::WeakODRLinkage;
      Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                           GlobalRecord::Kind::Variable, Avail, D, Access,
                           getFlags(WeakDef));
      if (!D->getDescribedClassTemplate() && !D->isInvalidDecl()) {
        VTableContextBase *VTable = D->getASTContext().getVTableContext();
        auto AddThunk = [&](GlobalDecl GD) {
          const ItaniumVTableContext::ThunkInfoVectorTy *Thunks =
              VTable->getThunkInfo(GD);
          if (!Thunks)
            return;

          for (const auto &Thunk : *Thunks) {
            const std::string Name = getMangledCXXThunk(GD, Thunk);
            Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                                 GlobalRecord::Kind::Function, Avail,
                                 GD.getDecl(), Access);
          }
        };

        for (const auto *Method : D->methods()) {
          if (isa<CXXConstructorDecl>(Method) || !Method->isVirtual())
            continue;

          if (auto Dtor = dyn_cast<CXXDestructorDecl>(Method)) {
            // Skip default destructor.
            if (Dtor->isDefaulted())
              continue;
            AddThunk({Dtor, Dtor_Deleting});
            AddThunk({Dtor, Dtor_Complete});
          } else
            AddThunk(Method);
        }
      }
    }
  }

  if (!EmittedVTable)
    return;

  if (hasRTTI(D)) {
    std::string Name = getMangledCXXRTTI(D);
    Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                         GlobalRecord::Kind::Variable, Avail, D, Access);

    Name = getMangledCXXRTTIName(D);
    Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                         GlobalRecord::Kind::Variable, Avail, D, Access);
  }

  for (const auto &It : D->bases()) {
    const CXXRecordDecl *Base =
        cast<CXXRecordDecl>(It.getType()->castAs<RecordType>()->getDecl());
    const auto BaseAccess = getAccessForDecl(Base);
    if (!BaseAccess)
      continue;
    const AvailabilityInfo BaseAvail = AvailabilityInfo::createFromDecl(Base);
    emitVTableSymbols(Base, BaseAvail, *BaseAccess, /*EmittedVTable=*/true);
  }
}

bool InstallAPIVisitor::VisitCXXRecordDecl(const CXXRecordDecl *D) {
  if (!D->isCompleteDefinition())
    return true;

  // Skip templated classes.
  if (D->getDescribedClassTemplate() != nullptr)
    return true;

  // Skip partial templated classes too.
  if (isa<ClassTemplatePartialSpecializationDecl>(D))
    return true;

  auto Access = getAccessForDecl(D);
  if (!Access)
    return true;
  const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(D);

  // Check whether to emit the vtable/rtti symbols.
  if (isExported(D))
    emitVTableSymbols(D, Avail, *Access);

  TemplateSpecializationKind ClassSK = TSK_Undeclared;
  bool KeepInlineAsWeak = false;
  if (auto *Templ = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    ClassSK = Templ->getTemplateSpecializationKind();
    if (ClassSK == TSK_ExplicitInstantiationDeclaration)
      KeepInlineAsWeak = true;
  }

  // Record the class methods.
  for (const auto *M : D->methods()) {
    // Inlined methods are usually not emitted, except when it comes from a
    // specialized template.
    bool WeakDef = false;
    if (isInlined(M)) {
      if (!KeepInlineAsWeak)
        continue;

      WeakDef = true;
    }

    if (!isExported(M))
      continue;

    switch (M->getTemplateSpecializationKind()) {
    case TSK_Undeclared:
    case TSK_ExplicitSpecialization:
      break;
    case TSK_ImplicitInstantiation:
      continue;
    case TSK_ExplicitInstantiationDeclaration:
      if (ClassSK == TSK_ExplicitInstantiationDeclaration)
        WeakDef = true;
      break;
    case TSK_ExplicitInstantiationDefinition:
      WeakDef = true;
      break;
    }

    if (!M->isUserProvided())
      continue;

    // Methods that are deleted are not exported.
    if (M->isDeleted())
      continue;

    const auto Access = getAccessForDecl(M);
    if (!Access)
      return true;
    const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(M);

    if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(M)) {
      // Defaulted constructors are not exported.
      if (Ctor->isDefaulted())
        continue;

      std::string Name = getMangledCtorDtor(M, Ctor_Base);
      Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                           GlobalRecord::Kind::Function, Avail, D, *Access,
                           getFlags(WeakDef));

      if (!D->isAbstract()) {
        std::string Name = getMangledCtorDtor(M, Ctor_Complete);
        Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                             GlobalRecord::Kind::Function, Avail, D, *Access,
                             getFlags(WeakDef));
      }

      continue;
    }

    if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(M)) {
      // Defaulted destructors are not exported.
      if (Dtor->isDefaulted())
        continue;

      std::string Name = getMangledCtorDtor(M, Dtor_Base);
      Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                           GlobalRecord::Kind::Function, Avail, D, *Access,
                           getFlags(WeakDef));

      Name = getMangledCtorDtor(M, Dtor_Complete);
      Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                           GlobalRecord::Kind::Function, Avail, D, *Access,
                           getFlags(WeakDef));

      if (Dtor->isVirtual()) {
        Name = getMangledCtorDtor(M, Dtor_Deleting);
        Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                             GlobalRecord::Kind::Function, Avail, D, *Access,
                             getFlags(WeakDef));
      }

      continue;
    }

    // Though abstract methods can map to exports, this is generally unexpected.
    // Except in the case of destructors. Only ignore pure virtuals after
    // checking if the member function was a destructor.
    if (M->isPureVirtual())
      continue;

    std::string Name = getMangledName(M);
    Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                         GlobalRecord::Kind::Function, Avail, D, *Access,
                         getFlags(WeakDef));
  }

  if (auto *Templ = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    if (!Templ->isExplicitInstantiationOrSpecialization())
      return true;
  }

  using var_iter = CXXRecordDecl::specific_decl_iterator<VarDecl>;
  using var_range = iterator_range<var_iter>;
  for (const auto *Var : var_range(D->decls())) {
    // Skip const static member variables.
    // \code
    // struct S {
    //   static const int x = 0;
    // };
    // \endcode
    if (Var->isStaticDataMember() && Var->hasInit())
      continue;

    // Skip unexported var decls.
    if (!isExported(Var))
      continue;

    const std::string Name = getMangledName(Var);
    const auto Access = getAccessForDecl(Var);
    if (!Access)
      return true;
    const AvailabilityInfo Avail = AvailabilityInfo::createFromDecl(Var);
    const bool WeakDef = Var->hasAttr<WeakAttr>() || KeepInlineAsWeak;

    Ctx.Slice->addGlobal(Name, RecordLinkage::Exported,
                         GlobalRecord::Kind::Variable, Avail, D, *Access,
                         getFlags(WeakDef));
  }

  return true;
}

} // namespace clang::installapi