llvm-project

Форк
0
5768 строк · 206.3 Кб
1
//===- Decl.cpp - 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 Decl subclasses.
10
//
11
//===----------------------------------------------------------------------===//
12

13
#include "clang/AST/Decl.h"
14
#include "Linkage.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTDiagnostic.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/Attr.h"
20
#include "clang/AST/CanonicalType.h"
21
#include "clang/AST/DeclBase.h"
22
#include "clang/AST/DeclCXX.h"
23
#include "clang/AST/DeclObjC.h"
24
#include "clang/AST/DeclOpenMP.h"
25
#include "clang/AST/DeclTemplate.h"
26
#include "clang/AST/DeclarationName.h"
27
#include "clang/AST/Expr.h"
28
#include "clang/AST/ExprCXX.h"
29
#include "clang/AST/ExternalASTSource.h"
30
#include "clang/AST/ODRHash.h"
31
#include "clang/AST/PrettyDeclStackTrace.h"
32
#include "clang/AST/PrettyPrinter.h"
33
#include "clang/AST/Randstruct.h"
34
#include "clang/AST/RecordLayout.h"
35
#include "clang/AST/Redeclarable.h"
36
#include "clang/AST/Stmt.h"
37
#include "clang/AST/TemplateBase.h"
38
#include "clang/AST/Type.h"
39
#include "clang/AST/TypeLoc.h"
40
#include "clang/Basic/Builtins.h"
41
#include "clang/Basic/IdentifierTable.h"
42
#include "clang/Basic/LLVM.h"
43
#include "clang/Basic/LangOptions.h"
44
#include "clang/Basic/Linkage.h"
45
#include "clang/Basic/Module.h"
46
#include "clang/Basic/NoSanitizeList.h"
47
#include "clang/Basic/PartialDiagnostic.h"
48
#include "clang/Basic/Sanitizers.h"
49
#include "clang/Basic/SourceLocation.h"
50
#include "clang/Basic/SourceManager.h"
51
#include "clang/Basic/Specifiers.h"
52
#include "clang/Basic/TargetCXXABI.h"
53
#include "clang/Basic/TargetInfo.h"
54
#include "clang/Basic/Visibility.h"
55
#include "llvm/ADT/APSInt.h"
56
#include "llvm/ADT/ArrayRef.h"
57
#include "llvm/ADT/STLExtras.h"
58
#include "llvm/ADT/SmallVector.h"
59
#include "llvm/ADT/StringRef.h"
60
#include "llvm/ADT/StringSwitch.h"
61
#include "llvm/Support/Casting.h"
62
#include "llvm/Support/ErrorHandling.h"
63
#include "llvm/Support/raw_ostream.h"
64
#include "llvm/TargetParser/Triple.h"
65
#include <algorithm>
66
#include <cassert>
67
#include <cstddef>
68
#include <cstring>
69
#include <memory>
70
#include <optional>
71
#include <string>
72
#include <tuple>
73
#include <type_traits>
74

75
using namespace clang;
76

77
Decl *clang::getPrimaryMergedDecl(Decl *D) {
78
  return D->getASTContext().getPrimaryMergedDecl(D);
79
}
80

81
void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
82
  SourceLocation Loc = this->Loc;
83
  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
84
  if (Loc.isValid()) {
85
    Loc.print(OS, Context.getSourceManager());
86
    OS << ": ";
87
  }
88
  OS << Message;
89

90
  if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {
91
    OS << " '";
92
    ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
93
    OS << "'";
94
  }
95

96
  OS << '\n';
97
}
98

99
// Defined here so that it can be inlined into its direct callers.
100
bool Decl::isOutOfLine() const {
101
  return !getLexicalDeclContext()->Equals(getDeclContext());
102
}
103

104
TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
105
    : Decl(TranslationUnit, nullptr, SourceLocation()),
106
      DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
107

108
//===----------------------------------------------------------------------===//
109
// NamedDecl Implementation
110
//===----------------------------------------------------------------------===//
111

112
// Visibility rules aren't rigorously externally specified, but here
113
// are the basic principles behind what we implement:
114
//
115
// 1. An explicit visibility attribute is generally a direct expression
116
// of the user's intent and should be honored.  Only the innermost
117
// visibility attribute applies.  If no visibility attribute applies,
118
// global visibility settings are considered.
119
//
120
// 2. There is one caveat to the above: on or in a template pattern,
121
// an explicit visibility attribute is just a default rule, and
122
// visibility can be decreased by the visibility of template
123
// arguments.  But this, too, has an exception: an attribute on an
124
// explicit specialization or instantiation causes all the visibility
125
// restrictions of the template arguments to be ignored.
126
//
127
// 3. A variable that does not otherwise have explicit visibility can
128
// be restricted by the visibility of its type.
129
//
130
// 4. A visibility restriction is explicit if it comes from an
131
// attribute (or something like it), not a global visibility setting.
132
// When emitting a reference to an external symbol, visibility
133
// restrictions are ignored unless they are explicit.
134
//
135
// 5. When computing the visibility of a non-type, including a
136
// non-type member of a class, only non-type visibility restrictions
137
// are considered: the 'visibility' attribute, global value-visibility
138
// settings, and a few special cases like __private_extern.
139
//
140
// 6. When computing the visibility of a type, including a type member
141
// of a class, only type visibility restrictions are considered:
142
// the 'type_visibility' attribute and global type-visibility settings.
143
// However, a 'visibility' attribute counts as a 'type_visibility'
144
// attribute on any declaration that only has the former.
145
//
146
// The visibility of a "secondary" entity, like a template argument,
147
// is computed using the kind of that entity, not the kind of the
148
// primary entity for which we are computing visibility.  For example,
149
// the visibility of a specialization of either of these templates:
150
//   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
151
//   template <class T, bool (&compare)(T, X)> class matcher;
152
// is restricted according to the type visibility of the argument 'T',
153
// the type visibility of 'bool(&)(T,X)', and the value visibility of
154
// the argument function 'compare'.  That 'has_match' is a value
155
// and 'matcher' is a type only matters when looking for attributes
156
// and settings from the immediate context.
157

158
/// Does this computation kind permit us to consider additional
159
/// visibility settings from attributes and the like?
160
static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
161
  return computation.IgnoreExplicitVisibility;
162
}
163

164
/// Given an LVComputationKind, return one of the same type/value sort
165
/// that records that it already has explicit visibility.
166
static LVComputationKind
167
withExplicitVisibilityAlready(LVComputationKind Kind) {
168
  Kind.IgnoreExplicitVisibility = true;
169
  return Kind;
170
}
171

172
static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
173
                                                       LVComputationKind kind) {
174
  assert(!kind.IgnoreExplicitVisibility &&
175
         "asking for explicit visibility when we shouldn't be");
176
  return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
177
}
178

179
/// Is the given declaration a "type" or a "value" for the purposes of
180
/// visibility computation?
181
static bool usesTypeVisibility(const NamedDecl *D) {
182
  return isa<TypeDecl>(D) ||
183
         isa<ClassTemplateDecl>(D) ||
184
         isa<ObjCInterfaceDecl>(D);
185
}
186

187
/// Does the given declaration have member specialization information,
188
/// and if so, is it an explicit specialization?
189
template <class T>
190
static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>
191
isExplicitMemberSpecialization(const T *D) {
192
  if (const MemberSpecializationInfo *member =
193
        D->getMemberSpecializationInfo()) {
194
    return member->isExplicitSpecialization();
195
  }
196
  return false;
197
}
198

199
/// For templates, this question is easier: a member template can't be
200
/// explicitly instantiated, so there's a single bit indicating whether
201
/// or not this is an explicit member specialization.
202
static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
203
  return D->isMemberSpecialization();
204
}
205

206
/// Given a visibility attribute, return the explicit visibility
207
/// associated with it.
208
template <class T>
209
static Visibility getVisibilityFromAttr(const T *attr) {
210
  switch (attr->getVisibility()) {
211
  case T::Default:
212
    return DefaultVisibility;
213
  case T::Hidden:
214
    return HiddenVisibility;
215
  case T::Protected:
216
    return ProtectedVisibility;
217
  }
218
  llvm_unreachable("bad visibility kind");
219
}
220

221
/// Return the explicit visibility of the given declaration.
222
static std::optional<Visibility>
223
getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) {
224
  // If we're ultimately computing the visibility of a type, look for
225
  // a 'type_visibility' attribute before looking for 'visibility'.
226
  if (kind == NamedDecl::VisibilityForType) {
227
    if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
228
      return getVisibilityFromAttr(A);
229
    }
230
  }
231

232
  // If this declaration has an explicit visibility attribute, use it.
233
  if (const auto *A = D->getAttr<VisibilityAttr>()) {
234
    return getVisibilityFromAttr(A);
235
  }
236

237
  return std::nullopt;
238
}
239

240
LinkageInfo LinkageComputer::getLVForType(const Type &T,
241
                                          LVComputationKind computation) {
242
  if (computation.IgnoreAllVisibility)
243
    return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
244
  return getTypeLinkageAndVisibility(&T);
245
}
246

247
/// Get the most restrictive linkage for the types in the given
248
/// template parameter list.  For visibility purposes, template
249
/// parameters are part of the signature of a template.
250
LinkageInfo LinkageComputer::getLVForTemplateParameterList(
251
    const TemplateParameterList *Params, LVComputationKind computation) {
252
  LinkageInfo LV;
253
  for (const NamedDecl *P : *Params) {
254
    // Template type parameters are the most common and never
255
    // contribute to visibility, pack or not.
256
    if (isa<TemplateTypeParmDecl>(P))
257
      continue;
258

259
    // Non-type template parameters can be restricted by the value type, e.g.
260
    //   template <enum X> class A { ... };
261
    // We have to be careful here, though, because we can be dealing with
262
    // dependent types.
263
    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
264
      // Handle the non-pack case first.
265
      if (!NTTP->isExpandedParameterPack()) {
266
        if (!NTTP->getType()->isDependentType()) {
267
          LV.merge(getLVForType(*NTTP->getType(), computation));
268
        }
269
        continue;
270
      }
271

272
      // Look at all the types in an expanded pack.
273
      for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
274
        QualType type = NTTP->getExpansionType(i);
275
        if (!type->isDependentType())
276
          LV.merge(getTypeLinkageAndVisibility(type));
277
      }
278
      continue;
279
    }
280

281
    // Template template parameters can be restricted by their
282
    // template parameters, recursively.
283
    const auto *TTP = cast<TemplateTemplateParmDecl>(P);
284

285
    // Handle the non-pack case first.
286
    if (!TTP->isExpandedParameterPack()) {
287
      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
288
                                             computation));
289
      continue;
290
    }
291

292
    // Look at all expansions in an expanded pack.
293
    for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
294
           i != n; ++i) {
295
      LV.merge(getLVForTemplateParameterList(
296
          TTP->getExpansionTemplateParameters(i), computation));
297
    }
298
  }
299

300
  return LV;
301
}
302

303
static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
304
  const Decl *Ret = nullptr;
305
  const DeclContext *DC = D->getDeclContext();
306
  while (DC->getDeclKind() != Decl::TranslationUnit) {
307
    if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
308
      Ret = cast<Decl>(DC);
309
    DC = DC->getParent();
310
  }
311
  return Ret;
312
}
313

314
/// Get the most restrictive linkage for the types and
315
/// declarations in the given template argument list.
316
///
317
/// Note that we don't take an LVComputationKind because we always
318
/// want to honor the visibility of template arguments in the same way.
319
LinkageInfo
320
LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
321
                                              LVComputationKind computation) {
322
  LinkageInfo LV;
323

324
  for (const TemplateArgument &Arg : Args) {
325
    switch (Arg.getKind()) {
326
    case TemplateArgument::Null:
327
    case TemplateArgument::Integral:
328
    case TemplateArgument::Expression:
329
      continue;
330

331
    case TemplateArgument::Type:
332
      LV.merge(getLVForType(*Arg.getAsType(), computation));
333
      continue;
334

335
    case TemplateArgument::Declaration: {
336
      const NamedDecl *ND = Arg.getAsDecl();
337
      assert(!usesTypeVisibility(ND));
338
      LV.merge(getLVForDecl(ND, computation));
339
      continue;
340
    }
341

342
    case TemplateArgument::NullPtr:
343
      LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
344
      continue;
345

346
    case TemplateArgument::StructuralValue:
347
      LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));
348
      continue;
349

350
    case TemplateArgument::Template:
351
    case TemplateArgument::TemplateExpansion:
352
      if (TemplateDecl *Template =
353
              Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
354
        LV.merge(getLVForDecl(Template, computation));
355
      continue;
356

357
    case TemplateArgument::Pack:
358
      LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
359
      continue;
360
    }
361
    llvm_unreachable("bad template argument kind");
362
  }
363

364
  return LV;
365
}
366

367
LinkageInfo
368
LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
369
                                              LVComputationKind computation) {
370
  return getLVForTemplateArgumentList(TArgs.asArray(), computation);
371
}
372

373
static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
374
                        const FunctionTemplateSpecializationInfo *specInfo) {
375
  // Include visibility from the template parameters and arguments
376
  // only if this is not an explicit instantiation or specialization
377
  // with direct explicit visibility.  (Implicit instantiations won't
378
  // have a direct attribute.)
379
  if (!specInfo->isExplicitInstantiationOrSpecialization())
380
    return true;
381

382
  return !fn->hasAttr<VisibilityAttr>();
383
}
384

385
/// Merge in template-related linkage and visibility for the given
386
/// function template specialization.
387
///
388
/// We don't need a computation kind here because we can assume
389
/// LVForValue.
390
///
391
/// \param[out] LV the computation to use for the parent
392
void LinkageComputer::mergeTemplateLV(
393
    LinkageInfo &LV, const FunctionDecl *fn,
394
    const FunctionTemplateSpecializationInfo *specInfo,
395
    LVComputationKind computation) {
396
  bool considerVisibility =
397
    shouldConsiderTemplateVisibility(fn, specInfo);
398

399
  FunctionTemplateDecl *temp = specInfo->getTemplate();
400
  // Merge information from the template declaration.
401
  LinkageInfo tempLV = getLVForDecl(temp, computation);
402
  // The linkage of the specialization should be consistent with the
403
  // template declaration.
404
  LV.setLinkage(tempLV.getLinkage());
405

406
  // Merge information from the template parameters.
407
  LinkageInfo paramsLV =
408
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
409
  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
410

411
  // Merge information from the template arguments.
412
  const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
413
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
414
  LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
415
}
416

417
/// Does the given declaration have a direct visibility attribute
418
/// that would match the given rules?
419
static bool hasDirectVisibilityAttribute(const NamedDecl *D,
420
                                         LVComputationKind computation) {
421
  if (computation.IgnoreAllVisibility)
422
    return false;
423

424
  return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
425
         D->hasAttr<VisibilityAttr>();
426
}
427

428
/// Should we consider visibility associated with the template
429
/// arguments and parameters of the given class template specialization?
430
static bool shouldConsiderTemplateVisibility(
431
                                 const ClassTemplateSpecializationDecl *spec,
432
                                 LVComputationKind computation) {
433
  // Include visibility from the template parameters and arguments
434
  // only if this is not an explicit instantiation or specialization
435
  // with direct explicit visibility (and note that implicit
436
  // instantiations won't have a direct attribute).
437
  //
438
  // Furthermore, we want to ignore template parameters and arguments
439
  // for an explicit specialization when computing the visibility of a
440
  // member thereof with explicit visibility.
441
  //
442
  // This is a bit complex; let's unpack it.
443
  //
444
  // An explicit class specialization is an independent, top-level
445
  // declaration.  As such, if it or any of its members has an
446
  // explicit visibility attribute, that must directly express the
447
  // user's intent, and we should honor it.  The same logic applies to
448
  // an explicit instantiation of a member of such a thing.
449

450
  // Fast path: if this is not an explicit instantiation or
451
  // specialization, we always want to consider template-related
452
  // visibility restrictions.
453
  if (!spec->isExplicitInstantiationOrSpecialization())
454
    return true;
455

456
  // This is the 'member thereof' check.
457
  if (spec->isExplicitSpecialization() &&
458
      hasExplicitVisibilityAlready(computation))
459
    return false;
460

461
  return !hasDirectVisibilityAttribute(spec, computation);
462
}
463

464
/// Merge in template-related linkage and visibility for the given
465
/// class template specialization.
466
void LinkageComputer::mergeTemplateLV(
467
    LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
468
    LVComputationKind computation) {
469
  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
470

471
  // Merge information from the template parameters, but ignore
472
  // visibility if we're only considering template arguments.
473
  ClassTemplateDecl *temp = spec->getSpecializedTemplate();
474
  // Merge information from the template declaration.
475
  LinkageInfo tempLV = getLVForDecl(temp, computation);
476
  // The linkage of the specialization should be consistent with the
477
  // template declaration.
478
  LV.setLinkage(tempLV.getLinkage());
479

480
  LinkageInfo paramsLV =
481
    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
482
  LV.mergeMaybeWithVisibility(paramsLV,
483
           considerVisibility && !hasExplicitVisibilityAlready(computation));
484

485
  // Merge information from the template arguments.  We ignore
486
  // template-argument visibility if we've got an explicit
487
  // instantiation with a visibility attribute.
488
  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
489
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
490
  if (considerVisibility)
491
    LV.mergeVisibility(argsLV);
492
  LV.mergeExternalVisibility(argsLV);
493
}
494

495
/// Should we consider visibility associated with the template
496
/// arguments and parameters of the given variable template
497
/// specialization? As usual, follow class template specialization
498
/// logic up to initialization.
499
static bool shouldConsiderTemplateVisibility(
500
                                 const VarTemplateSpecializationDecl *spec,
501
                                 LVComputationKind computation) {
502
  // Include visibility from the template parameters and arguments
503
  // only if this is not an explicit instantiation or specialization
504
  // with direct explicit visibility (and note that implicit
505
  // instantiations won't have a direct attribute).
506
  if (!spec->isExplicitInstantiationOrSpecialization())
507
    return true;
508

509
  // An explicit variable specialization is an independent, top-level
510
  // declaration.  As such, if it has an explicit visibility attribute,
511
  // that must directly express the user's intent, and we should honor
512
  // it.
513
  if (spec->isExplicitSpecialization() &&
514
      hasExplicitVisibilityAlready(computation))
515
    return false;
516

517
  return !hasDirectVisibilityAttribute(spec, computation);
518
}
519

520
/// Merge in template-related linkage and visibility for the given
521
/// variable template specialization. As usual, follow class template
522
/// specialization logic up to initialization.
523
void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
524
                                      const VarTemplateSpecializationDecl *spec,
525
                                      LVComputationKind computation) {
526
  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
527

528
  // Merge information from the template parameters, but ignore
529
  // visibility if we're only considering template arguments.
530
  VarTemplateDecl *temp = spec->getSpecializedTemplate();
531
  LinkageInfo tempLV =
532
    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
533
  LV.mergeMaybeWithVisibility(tempLV,
534
           considerVisibility && !hasExplicitVisibilityAlready(computation));
535

536
  // Merge information from the template arguments.  We ignore
537
  // template-argument visibility if we've got an explicit
538
  // instantiation with a visibility attribute.
539
  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
540
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
541
  if (considerVisibility)
542
    LV.mergeVisibility(argsLV);
543
  LV.mergeExternalVisibility(argsLV);
544
}
545

546
static bool useInlineVisibilityHidden(const NamedDecl *D) {
547
  // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
548
  const LangOptions &Opts = D->getASTContext().getLangOpts();
549
  if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
550
    return false;
551

552
  const auto *FD = dyn_cast<FunctionDecl>(D);
553
  if (!FD)
554
    return false;
555

556
  TemplateSpecializationKind TSK = TSK_Undeclared;
557
  if (FunctionTemplateSpecializationInfo *spec
558
      = FD->getTemplateSpecializationInfo()) {
559
    TSK = spec->getTemplateSpecializationKind();
560
  } else if (MemberSpecializationInfo *MSI =
561
             FD->getMemberSpecializationInfo()) {
562
    TSK = MSI->getTemplateSpecializationKind();
563
  }
564

565
  const FunctionDecl *Def = nullptr;
566
  // InlineVisibilityHidden only applies to definitions, and
567
  // isInlined() only gives meaningful answers on definitions
568
  // anyway.
569
  return TSK != TSK_ExplicitInstantiationDeclaration &&
570
    TSK != TSK_ExplicitInstantiationDefinition &&
571
    FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
572
}
573

574
template <typename T> static bool isFirstInExternCContext(T *D) {
575
  const T *First = D->getFirstDecl();
576
  return First->isInExternCContext();
577
}
578

579
static bool isSingleLineLanguageLinkage(const Decl &D) {
580
  if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
581
    if (!SD->hasBraces())
582
      return true;
583
  return false;
584
}
585

586
static bool isDeclaredInModuleInterfaceOrPartition(const NamedDecl *D) {
587
  if (auto *M = D->getOwningModule())
588
    return M->isInterfaceOrPartition();
589
  return false;
590
}
591

592
static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
593
  return LinkageInfo::external();
594
}
595

596
static StorageClass getStorageClass(const Decl *D) {
597
  if (auto *TD = dyn_cast<TemplateDecl>(D))
598
    D = TD->getTemplatedDecl();
599
  if (D) {
600
    if (auto *VD = dyn_cast<VarDecl>(D))
601
      return VD->getStorageClass();
602
    if (auto *FD = dyn_cast<FunctionDecl>(D))
603
      return FD->getStorageClass();
604
  }
605
  return SC_None;
606
}
607

608
LinkageInfo
609
LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
610
                                            LVComputationKind computation,
611
                                            bool IgnoreVarTypeLinkage) {
612
  assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
613
         "Not a name having namespace scope");
614
  ASTContext &Context = D->getASTContext();
615
  const auto *Var = dyn_cast<VarDecl>(D);
616

617
  // C++ [basic.link]p3:
618
  //   A name having namespace scope (3.3.6) has internal linkage if it
619
  //   is the name of
620

621
  if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) ||
622
      (Context.getLangOpts().C23 && Var && Var->isConstexpr())) {
623
    // - a variable, variable template, function, or function template
624
    //   that is explicitly declared static; or
625
    // (This bullet corresponds to C99 6.2.2p3.)
626

627
    // C23 6.2.2p3
628
    // If the declaration of a file scope identifier for
629
    // an object contains any of the storage-class specifiers static or
630
    // constexpr then the identifier has internal linkage.
631
    return LinkageInfo::internal();
632
  }
633

634
  if (Var) {
635
    // - a non-template variable of non-volatile const-qualified type, unless
636
    //   - it is explicitly declared extern, or
637
    //   - it is declared in the purview of a module interface unit
638
    //     (outside the private-module-fragment, if any) or module partition, or
639
    //   - it is inline, or
640
    //   - it was previously declared and the prior declaration did not have
641
    //     internal linkage
642
    // (There is no equivalent in C99.)
643
    if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
644
        !Var->getType().isVolatileQualified() && !Var->isInline() &&
645
        !isDeclaredInModuleInterfaceOrPartition(Var) &&
646
        !isa<VarTemplateSpecializationDecl>(Var) &&
647
        !Var->getDescribedVarTemplate()) {
648
      const VarDecl *PrevVar = Var->getPreviousDecl();
649
      if (PrevVar)
650
        return getLVForDecl(PrevVar, computation);
651

652
      if (Var->getStorageClass() != SC_Extern &&
653
          Var->getStorageClass() != SC_PrivateExtern &&
654
          !isSingleLineLanguageLinkage(*Var))
655
        return LinkageInfo::internal();
656
    }
657

658
    for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
659
         PrevVar = PrevVar->getPreviousDecl()) {
660
      if (PrevVar->getStorageClass() == SC_PrivateExtern &&
661
          Var->getStorageClass() == SC_None)
662
        return getDeclLinkageAndVisibility(PrevVar);
663
      // Explicitly declared static.
664
      if (PrevVar->getStorageClass() == SC_Static)
665
        return LinkageInfo::internal();
666
    }
667
  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668
    //   - a data member of an anonymous union.
669
    const VarDecl *VD = IFD->getVarDecl();
670
    assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
671
    return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
672
  }
673
  assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
674

675
  // FIXME: This gives internal linkage to names that should have no linkage
676
  // (those not covered by [basic.link]p6).
677
  if (D->isInAnonymousNamespace()) {
678
    const auto *Var = dyn_cast<VarDecl>(D);
679
    const auto *Func = dyn_cast<FunctionDecl>(D);
680
    // FIXME: The check for extern "C" here is not justified by the standard
681
    // wording, but we retain it from the pre-DR1113 model to avoid breaking
682
    // code.
683
    //
684
    // C++11 [basic.link]p4:
685
    //   An unnamed namespace or a namespace declared directly or indirectly
686
    //   within an unnamed namespace has internal linkage.
687
    if ((!Var || !isFirstInExternCContext(Var)) &&
688
        (!Func || !isFirstInExternCContext(Func)))
689
      return LinkageInfo::internal();
690
  }
691

692
  // Set up the defaults.
693

694
  // C99 6.2.2p5:
695
  //   If the declaration of an identifier for an object has file
696
  //   scope and no storage-class specifier, its linkage is
697
  //   external.
698
  LinkageInfo LV = getExternalLinkageFor(D);
699

700
  if (!hasExplicitVisibilityAlready(computation)) {
701
    if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
702
      LV.mergeVisibility(*Vis, true);
703
    } else {
704
      // If we're declared in a namespace with a visibility attribute,
705
      // use that namespace's visibility, and it still counts as explicit.
706
      for (const DeclContext *DC = D->getDeclContext();
707
           !isa<TranslationUnitDecl>(DC);
708
           DC = DC->getParent()) {
709
        const auto *ND = dyn_cast<NamespaceDecl>(DC);
710
        if (!ND) continue;
711
        if (std::optional<Visibility> Vis =
712
                getExplicitVisibility(ND, computation)) {
713
          LV.mergeVisibility(*Vis, true);
714
          break;
715
        }
716
      }
717
    }
718

719
    // Add in global settings if the above didn't give us direct visibility.
720
    if (!LV.isVisibilityExplicit()) {
721
      // Use global type/value visibility as appropriate.
722
      Visibility globalVisibility =
723
          computation.isValueVisibility()
724
              ? Context.getLangOpts().getValueVisibilityMode()
725
              : Context.getLangOpts().getTypeVisibilityMode();
726
      LV.mergeVisibility(globalVisibility, /*explicit*/ false);
727

728
      // If we're paying attention to global visibility, apply
729
      // -finline-visibility-hidden if this is an inline method.
730
      if (useInlineVisibilityHidden(D))
731
        LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
732
    }
733
  }
734

735
  // C++ [basic.link]p4:
736

737
  //   A name having namespace scope that has not been given internal linkage
738
  //   above and that is the name of
739
  //   [...bullets...]
740
  //   has its linkage determined as follows:
741
  //     - if the enclosing namespace has internal linkage, the name has
742
  //       internal linkage; [handled above]
743
  //     - otherwise, if the declaration of the name is attached to a named
744
  //       module and is not exported, the name has module linkage;
745
  //     - otherwise, the name has external linkage.
746
  // LV is currently set up to handle the last two bullets.
747
  //
748
  //   The bullets are:
749

750
  //     - a variable; or
751
  if (const auto *Var = dyn_cast<VarDecl>(D)) {
752
    // GCC applies the following optimization to variables and static
753
    // data members, but not to functions:
754
    //
755
    // Modify the variable's LV by the LV of its type unless this is
756
    // C or extern "C".  This follows from [basic.link]p9:
757
    //   A type without linkage shall not be used as the type of a
758
    //   variable or function with external linkage unless
759
    //    - the entity has C language linkage, or
760
    //    - the entity is declared within an unnamed namespace, or
761
    //    - the entity is not used or is defined in the same
762
    //      translation unit.
763
    // and [basic.link]p10:
764
    //   ...the types specified by all declarations referring to a
765
    //   given variable or function shall be identical...
766
    // C does not have an equivalent rule.
767
    //
768
    // Ignore this if we've got an explicit attribute;  the user
769
    // probably knows what they're doing.
770
    //
771
    // Note that we don't want to make the variable non-external
772
    // because of this, but unique-external linkage suits us.
773

774
    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
775
        !IgnoreVarTypeLinkage) {
776
      LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
777
      if (!isExternallyVisible(TypeLV.getLinkage()))
778
        return LinkageInfo::uniqueExternal();
779
      if (!LV.isVisibilityExplicit())
780
        LV.mergeVisibility(TypeLV);
781
    }
782

783
    if (Var->getStorageClass() == SC_PrivateExtern)
784
      LV.mergeVisibility(HiddenVisibility, true);
785

786
    // Note that Sema::MergeVarDecl already takes care of implementing
787
    // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
788
    // to do it here.
789

790
    // As per function and class template specializations (below),
791
    // consider LV for the template and template arguments.  We're at file
792
    // scope, so we do not need to worry about nested specializations.
793
    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
794
      mergeTemplateLV(LV, spec, computation);
795
    }
796

797
  //     - a function; or
798
  } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
799
    // In theory, we can modify the function's LV by the LV of its
800
    // type unless it has C linkage (see comment above about variables
801
    // for justification).  In practice, GCC doesn't do this, so it's
802
    // just too painful to make work.
803

804
    if (Function->getStorageClass() == SC_PrivateExtern)
805
      LV.mergeVisibility(HiddenVisibility, true);
806

807
    // OpenMP target declare device functions are not callable from the host so
808
    // they should not be exported from the device image. This applies to all
809
    // functions as the host-callable kernel functions are emitted at codegen.
810
    if (Context.getLangOpts().OpenMP &&
811
        Context.getLangOpts().OpenMPIsTargetDevice &&
812
        ((Context.getTargetInfo().getTriple().isAMDGPU() ||
813
          Context.getTargetInfo().getTriple().isNVPTX()) ||
814
         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
815
      LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
816

817
    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
818
    // merging storage classes and visibility attributes, so we don't have to
819
    // look at previous decls in here.
820

821
    // In C++, then if the type of the function uses a type with
822
    // unique-external linkage, it's not legally usable from outside
823
    // this translation unit.  However, we should use the C linkage
824
    // rules instead for extern "C" declarations.
825
    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
826
      // Only look at the type-as-written. Otherwise, deducing the return type
827
      // of a function could change its linkage.
828
      QualType TypeAsWritten = Function->getType();
829
      if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
830
        TypeAsWritten = TSI->getType();
831
      if (!isExternallyVisible(TypeAsWritten->getLinkage()))
832
        return LinkageInfo::uniqueExternal();
833
    }
834

835
    // Consider LV from the template and the template arguments.
836
    // We're at file scope, so we do not need to worry about nested
837
    // specializations.
838
    if (FunctionTemplateSpecializationInfo *specInfo
839
                               = Function->getTemplateSpecializationInfo()) {
840
      mergeTemplateLV(LV, Function, specInfo, computation);
841
    }
842

843
  //     - a named class (Clause 9), or an unnamed class defined in a
844
  //       typedef declaration in which the class has the typedef name
845
  //       for linkage purposes (7.1.3); or
846
  //     - a named enumeration (7.2), or an unnamed enumeration
847
  //       defined in a typedef declaration in which the enumeration
848
  //       has the typedef name for linkage purposes (7.1.3); or
849
  } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
850
    // Unnamed tags have no linkage.
851
    if (!Tag->hasNameForLinkage())
852
      return LinkageInfo::none();
853

854
    // If this is a class template specialization, consider the
855
    // linkage of the template and template arguments.  We're at file
856
    // scope, so we do not need to worry about nested specializations.
857
    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
858
      mergeTemplateLV(LV, spec, computation);
859
    }
860

861
  // FIXME: This is not part of the C++ standard any more.
862
  //     - an enumerator belonging to an enumeration with external linkage; or
863
  } else if (isa<EnumConstantDecl>(D)) {
864
    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
865
                                      computation);
866
    if (!isExternalFormalLinkage(EnumLV.getLinkage()))
867
      return LinkageInfo::none();
868
    LV.merge(EnumLV);
869

870
  //     - a template
871
  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
872
    bool considerVisibility = !hasExplicitVisibilityAlready(computation);
873
    LinkageInfo tempLV =
874
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
875
    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
876

877
  //     An unnamed namespace or a namespace declared directly or indirectly
878
  //     within an unnamed namespace has internal linkage. All other namespaces
879
  //     have external linkage.
880
  //
881
  // We handled names in anonymous namespaces above.
882
  } else if (isa<NamespaceDecl>(D)) {
883
    return LV;
884

885
  // By extension, we assign external linkage to Objective-C
886
  // interfaces.
887
  } else if (isa<ObjCInterfaceDecl>(D)) {
888
    // fallout
889

890
  } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
891
    // A typedef declaration has linkage if it gives a type a name for
892
    // linkage purposes.
893
    if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
894
      return LinkageInfo::none();
895

896
  } else if (isa<MSGuidDecl>(D)) {
897
    // A GUID behaves like an inline variable with external linkage. Fall
898
    // through.
899

900
  // Everything not covered here has no linkage.
901
  } else {
902
    return LinkageInfo::none();
903
  }
904

905
  // If we ended up with non-externally-visible linkage, visibility should
906
  // always be default.
907
  if (!isExternallyVisible(LV.getLinkage()))
908
    return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
909

910
  return LV;
911
}
912

913
LinkageInfo
914
LinkageComputer::getLVForClassMember(const NamedDecl *D,
915
                                     LVComputationKind computation,
916
                                     bool IgnoreVarTypeLinkage) {
917
  // Only certain class members have linkage.  Note that fields don't
918
  // really have linkage, but it's convenient to say they do for the
919
  // purposes of calculating linkage of pointer-to-data-member
920
  // template arguments.
921
  //
922
  // Templates also don't officially have linkage, but since we ignore
923
  // the C++ standard and look at template arguments when determining
924
  // linkage and visibility of a template specialization, we might hit
925
  // a template template argument that way. If we do, we need to
926
  // consider its linkage.
927
  if (!(isa<CXXMethodDecl>(D) ||
928
        isa<VarDecl>(D) ||
929
        isa<FieldDecl>(D) ||
930
        isa<IndirectFieldDecl>(D) ||
931
        isa<TagDecl>(D) ||
932
        isa<TemplateDecl>(D)))
933
    return LinkageInfo::none();
934

935
  LinkageInfo LV;
936

937
  // If we have an explicit visibility attribute, merge that in.
938
  if (!hasExplicitVisibilityAlready(computation)) {
939
    if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
940
      LV.mergeVisibility(*Vis, true);
941
    // If we're paying attention to global visibility, apply
942
    // -finline-visibility-hidden if this is an inline method.
943
    //
944
    // Note that we do this before merging information about
945
    // the class visibility.
946
    if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
947
      LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
948
  }
949

950
  // If this class member has an explicit visibility attribute, the only
951
  // thing that can change its visibility is the template arguments, so
952
  // only look for them when processing the class.
953
  LVComputationKind classComputation = computation;
954
  if (LV.isVisibilityExplicit())
955
    classComputation = withExplicitVisibilityAlready(computation);
956

957
  LinkageInfo classLV =
958
    getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
959
  // The member has the same linkage as the class. If that's not externally
960
  // visible, we don't need to compute anything about the linkage.
961
  // FIXME: If we're only computing linkage, can we bail out here?
962
  if (!isExternallyVisible(classLV.getLinkage()))
963
    return classLV;
964

965

966
  // Otherwise, don't merge in classLV yet, because in certain cases
967
  // we need to completely ignore the visibility from it.
968

969
  // Specifically, if this decl exists and has an explicit attribute.
970
  const NamedDecl *explicitSpecSuppressor = nullptr;
971

972
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
973
    // Only look at the type-as-written. Otherwise, deducing the return type
974
    // of a function could change its linkage.
975
    QualType TypeAsWritten = MD->getType();
976
    if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
977
      TypeAsWritten = TSI->getType();
978
    if (!isExternallyVisible(TypeAsWritten->getLinkage()))
979
      return LinkageInfo::uniqueExternal();
980

981
    // If this is a method template specialization, use the linkage for
982
    // the template parameters and arguments.
983
    if (FunctionTemplateSpecializationInfo *spec
984
           = MD->getTemplateSpecializationInfo()) {
985
      mergeTemplateLV(LV, MD, spec, computation);
986
      if (spec->isExplicitSpecialization()) {
987
        explicitSpecSuppressor = MD;
988
      } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
989
        explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
990
      }
991
    } else if (isExplicitMemberSpecialization(MD)) {
992
      explicitSpecSuppressor = MD;
993
    }
994

995
    // OpenMP target declare device functions are not callable from the host so
996
    // they should not be exported from the device image. This applies to all
997
    // functions as the host-callable kernel functions are emitted at codegen.
998
    ASTContext &Context = D->getASTContext();
999
    if (Context.getLangOpts().OpenMP &&
1000
        Context.getLangOpts().OpenMPIsTargetDevice &&
1001
        ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1002
          Context.getTargetInfo().getTriple().isNVPTX()) ||
1003
         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1004
      LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1005

1006
  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1007
    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1008
      mergeTemplateLV(LV, spec, computation);
1009
      if (spec->isExplicitSpecialization()) {
1010
        explicitSpecSuppressor = spec;
1011
      } else {
1012
        const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1013
        if (isExplicitMemberSpecialization(temp)) {
1014
          explicitSpecSuppressor = temp->getTemplatedDecl();
1015
        }
1016
      }
1017
    } else if (isExplicitMemberSpecialization(RD)) {
1018
      explicitSpecSuppressor = RD;
1019
    }
1020

1021
  // Static data members.
1022
  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1023
    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1024
      mergeTemplateLV(LV, spec, computation);
1025

1026
    // Modify the variable's linkage by its type, but ignore the
1027
    // type's visibility unless it's a definition.
1028
    if (!IgnoreVarTypeLinkage) {
1029
      LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1030
      // FIXME: If the type's linkage is not externally visible, we can
1031
      // give this static data member UniqueExternalLinkage.
1032
      if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1033
        LV.mergeVisibility(typeLV);
1034
      LV.mergeExternalVisibility(typeLV);
1035
    }
1036

1037
    if (isExplicitMemberSpecialization(VD)) {
1038
      explicitSpecSuppressor = VD;
1039
    }
1040

1041
  // Template members.
1042
  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1043
    bool considerVisibility =
1044
      (!LV.isVisibilityExplicit() &&
1045
       !classLV.isVisibilityExplicit() &&
1046
       !hasExplicitVisibilityAlready(computation));
1047
    LinkageInfo tempLV =
1048
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1049
    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1050

1051
    if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1052
      if (isExplicitMemberSpecialization(redeclTemp)) {
1053
        explicitSpecSuppressor = temp->getTemplatedDecl();
1054
      }
1055
    }
1056
  }
1057

1058
  // We should never be looking for an attribute directly on a template.
1059
  assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1060

1061
  // If this member is an explicit member specialization, and it has
1062
  // an explicit attribute, ignore visibility from the parent.
1063
  bool considerClassVisibility = true;
1064
  if (explicitSpecSuppressor &&
1065
      // optimization: hasDVA() is true only with explicit visibility.
1066
      LV.isVisibilityExplicit() &&
1067
      classLV.getVisibility() != DefaultVisibility &&
1068
      hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1069
    considerClassVisibility = false;
1070
  }
1071

1072
  // Finally, merge in information from the class.
1073
  LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1074
  return LV;
1075
}
1076

1077
void NamedDecl::anchor() {}
1078

1079
bool NamedDecl::isLinkageValid() const {
1080
  if (!hasCachedLinkage())
1081
    return true;
1082

1083
  Linkage L = LinkageComputer{}
1084
                  .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1085
                  .getLinkage();
1086
  return L == getCachedLinkage();
1087
}
1088

1089
bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {
1090
  // [C++2c] [basic.scope.scope]/p5
1091
  // A declaration is name-independent if its name is _ and it declares
1092
  // - a variable with automatic storage duration,
1093
  // - a structured binding not inhabiting a namespace scope,
1094
  // - the variable introduced by an init-capture
1095
  // - or a non-static data member.
1096

1097
  if (!LangOpts.CPlusPlus || !getIdentifier() ||
1098
      !getIdentifier()->isPlaceholder())
1099
    return false;
1100
  if (isa<FieldDecl>(this))
1101
    return true;
1102
  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {
1103
    if (!getDeclContext()->isFunctionOrMethod() &&
1104
        !getDeclContext()->isRecord())
1105
      return false;
1106
    const VarDecl *VD = IFD->getVarDecl();
1107
    return !VD || VD->getStorageDuration() == SD_Automatic;
1108
  }
1109
  // and it declares a variable with automatic storage duration
1110
  if (const auto *VD = dyn_cast<VarDecl>(this)) {
1111
    if (isa<ParmVarDecl>(VD))
1112
      return false;
1113
    if (VD->isInitCapture())
1114
      return true;
1115
    return VD->getStorageDuration() == StorageDuration::SD_Automatic;
1116
  }
1117
  if (const auto *BD = dyn_cast<BindingDecl>(this);
1118
      BD && getDeclContext()->isFunctionOrMethod()) {
1119
    const VarDecl *VD = BD->getHoldingVar();
1120
    return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic;
1121
  }
1122
  return false;
1123
}
1124

1125
ReservedIdentifierStatus
1126
NamedDecl::isReserved(const LangOptions &LangOpts) const {
1127
  const IdentifierInfo *II = getIdentifier();
1128

1129
  // This triggers at least for CXXLiteralIdentifiers, which we already checked
1130
  // at lexing time.
1131
  if (!II)
1132
    return ReservedIdentifierStatus::NotReserved;
1133

1134
  ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1135
  if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1136
    // This name is only reserved at global scope. Check if this declaration
1137
    // conflicts with a global scope declaration.
1138
    if (isa<ParmVarDecl>(this) || isTemplateParameter())
1139
      return ReservedIdentifierStatus::NotReserved;
1140

1141
    // C++ [dcl.link]/7:
1142
    //   Two declarations [conflict] if [...] one declares a function or
1143
    //   variable with C language linkage, and the other declares [...] a
1144
    //   variable that belongs to the global scope.
1145
    //
1146
    // Therefore names that are reserved at global scope are also reserved as
1147
    // names of variables and functions with C language linkage.
1148
    const DeclContext *DC = getDeclContext()->getRedeclContext();
1149
    if (DC->isTranslationUnit())
1150
      return Status;
1151
    if (auto *VD = dyn_cast<VarDecl>(this))
1152
      if (VD->isExternC())
1153
        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1154
    if (auto *FD = dyn_cast<FunctionDecl>(this))
1155
      if (FD->isExternC())
1156
        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1157
    return ReservedIdentifierStatus::NotReserved;
1158
  }
1159

1160
  return Status;
1161
}
1162

1163
ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1164
  StringRef name = getName();
1165
  if (name.empty()) return SFF_None;
1166

1167
  if (name.front() == 'C')
1168
    if (name == "CFStringCreateWithFormat" ||
1169
        name == "CFStringCreateWithFormatAndArguments" ||
1170
        name == "CFStringAppendFormat" ||
1171
        name == "CFStringAppendFormatAndArguments")
1172
      return SFF_CFString;
1173
  return SFF_None;
1174
}
1175

1176
Linkage NamedDecl::getLinkageInternal() const {
1177
  // We don't care about visibility here, so ask for the cheapest
1178
  // possible visibility analysis.
1179
  return LinkageComputer{}
1180
      .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1181
      .getLinkage();
1182
}
1183

1184
/// Determine whether D is attached to a named module.
1185
static bool isInNamedModule(const NamedDecl *D) {
1186
  if (auto *M = D->getOwningModule())
1187
    return M->isNamedModule();
1188
  return false;
1189
}
1190

1191
static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
1192
  // FIXME: Handle isModulePrivate.
1193
  switch (D->getModuleOwnershipKind()) {
1194
  case Decl::ModuleOwnershipKind::Unowned:
1195
  case Decl::ModuleOwnershipKind::ReachableWhenImported:
1196
  case Decl::ModuleOwnershipKind::ModulePrivate:
1197
    return false;
1198
  case Decl::ModuleOwnershipKind::Visible:
1199
  case Decl::ModuleOwnershipKind::VisibleWhenImported:
1200
    return isInNamedModule(D);
1201
  }
1202
  llvm_unreachable("unexpected module ownership kind");
1203
}
1204

1205
/// Get the linkage from a semantic point of view. Entities in
1206
/// anonymous namespaces are external (in c++98).
1207
Linkage NamedDecl::getFormalLinkage() const {
1208
  Linkage InternalLinkage = getLinkageInternal();
1209

1210
  // C++ [basic.link]p4.8:
1211
  //   - if the declaration of the name is attached to a named module and is not
1212
  //   exported
1213
  //     the name has module linkage;
1214
  //
1215
  // [basic.namespace.general]/p2
1216
  //   A namespace is never attached to a named module and never has a name with
1217
  //   module linkage.
1218
  if (isInNamedModule(this) && InternalLinkage == Linkage::External &&
1219
      !isExportedFromModuleInterfaceUnit(
1220
          cast<NamedDecl>(this->getCanonicalDecl())) &&
1221
      !isa<NamespaceDecl>(this))
1222
    InternalLinkage = Linkage::Module;
1223

1224
  return clang::getFormalLinkage(InternalLinkage);
1225
}
1226

1227
LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1228
  return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1229
}
1230

1231
static std::optional<Visibility>
1232
getExplicitVisibilityAux(const NamedDecl *ND,
1233
                         NamedDecl::ExplicitVisibilityKind kind,
1234
                         bool IsMostRecent) {
1235
  assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1236

1237
  // Check the declaration itself first.
1238
  if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1239
    return V;
1240

1241
  // If this is a member class of a specialization of a class template
1242
  // and the corresponding decl has explicit visibility, use that.
1243
  if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1244
    CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1245
    if (InstantiatedFrom)
1246
      return getVisibilityOf(InstantiatedFrom, kind);
1247
  }
1248

1249
  // If there wasn't explicit visibility there, and this is a
1250
  // specialization of a class template, check for visibility
1251
  // on the pattern.
1252
  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1253
    // Walk all the template decl till this point to see if there are
1254
    // explicit visibility attributes.
1255
    const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1256
    while (TD != nullptr) {
1257
      auto Vis = getVisibilityOf(TD, kind);
1258
      if (Vis != std::nullopt)
1259
        return Vis;
1260
      TD = TD->getPreviousDecl();
1261
    }
1262
    return std::nullopt;
1263
  }
1264

1265
  // Use the most recent declaration.
1266
  if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1267
    const NamedDecl *MostRecent = ND->getMostRecentDecl();
1268
    if (MostRecent != ND)
1269
      return getExplicitVisibilityAux(MostRecent, kind, true);
1270
  }
1271

1272
  if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1273
    if (Var->isStaticDataMember()) {
1274
      VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1275
      if (InstantiatedFrom)
1276
        return getVisibilityOf(InstantiatedFrom, kind);
1277
    }
1278

1279
    if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1280
      return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1281
                             kind);
1282

1283
    return std::nullopt;
1284
  }
1285
  // Also handle function template specializations.
1286
  if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1287
    // If the function is a specialization of a template with an
1288
    // explicit visibility attribute, use that.
1289
    if (FunctionTemplateSpecializationInfo *templateInfo
1290
          = fn->getTemplateSpecializationInfo())
1291
      return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1292
                             kind);
1293

1294
    // If the function is a member of a specialization of a class template
1295
    // and the corresponding decl has explicit visibility, use that.
1296
    FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1297
    if (InstantiatedFrom)
1298
      return getVisibilityOf(InstantiatedFrom, kind);
1299

1300
    return std::nullopt;
1301
  }
1302

1303
  // The visibility of a template is stored in the templated decl.
1304
  if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1305
    return getVisibilityOf(TD->getTemplatedDecl(), kind);
1306

1307
  return std::nullopt;
1308
}
1309

1310
std::optional<Visibility>
1311
NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1312
  return getExplicitVisibilityAux(this, kind, false);
1313
}
1314

1315
LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1316
                                             Decl *ContextDecl,
1317
                                             LVComputationKind computation) {
1318
  // This lambda has its linkage/visibility determined by its owner.
1319
  const NamedDecl *Owner;
1320
  if (!ContextDecl)
1321
    Owner = dyn_cast<NamedDecl>(DC);
1322
  else if (isa<ParmVarDecl>(ContextDecl))
1323
    Owner =
1324
        dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1325
  else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1326
    // Replace with the concept's owning decl, which is either a namespace or a
1327
    // TU, so this needs a dyn_cast.
1328
    Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1329
  } else {
1330
    Owner = cast<NamedDecl>(ContextDecl);
1331
  }
1332

1333
  if (!Owner)
1334
    return LinkageInfo::none();
1335

1336
  // If the owner has a deduced type, we need to skip querying the linkage and
1337
  // visibility of that type, because it might involve this closure type.  The
1338
  // only effect of this is that we might give a lambda VisibleNoLinkage rather
1339
  // than NoLinkage when we don't strictly need to, which is benign.
1340
  auto *VD = dyn_cast<VarDecl>(Owner);
1341
  LinkageInfo OwnerLV =
1342
      VD && VD->getType()->getContainedDeducedType()
1343
          ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1344
          : getLVForDecl(Owner, computation);
1345

1346
  // A lambda never formally has linkage. But if the owner is externally
1347
  // visible, then the lambda is too. We apply the same rules to blocks.
1348
  if (!isExternallyVisible(OwnerLV.getLinkage()))
1349
    return LinkageInfo::none();
1350
  return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(),
1351
                     OwnerLV.isVisibilityExplicit());
1352
}
1353

1354
LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1355
                                               LVComputationKind computation) {
1356
  if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1357
    if (Function->isInAnonymousNamespace() &&
1358
        !isFirstInExternCContext(Function))
1359
      return LinkageInfo::internal();
1360

1361
    // This is a "void f();" which got merged with a file static.
1362
    if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1363
      return LinkageInfo::internal();
1364

1365
    LinkageInfo LV;
1366
    if (!hasExplicitVisibilityAlready(computation)) {
1367
      if (std::optional<Visibility> Vis =
1368
              getExplicitVisibility(Function, computation))
1369
        LV.mergeVisibility(*Vis, true);
1370
    }
1371

1372
    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1373
    // merging storage classes and visibility attributes, so we don't have to
1374
    // look at previous decls in here.
1375

1376
    return LV;
1377
  }
1378

1379
  if (const auto *Var = dyn_cast<VarDecl>(D)) {
1380
    if (Var->hasExternalStorage()) {
1381
      if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1382
        return LinkageInfo::internal();
1383

1384
      LinkageInfo LV;
1385
      if (Var->getStorageClass() == SC_PrivateExtern)
1386
        LV.mergeVisibility(HiddenVisibility, true);
1387
      else if (!hasExplicitVisibilityAlready(computation)) {
1388
        if (std::optional<Visibility> Vis =
1389
                getExplicitVisibility(Var, computation))
1390
          LV.mergeVisibility(*Vis, true);
1391
      }
1392

1393
      if (const VarDecl *Prev = Var->getPreviousDecl()) {
1394
        LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1395
        if (PrevLV.getLinkage() != Linkage::Invalid)
1396
          LV.setLinkage(PrevLV.getLinkage());
1397
        LV.mergeVisibility(PrevLV);
1398
      }
1399

1400
      return LV;
1401
    }
1402

1403
    if (!Var->isStaticLocal())
1404
      return LinkageInfo::none();
1405
  }
1406

1407
  ASTContext &Context = D->getASTContext();
1408
  if (!Context.getLangOpts().CPlusPlus)
1409
    return LinkageInfo::none();
1410

1411
  const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1412
  if (!OuterD || OuterD->isInvalidDecl())
1413
    return LinkageInfo::none();
1414

1415
  LinkageInfo LV;
1416
  if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1417
    if (!BD->getBlockManglingNumber())
1418
      return LinkageInfo::none();
1419

1420
    LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1421
                         BD->getBlockManglingContextDecl(), computation);
1422
  } else {
1423
    const auto *FD = cast<FunctionDecl>(OuterD);
1424
    if (!FD->isInlined() &&
1425
        !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1426
      return LinkageInfo::none();
1427

1428
    // If a function is hidden by -fvisibility-inlines-hidden option and
1429
    // is not explicitly attributed as a hidden function,
1430
    // we should not make static local variables in the function hidden.
1431
    LV = getLVForDecl(FD, computation);
1432
    if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1433
        !LV.isVisibilityExplicit() &&
1434
        !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1435
      assert(cast<VarDecl>(D)->isStaticLocal());
1436
      // If this was an implicitly hidden inline method, check again for
1437
      // explicit visibility on the parent class, and use that for static locals
1438
      // if present.
1439
      if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1440
        LV = getLVForDecl(MD->getParent(), computation);
1441
      if (!LV.isVisibilityExplicit()) {
1442
        Visibility globalVisibility =
1443
            computation.isValueVisibility()
1444
                ? Context.getLangOpts().getValueVisibilityMode()
1445
                : Context.getLangOpts().getTypeVisibilityMode();
1446
        return LinkageInfo(Linkage::VisibleNone, globalVisibility,
1447
                           /*visibilityExplicit=*/false);
1448
      }
1449
    }
1450
  }
1451
  if (!isExternallyVisible(LV.getLinkage()))
1452
    return LinkageInfo::none();
1453
  return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(),
1454
                     LV.isVisibilityExplicit());
1455
}
1456

1457
LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1458
                                              LVComputationKind computation,
1459
                                              bool IgnoreVarTypeLinkage) {
1460
  // Internal_linkage attribute overrides other considerations.
1461
  if (D->hasAttr<InternalLinkageAttr>())
1462
    return LinkageInfo::internal();
1463

1464
  // Objective-C: treat all Objective-C declarations as having external
1465
  // linkage.
1466
  switch (D->getKind()) {
1467
    default:
1468
      break;
1469

1470
    // Per C++ [basic.link]p2, only the names of objects, references,
1471
    // functions, types, templates, namespaces, and values ever have linkage.
1472
    //
1473
    // Note that the name of a typedef, namespace alias, using declaration,
1474
    // and so on are not the name of the corresponding type, namespace, or
1475
    // declaration, so they do *not* have linkage.
1476
    case Decl::ImplicitParam:
1477
    case Decl::Label:
1478
    case Decl::NamespaceAlias:
1479
    case Decl::ParmVar:
1480
    case Decl::Using:
1481
    case Decl::UsingEnum:
1482
    case Decl::UsingShadow:
1483
    case Decl::UsingDirective:
1484
      return LinkageInfo::none();
1485

1486
    case Decl::EnumConstant:
1487
      // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1488
      if (D->getASTContext().getLangOpts().CPlusPlus)
1489
        return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1490
      return LinkageInfo::visible_none();
1491

1492
    case Decl::Typedef:
1493
    case Decl::TypeAlias:
1494
      // A typedef declaration has linkage if it gives a type a name for
1495
      // linkage purposes.
1496
      if (!cast<TypedefNameDecl>(D)
1497
               ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1498
        return LinkageInfo::none();
1499
      break;
1500

1501
    case Decl::TemplateTemplateParm: // count these as external
1502
    case Decl::NonTypeTemplateParm:
1503
    case Decl::ObjCAtDefsField:
1504
    case Decl::ObjCCategory:
1505
    case Decl::ObjCCategoryImpl:
1506
    case Decl::ObjCCompatibleAlias:
1507
    case Decl::ObjCImplementation:
1508
    case Decl::ObjCMethod:
1509
    case Decl::ObjCProperty:
1510
    case Decl::ObjCPropertyImpl:
1511
    case Decl::ObjCProtocol:
1512
      return getExternalLinkageFor(D);
1513

1514
    case Decl::CXXRecord: {
1515
      const auto *Record = cast<CXXRecordDecl>(D);
1516
      if (Record->isLambda()) {
1517
        if (Record->hasKnownLambdaInternalLinkage() ||
1518
            !Record->getLambdaManglingNumber()) {
1519
          // This lambda has no mangling number, so it's internal.
1520
          return LinkageInfo::internal();
1521
        }
1522

1523
        return getLVForClosure(
1524
                  Record->getDeclContext()->getRedeclContext(),
1525
                  Record->getLambdaContextDecl(), computation);
1526
      }
1527

1528
      break;
1529
    }
1530

1531
    case Decl::TemplateParamObject: {
1532
      // The template parameter object can be referenced from anywhere its type
1533
      // and value can be referenced.
1534
      auto *TPO = cast<TemplateParamObjectDecl>(D);
1535
      LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1536
      LV.merge(getLVForValue(TPO->getValue(), computation));
1537
      return LV;
1538
    }
1539
  }
1540

1541
  // Handle linkage for namespace-scope names.
1542
  if (D->getDeclContext()->getRedeclContext()->isFileContext())
1543
    return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1544

1545
  // C++ [basic.link]p5:
1546
  //   In addition, a member function, static data member, a named
1547
  //   class or enumeration of class scope, or an unnamed class or
1548
  //   enumeration defined in a class-scope typedef declaration such
1549
  //   that the class or enumeration has the typedef name for linkage
1550
  //   purposes (7.1.3), has external linkage if the name of the class
1551
  //   has external linkage.
1552
  if (D->getDeclContext()->isRecord())
1553
    return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1554

1555
  // C++ [basic.link]p6:
1556
  //   The name of a function declared in block scope and the name of
1557
  //   an object declared by a block scope extern declaration have
1558
  //   linkage. If there is a visible declaration of an entity with
1559
  //   linkage having the same name and type, ignoring entities
1560
  //   declared outside the innermost enclosing namespace scope, the
1561
  //   block scope declaration declares that same entity and receives
1562
  //   the linkage of the previous declaration. If there is more than
1563
  //   one such matching entity, the program is ill-formed. Otherwise,
1564
  //   if no matching entity is found, the block scope entity receives
1565
  //   external linkage.
1566
  if (D->getDeclContext()->isFunctionOrMethod())
1567
    return getLVForLocalDecl(D, computation);
1568

1569
  // C++ [basic.link]p6:
1570
  //   Names not covered by these rules have no linkage.
1571
  return LinkageInfo::none();
1572
}
1573

1574
/// getLVForDecl - Get the linkage and visibility for the given declaration.
1575
LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1576
                                          LVComputationKind computation) {
1577
  // Internal_linkage attribute overrides other considerations.
1578
  if (D->hasAttr<InternalLinkageAttr>())
1579
    return LinkageInfo::internal();
1580

1581
  if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1582
    return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1583

1584
  if (std::optional<LinkageInfo> LI = lookup(D, computation))
1585
    return *LI;
1586

1587
  LinkageInfo LV = computeLVForDecl(D, computation);
1588
  if (D->hasCachedLinkage())
1589
    assert(D->getCachedLinkage() == LV.getLinkage());
1590

1591
  D->setCachedLinkage(LV.getLinkage());
1592
  cache(D, computation, LV);
1593

1594
#ifndef NDEBUG
1595
  // In C (because of gnu inline) and in c++ with microsoft extensions an
1596
  // static can follow an extern, so we can have two decls with different
1597
  // linkages.
1598
  const LangOptions &Opts = D->getASTContext().getLangOpts();
1599
  if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1600
    return LV;
1601

1602
  // We have just computed the linkage for this decl. By induction we know
1603
  // that all other computed linkages match, check that the one we just
1604
  // computed also does.
1605
  NamedDecl *Old = nullptr;
1606
  for (auto *I : D->redecls()) {
1607
    auto *T = cast<NamedDecl>(I);
1608
    if (T == D)
1609
      continue;
1610
    if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1611
      Old = T;
1612
      break;
1613
    }
1614
  }
1615
  assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1616
#endif
1617

1618
  return LV;
1619
}
1620

1621
LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1622
  NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1623
                                             ? NamedDecl::VisibilityForType
1624
                                             : NamedDecl::VisibilityForValue;
1625
  LVComputationKind CK(EK);
1626
  return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1627
                             ? CK.forLinkageOnly()
1628
                             : CK);
1629
}
1630

1631
Module *Decl::getOwningModuleForLinkage() const {
1632
  if (isa<NamespaceDecl>(this))
1633
    // Namespaces never have module linkage.  It is the entities within them
1634
    // that [may] do.
1635
    return nullptr;
1636

1637
  Module *M = getOwningModule();
1638
  if (!M)
1639
    return nullptr;
1640

1641
  switch (M->Kind) {
1642
  case Module::ModuleMapModule:
1643
    // Module map modules have no special linkage semantics.
1644
    return nullptr;
1645

1646
  case Module::ModuleInterfaceUnit:
1647
  case Module::ModuleImplementationUnit:
1648
  case Module::ModulePartitionInterface:
1649
  case Module::ModulePartitionImplementation:
1650
    return M;
1651

1652
  case Module::ModuleHeaderUnit:
1653
  case Module::ExplicitGlobalModuleFragment:
1654
  case Module::ImplicitGlobalModuleFragment:
1655
    // The global module shouldn't change the linkage.
1656
    return nullptr;
1657

1658
  case Module::PrivateModuleFragment:
1659
    // The private module fragment is part of its containing module for linkage
1660
    // purposes.
1661
    return M->Parent;
1662
  }
1663

1664
  llvm_unreachable("unknown module kind");
1665
}
1666

1667
void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1668
  Name.print(OS, Policy);
1669
}
1670

1671
void NamedDecl::printName(raw_ostream &OS) const {
1672
  printName(OS, getASTContext().getPrintingPolicy());
1673
}
1674

1675
std::string NamedDecl::getQualifiedNameAsString() const {
1676
  std::string QualName;
1677
  llvm::raw_string_ostream OS(QualName);
1678
  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1679
  return QualName;
1680
}
1681

1682
void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1683
  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1684
}
1685

1686
void NamedDecl::printQualifiedName(raw_ostream &OS,
1687
                                   const PrintingPolicy &P) const {
1688
  if (getDeclContext()->isFunctionOrMethod()) {
1689
    // We do not print '(anonymous)' for function parameters without name.
1690
    printName(OS, P);
1691
    return;
1692
  }
1693
  printNestedNameSpecifier(OS, P);
1694
  if (getDeclName())
1695
    OS << *this;
1696
  else {
1697
    // Give the printName override a chance to pick a different name before we
1698
    // fall back to "(anonymous)".
1699
    SmallString<64> NameBuffer;
1700
    llvm::raw_svector_ostream NameOS(NameBuffer);
1701
    printName(NameOS, P);
1702
    if (NameBuffer.empty())
1703
      OS << "(anonymous)";
1704
    else
1705
      OS << NameBuffer;
1706
  }
1707
}
1708

1709
void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1710
  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1711
}
1712

1713
void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1714
                                         const PrintingPolicy &P) const {
1715
  const DeclContext *Ctx = getDeclContext();
1716

1717
  // For ObjC methods and properties, look through categories and use the
1718
  // interface as context.
1719
  if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1720
    if (auto *ID = MD->getClassInterface())
1721
      Ctx = ID;
1722
  } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1723
    if (auto *MD = PD->getGetterMethodDecl())
1724
      if (auto *ID = MD->getClassInterface())
1725
        Ctx = ID;
1726
  } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1727
    if (auto *CI = ID->getContainingInterface())
1728
      Ctx = CI;
1729
  }
1730

1731
  if (Ctx->isFunctionOrMethod())
1732
    return;
1733

1734
  using ContextsTy = SmallVector<const DeclContext *, 8>;
1735
  ContextsTy Contexts;
1736

1737
  // Collect named contexts.
1738
  DeclarationName NameInScope = getDeclName();
1739
  for (; Ctx; Ctx = Ctx->getParent()) {
1740
    // Suppress anonymous namespace if requested.
1741
    if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1742
        cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1743
      continue;
1744

1745
    // Suppress inline namespace if it doesn't make the result ambiguous.
1746
    if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1747
        cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1748
      continue;
1749

1750
    // Skip non-named contexts such as linkage specifications and ExportDecls.
1751
    const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1752
    if (!ND)
1753
      continue;
1754

1755
    Contexts.push_back(Ctx);
1756
    NameInScope = ND->getDeclName();
1757
  }
1758

1759
  for (const DeclContext *DC : llvm::reverse(Contexts)) {
1760
    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1761
      OS << Spec->getName();
1762
      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1763
      printTemplateArgumentList(
1764
          OS, TemplateArgs.asArray(), P,
1765
          Spec->getSpecializedTemplate()->getTemplateParameters());
1766
    } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1767
      if (ND->isAnonymousNamespace()) {
1768
        OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1769
                                : "(anonymous namespace)");
1770
      }
1771
      else
1772
        OS << *ND;
1773
    } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1774
      if (!RD->getIdentifier())
1775
        OS << "(anonymous " << RD->getKindName() << ')';
1776
      else
1777
        OS << *RD;
1778
    } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1779
      const FunctionProtoType *FT = nullptr;
1780
      if (FD->hasWrittenPrototype())
1781
        FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1782

1783
      OS << *FD << '(';
1784
      if (FT) {
1785
        unsigned NumParams = FD->getNumParams();
1786
        for (unsigned i = 0; i < NumParams; ++i) {
1787
          if (i)
1788
            OS << ", ";
1789
          OS << FD->getParamDecl(i)->getType().stream(P);
1790
        }
1791

1792
        if (FT->isVariadic()) {
1793
          if (NumParams > 0)
1794
            OS << ", ";
1795
          OS << "...";
1796
        }
1797
      }
1798
      OS << ')';
1799
    } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1800
      // C++ [dcl.enum]p10: Each enum-name and each unscoped
1801
      // enumerator is declared in the scope that immediately contains
1802
      // the enum-specifier. Each scoped enumerator is declared in the
1803
      // scope of the enumeration.
1804
      // For the case of unscoped enumerator, do not include in the qualified
1805
      // name any information about its enum enclosing scope, as its visibility
1806
      // is global.
1807
      if (ED->isScoped())
1808
        OS << *ED;
1809
      else
1810
        continue;
1811
    } else {
1812
      OS << *cast<NamedDecl>(DC);
1813
    }
1814
    OS << "::";
1815
  }
1816
}
1817

1818
void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1819
                                     const PrintingPolicy &Policy,
1820
                                     bool Qualified) const {
1821
  if (Qualified)
1822
    printQualifiedName(OS, Policy);
1823
  else
1824
    printName(OS, Policy);
1825
}
1826

1827
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1828
  return true;
1829
}
1830
static bool isRedeclarableImpl(...) { return false; }
1831
static bool isRedeclarable(Decl::Kind K) {
1832
  switch (K) {
1833
#define DECL(Type, Base) \
1834
  case Decl::Type: \
1835
    return isRedeclarableImpl((Type##Decl *)nullptr);
1836
#define ABSTRACT_DECL(DECL)
1837
#include "clang/AST/DeclNodes.inc"
1838
  }
1839
  llvm_unreachable("unknown decl kind");
1840
}
1841

1842
bool NamedDecl::declarationReplaces(const NamedDecl *OldD,
1843
                                    bool IsKnownNewer) const {
1844
  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1845

1846
  // Never replace one imported declaration with another; we need both results
1847
  // when re-exporting.
1848
  if (OldD->isFromASTFile() && isFromASTFile())
1849
    return false;
1850

1851
  // A kind mismatch implies that the declaration is not replaced.
1852
  if (OldD->getKind() != getKind())
1853
    return false;
1854

1855
  // For method declarations, we never replace. (Why?)
1856
  if (isa<ObjCMethodDecl>(this))
1857
    return false;
1858

1859
  // For parameters, pick the newer one. This is either an error or (in
1860
  // Objective-C) permitted as an extension.
1861
  if (isa<ParmVarDecl>(this))
1862
    return true;
1863

1864
  // Inline namespaces can give us two declarations with the same
1865
  // name and kind in the same scope but different contexts; we should
1866
  // keep both declarations in this case.
1867
  if (!this->getDeclContext()->getRedeclContext()->Equals(
1868
          OldD->getDeclContext()->getRedeclContext()))
1869
    return false;
1870

1871
  // Using declarations can be replaced if they import the same name from the
1872
  // same context.
1873
  if (const auto *UD = dyn_cast<UsingDecl>(this)) {
1874
    ASTContext &Context = getASTContext();
1875
    return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1876
           Context.getCanonicalNestedNameSpecifier(
1877
               cast<UsingDecl>(OldD)->getQualifier());
1878
  }
1879
  if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1880
    ASTContext &Context = getASTContext();
1881
    return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1882
           Context.getCanonicalNestedNameSpecifier(
1883
                        cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1884
  }
1885

1886
  if (isRedeclarable(getKind())) {
1887
    if (getCanonicalDecl() != OldD->getCanonicalDecl())
1888
      return false;
1889

1890
    if (IsKnownNewer)
1891
      return true;
1892

1893
    // Check whether this is actually newer than OldD. We want to keep the
1894
    // newer declaration. This loop will usually only iterate once, because
1895
    // OldD is usually the previous declaration.
1896
    for (const auto *D : redecls()) {
1897
      if (D == OldD)
1898
        break;
1899

1900
      // If we reach the canonical declaration, then OldD is not actually older
1901
      // than this one.
1902
      //
1903
      // FIXME: In this case, we should not add this decl to the lookup table.
1904
      if (D->isCanonicalDecl())
1905
        return false;
1906
    }
1907

1908
    // It's a newer declaration of the same kind of declaration in the same
1909
    // scope: we want this decl instead of the existing one.
1910
    return true;
1911
  }
1912

1913
  // In all other cases, we need to keep both declarations in case they have
1914
  // different visibility. Any attempt to use the name will result in an
1915
  // ambiguity if more than one is visible.
1916
  return false;
1917
}
1918

1919
bool NamedDecl::hasLinkage() const {
1920
  switch (getFormalLinkage()) {
1921
  case Linkage::Invalid:
1922
    llvm_unreachable("Linkage hasn't been computed!");
1923
  case Linkage::None:
1924
    return false;
1925
  case Linkage::Internal:
1926
    return true;
1927
  case Linkage::UniqueExternal:
1928
  case Linkage::VisibleNone:
1929
    llvm_unreachable("Non-formal linkage is not allowed here!");
1930
  case Linkage::Module:
1931
  case Linkage::External:
1932
    return true;
1933
  }
1934
  llvm_unreachable("Unhandled Linkage enum");
1935
}
1936

1937
NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1938
  NamedDecl *ND = this;
1939
  if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1940
    ND = UD->getTargetDecl();
1941

1942
  if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1943
    return AD->getClassInterface();
1944

1945
  if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1946
    return AD->getNamespace();
1947

1948
  return ND;
1949
}
1950

1951
bool NamedDecl::isCXXInstanceMember() const {
1952
  if (!isCXXClassMember())
1953
    return false;
1954

1955
  const NamedDecl *D = this;
1956
  if (isa<UsingShadowDecl>(D))
1957
    D = cast<UsingShadowDecl>(D)->getTargetDecl();
1958

1959
  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1960
    return true;
1961
  if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))
1962
    return MD->isInstance();
1963
  return false;
1964
}
1965

1966
//===----------------------------------------------------------------------===//
1967
// DeclaratorDecl Implementation
1968
//===----------------------------------------------------------------------===//
1969

1970
template <typename DeclT>
1971
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1972
  if (decl->getNumTemplateParameterLists() > 0)
1973
    return decl->getTemplateParameterList(0)->getTemplateLoc();
1974
  return decl->getInnerLocStart();
1975
}
1976

1977
SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1978
  TypeSourceInfo *TSI = getTypeSourceInfo();
1979
  if (TSI) return TSI->getTypeLoc().getBeginLoc();
1980
  return SourceLocation();
1981
}
1982

1983
SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1984
  TypeSourceInfo *TSI = getTypeSourceInfo();
1985
  if (TSI) return TSI->getTypeLoc().getEndLoc();
1986
  return SourceLocation();
1987
}
1988

1989
void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1990
  if (QualifierLoc) {
1991
    // Make sure the extended decl info is allocated.
1992
    if (!hasExtInfo()) {
1993
      // Save (non-extended) type source info pointer.
1994
      auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1995
      // Allocate external info struct.
1996
      DeclInfo = new (getASTContext()) ExtInfo;
1997
      // Restore savedTInfo into (extended) decl info.
1998
      getExtInfo()->TInfo = savedTInfo;
1999
    }
2000
    // Set qualifier info.
2001
    getExtInfo()->QualifierLoc = QualifierLoc;
2002
  } else if (hasExtInfo()) {
2003
    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2004
    getExtInfo()->QualifierLoc = QualifierLoc;
2005
  }
2006
}
2007

2008
void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
2009
  assert(TrailingRequiresClause);
2010
  // Make sure the extended decl info is allocated.
2011
  if (!hasExtInfo()) {
2012
    // Save (non-extended) type source info pointer.
2013
    auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2014
    // Allocate external info struct.
2015
    DeclInfo = new (getASTContext()) ExtInfo;
2016
    // Restore savedTInfo into (extended) decl info.
2017
    getExtInfo()->TInfo = savedTInfo;
2018
  }
2019
  // Set requires clause info.
2020
  getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
2021
}
2022

2023
void DeclaratorDecl::setTemplateParameterListsInfo(
2024
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2025
  assert(!TPLists.empty());
2026
  // Make sure the extended decl info is allocated.
2027
  if (!hasExtInfo()) {
2028
    // Save (non-extended) type source info pointer.
2029
    auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2030
    // Allocate external info struct.
2031
    DeclInfo = new (getASTContext()) ExtInfo;
2032
    // Restore savedTInfo into (extended) decl info.
2033
    getExtInfo()->TInfo = savedTInfo;
2034
  }
2035
  // Set the template parameter lists info.
2036
  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
2037
}
2038

2039
SourceLocation DeclaratorDecl::getOuterLocStart() const {
2040
  return getTemplateOrInnerLocStart(this);
2041
}
2042

2043
// Helper function: returns true if QT is or contains a type
2044
// having a postfix component.
2045
static bool typeIsPostfix(QualType QT) {
2046
  while (true) {
2047
    const Type* T = QT.getTypePtr();
2048
    switch (T->getTypeClass()) {
2049
    default:
2050
      return false;
2051
    case Type::Pointer:
2052
      QT = cast<PointerType>(T)->getPointeeType();
2053
      break;
2054
    case Type::BlockPointer:
2055
      QT = cast<BlockPointerType>(T)->getPointeeType();
2056
      break;
2057
    case Type::MemberPointer:
2058
      QT = cast<MemberPointerType>(T)->getPointeeType();
2059
      break;
2060
    case Type::LValueReference:
2061
    case Type::RValueReference:
2062
      QT = cast<ReferenceType>(T)->getPointeeType();
2063
      break;
2064
    case Type::PackExpansion:
2065
      QT = cast<PackExpansionType>(T)->getPattern();
2066
      break;
2067
    case Type::Paren:
2068
    case Type::ConstantArray:
2069
    case Type::DependentSizedArray:
2070
    case Type::IncompleteArray:
2071
    case Type::VariableArray:
2072
    case Type::FunctionProto:
2073
    case Type::FunctionNoProto:
2074
      return true;
2075
    }
2076
  }
2077
}
2078

2079
SourceRange DeclaratorDecl::getSourceRange() const {
2080
  SourceLocation RangeEnd = getLocation();
2081
  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2082
    // If the declaration has no name or the type extends past the name take the
2083
    // end location of the type.
2084
    if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2085
      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2086
  }
2087
  return SourceRange(getOuterLocStart(), RangeEnd);
2088
}
2089

2090
void QualifierInfo::setTemplateParameterListsInfo(
2091
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2092
  // Free previous template parameters (if any).
2093
  if (NumTemplParamLists > 0) {
2094
    Context.Deallocate(TemplParamLists);
2095
    TemplParamLists = nullptr;
2096
    NumTemplParamLists = 0;
2097
  }
2098
  // Set info on matched template parameter lists (if any).
2099
  if (!TPLists.empty()) {
2100
    TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2101
    NumTemplParamLists = TPLists.size();
2102
    std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2103
  }
2104
}
2105

2106
//===----------------------------------------------------------------------===//
2107
// VarDecl Implementation
2108
//===----------------------------------------------------------------------===//
2109

2110
const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
2111
  switch (SC) {
2112
  case SC_None:                 break;
2113
  case SC_Auto:                 return "auto";
2114
  case SC_Extern:               return "extern";
2115
  case SC_PrivateExtern:        return "__private_extern__";
2116
  case SC_Register:             return "register";
2117
  case SC_Static:               return "static";
2118
  }
2119

2120
  llvm_unreachable("Invalid storage class");
2121
}
2122

2123
VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2124
                 SourceLocation StartLoc, SourceLocation IdLoc,
2125
                 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2126
                 StorageClass SC)
2127
    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2128
      redeclarable_base(C) {
2129
  static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2130
                "VarDeclBitfields too large!");
2131
  static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2132
                "ParmVarDeclBitfields too large!");
2133
  static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2134
                "NonParmVarDeclBitfields too large!");
2135
  AllBits = 0;
2136
  VarDeclBits.SClass = SC;
2137
  // Everything else is implicitly initialized to false.
2138
}
2139

2140
VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,
2141
                         SourceLocation IdL, const IdentifierInfo *Id,
2142
                         QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2143
  return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2144
}
2145

2146
VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2147
  return new (C, ID)
2148
      VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2149
              QualType(), nullptr, SC_None);
2150
}
2151

2152
void VarDecl::setStorageClass(StorageClass SC) {
2153
  assert(isLegalForVariable(SC));
2154
  VarDeclBits.SClass = SC;
2155
}
2156

2157
VarDecl::TLSKind VarDecl::getTLSKind() const {
2158
  switch (VarDeclBits.TSCSpec) {
2159
  case TSCS_unspecified:
2160
    if (!hasAttr<ThreadAttr>() &&
2161
        !(getASTContext().getLangOpts().OpenMPUseTLS &&
2162
          getASTContext().getTargetInfo().isTLSSupported() &&
2163
          hasAttr<OMPThreadPrivateDeclAttr>()))
2164
      return TLS_None;
2165
    return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2166
                LangOptions::MSVC2015)) ||
2167
            hasAttr<OMPThreadPrivateDeclAttr>())
2168
               ? TLS_Dynamic
2169
               : TLS_Static;
2170
  case TSCS___thread: // Fall through.
2171
  case TSCS__Thread_local:
2172
    return TLS_Static;
2173
  case TSCS_thread_local:
2174
    return TLS_Dynamic;
2175
  }
2176
  llvm_unreachable("Unknown thread storage class specifier!");
2177
}
2178

2179
SourceRange VarDecl::getSourceRange() const {
2180
  if (const Expr *Init = getInit()) {
2181
    SourceLocation InitEnd = Init->getEndLoc();
2182
    // If Init is implicit, ignore its source range and fallback on
2183
    // DeclaratorDecl::getSourceRange() to handle postfix elements.
2184
    if (InitEnd.isValid() && InitEnd != getLocation())
2185
      return SourceRange(getOuterLocStart(), InitEnd);
2186
  }
2187
  return DeclaratorDecl::getSourceRange();
2188
}
2189

2190
template<typename T>
2191
static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2192
  // C++ [dcl.link]p1: All function types, function names with external linkage,
2193
  // and variable names with external linkage have a language linkage.
2194
  if (!D.hasExternalFormalLinkage())
2195
    return NoLanguageLinkage;
2196

2197
  // Language linkage is a C++ concept, but saying that everything else in C has
2198
  // C language linkage fits the implementation nicely.
2199
  if (!D.getASTContext().getLangOpts().CPlusPlus)
2200
    return CLanguageLinkage;
2201

2202
  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2203
  // language linkage of the names of class members and the function type of
2204
  // class member functions.
2205
  const DeclContext *DC = D.getDeclContext();
2206
  if (DC->isRecord())
2207
    return CXXLanguageLinkage;
2208

2209
  // If the first decl is in an extern "C" context, any other redeclaration
2210
  // will have C language linkage. If the first one is not in an extern "C"
2211
  // context, we would have reported an error for any other decl being in one.
2212
  if (isFirstInExternCContext(&D))
2213
    return CLanguageLinkage;
2214
  return CXXLanguageLinkage;
2215
}
2216

2217
template<typename T>
2218
static bool isDeclExternC(const T &D) {
2219
  // Since the context is ignored for class members, they can only have C++
2220
  // language linkage or no language linkage.
2221
  const DeclContext *DC = D.getDeclContext();
2222
  if (DC->isRecord()) {
2223
    assert(D.getASTContext().getLangOpts().CPlusPlus);
2224
    return false;
2225
  }
2226

2227
  return D.getLanguageLinkage() == CLanguageLinkage;
2228
}
2229

2230
LanguageLinkage VarDecl::getLanguageLinkage() const {
2231
  return getDeclLanguageLinkage(*this);
2232
}
2233

2234
bool VarDecl::isExternC() const {
2235
  return isDeclExternC(*this);
2236
}
2237

2238
bool VarDecl::isInExternCContext() const {
2239
  return getLexicalDeclContext()->isExternCContext();
2240
}
2241

2242
bool VarDecl::isInExternCXXContext() const {
2243
  return getLexicalDeclContext()->isExternCXXContext();
2244
}
2245

2246
VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2247

2248
VarDecl::DefinitionKind
2249
VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2250
  if (isThisDeclarationADemotedDefinition())
2251
    return DeclarationOnly;
2252

2253
  // C++ [basic.def]p2:
2254
  //   A declaration is a definition unless [...] it contains the 'extern'
2255
  //   specifier or a linkage-specification and neither an initializer [...],
2256
  //   it declares a non-inline static data member in a class declaration [...],
2257
  //   it declares a static data member outside a class definition and the variable
2258
  //   was defined within the class with the constexpr specifier [...],
2259
  // C++1y [temp.expl.spec]p15:
2260
  //   An explicit specialization of a static data member or an explicit
2261
  //   specialization of a static data member template is a definition if the
2262
  //   declaration includes an initializer; otherwise, it is a declaration.
2263
  //
2264
  // FIXME: How do you declare (but not define) a partial specialization of
2265
  // a static data member template outside the containing class?
2266
  if (isStaticDataMember()) {
2267
    if (isOutOfLine() &&
2268
        !(getCanonicalDecl()->isInline() &&
2269
          getCanonicalDecl()->isConstexpr()) &&
2270
        (hasInit() ||
2271
         // If the first declaration is out-of-line, this may be an
2272
         // instantiation of an out-of-line partial specialization of a variable
2273
         // template for which we have not yet instantiated the initializer.
2274
         (getFirstDecl()->isOutOfLine()
2275
              ? getTemplateSpecializationKind() == TSK_Undeclared
2276
              : getTemplateSpecializationKind() !=
2277
                    TSK_ExplicitSpecialization) ||
2278
         isa<VarTemplatePartialSpecializationDecl>(this)))
2279
      return Definition;
2280
    if (!isOutOfLine() && isInline())
2281
      return Definition;
2282
    return DeclarationOnly;
2283
  }
2284
  // C99 6.7p5:
2285
  //   A definition of an identifier is a declaration for that identifier that
2286
  //   [...] causes storage to be reserved for that object.
2287
  // Note: that applies for all non-file-scope objects.
2288
  // C99 6.9.2p1:
2289
  //   If the declaration of an identifier for an object has file scope and an
2290
  //   initializer, the declaration is an external definition for the identifier
2291
  if (hasInit())
2292
    return Definition;
2293

2294
  if (hasDefiningAttr())
2295
    return Definition;
2296

2297
  if (const auto *SAA = getAttr<SelectAnyAttr>())
2298
    if (!SAA->isInherited())
2299
      return Definition;
2300

2301
  // A variable template specialization (other than a static data member
2302
  // template or an explicit specialization) is a declaration until we
2303
  // instantiate its initializer.
2304
  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2305
    if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2306
        !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2307
        !VTSD->IsCompleteDefinition)
2308
      return DeclarationOnly;
2309
  }
2310

2311
  if (hasExternalStorage())
2312
    return DeclarationOnly;
2313

2314
  // [dcl.link] p7:
2315
  //   A declaration directly contained in a linkage-specification is treated
2316
  //   as if it contains the extern specifier for the purpose of determining
2317
  //   the linkage of the declared name and whether it is a definition.
2318
  if (isSingleLineLanguageLinkage(*this))
2319
    return DeclarationOnly;
2320

2321
  // C99 6.9.2p2:
2322
  //   A declaration of an object that has file scope without an initializer,
2323
  //   and without a storage class specifier or the scs 'static', constitutes
2324
  //   a tentative definition.
2325
  // No such thing in C++.
2326
  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2327
    return TentativeDefinition;
2328

2329
  // What's left is (in C, block-scope) declarations without initializers or
2330
  // external storage. These are definitions.
2331
  return Definition;
2332
}
2333

2334
VarDecl *VarDecl::getActingDefinition() {
2335
  DefinitionKind Kind = isThisDeclarationADefinition();
2336
  if (Kind != TentativeDefinition)
2337
    return nullptr;
2338

2339
  VarDecl *LastTentative = nullptr;
2340

2341
  // Loop through the declaration chain, starting with the most recent.
2342
  for (VarDecl *Decl = getMostRecentDecl(); Decl;
2343
       Decl = Decl->getPreviousDecl()) {
2344
    Kind = Decl->isThisDeclarationADefinition();
2345
    if (Kind == Definition)
2346
      return nullptr;
2347
    // Record the first (most recent) TentativeDefinition that is encountered.
2348
    if (Kind == TentativeDefinition && !LastTentative)
2349
      LastTentative = Decl;
2350
  }
2351

2352
  return LastTentative;
2353
}
2354

2355
VarDecl *VarDecl::getDefinition(ASTContext &C) {
2356
  VarDecl *First = getFirstDecl();
2357
  for (auto *I : First->redecls()) {
2358
    if (I->isThisDeclarationADefinition(C) == Definition)
2359
      return I;
2360
  }
2361
  return nullptr;
2362
}
2363

2364
VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2365
  DefinitionKind Kind = DeclarationOnly;
2366

2367
  const VarDecl *First = getFirstDecl();
2368
  for (auto *I : First->redecls()) {
2369
    Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2370
    if (Kind == Definition)
2371
      break;
2372
  }
2373

2374
  return Kind;
2375
}
2376

2377
const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2378
  for (auto *I : redecls()) {
2379
    if (auto Expr = I->getInit()) {
2380
      D = I;
2381
      return Expr;
2382
    }
2383
  }
2384
  return nullptr;
2385
}
2386

2387
bool VarDecl::hasInit() const {
2388
  if (auto *P = dyn_cast<ParmVarDecl>(this))
2389
    if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2390
      return false;
2391

2392
  if (auto *Eval = getEvaluatedStmt())
2393
    return Eval->Value.isValid();
2394

2395
  return !Init.isNull();
2396
}
2397

2398
Expr *VarDecl::getInit() {
2399
  if (!hasInit())
2400
    return nullptr;
2401

2402
  if (auto *S = Init.dyn_cast<Stmt *>())
2403
    return cast<Expr>(S);
2404

2405
  auto *Eval = getEvaluatedStmt();
2406

2407
  return cast<Expr>(Eval->Value.get(
2408
      Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));
2409
}
2410

2411
Stmt **VarDecl::getInitAddress() {
2412
  if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2413
    return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2414

2415
  return Init.getAddrOfPtr1();
2416
}
2417

2418
VarDecl *VarDecl::getInitializingDeclaration() {
2419
  VarDecl *Def = nullptr;
2420
  for (auto *I : redecls()) {
2421
    if (I->hasInit())
2422
      return I;
2423

2424
    if (I->isThisDeclarationADefinition()) {
2425
      if (isStaticDataMember())
2426
        return I;
2427
      Def = I;
2428
    }
2429
  }
2430
  return Def;
2431
}
2432

2433
bool VarDecl::isOutOfLine() const {
2434
  if (Decl::isOutOfLine())
2435
    return true;
2436

2437
  if (!isStaticDataMember())
2438
    return false;
2439

2440
  // If this static data member was instantiated from a static data member of
2441
  // a class template, check whether that static data member was defined
2442
  // out-of-line.
2443
  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2444
    return VD->isOutOfLine();
2445

2446
  return false;
2447
}
2448

2449
void VarDecl::setInit(Expr *I) {
2450
  if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2451
    Eval->~EvaluatedStmt();
2452
    getASTContext().Deallocate(Eval);
2453
  }
2454

2455
  Init = I;
2456
}
2457

2458
bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2459
  const LangOptions &Lang = C.getLangOpts();
2460

2461
  // OpenCL permits const integral variables to be used in constant
2462
  // expressions, like in C++98.
2463
  if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2464
    return false;
2465

2466
  // Function parameters are never usable in constant expressions.
2467
  if (isa<ParmVarDecl>(this))
2468
    return false;
2469

2470
  // The values of weak variables are never usable in constant expressions.
2471
  if (isWeak())
2472
    return false;
2473

2474
  // In C++11, any variable of reference type can be used in a constant
2475
  // expression if it is initialized by a constant expression.
2476
  if (Lang.CPlusPlus11 && getType()->isReferenceType())
2477
    return true;
2478

2479
  // Only const objects can be used in constant expressions in C++. C++98 does
2480
  // not require the variable to be non-volatile, but we consider this to be a
2481
  // defect.
2482
  if (!getType().isConstant(C) || getType().isVolatileQualified())
2483
    return false;
2484

2485
  // In C++, but not in C, const, non-volatile variables of integral or
2486
  // enumeration types can be used in constant expressions.
2487
  if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2488
    return true;
2489

2490
  // C23 6.6p7: An identifier that is:
2491
  // ...
2492
  // - declared with storage-class specifier constexpr and has an object type,
2493
  // is a named constant, ... such a named constant is a constant expression
2494
  // with the type and value of the declared object.
2495
  // Additionally, in C++11, non-volatile constexpr variables can be used in
2496
  // constant expressions.
2497
  return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2498
}
2499

2500
bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2501
  // C++2a [expr.const]p3:
2502
  //   A variable is usable in constant expressions after its initializing
2503
  //   declaration is encountered...
2504
  const VarDecl *DefVD = nullptr;
2505
  const Expr *Init = getAnyInitializer(DefVD);
2506
  if (!Init || Init->isValueDependent() || getType()->isDependentType())
2507
    return false;
2508
  //   ... if it is a constexpr variable, or it is of reference type or of
2509
  //   const-qualified integral or enumeration type, ...
2510
  if (!DefVD->mightBeUsableInConstantExpressions(Context))
2511
    return false;
2512
  //   ... and its initializer is a constant initializer.
2513
  if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2514
    return false;
2515
  // C++98 [expr.const]p1:
2516
  //   An integral constant-expression can involve only [...] const variables
2517
  //   or static data members of integral or enumeration types initialized with
2518
  //   [integer] constant expressions (dcl.init)
2519
  if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2520
      !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2521
    return false;
2522
  return true;
2523
}
2524

2525
/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2526
/// form, which contains extra information on the evaluated value of the
2527
/// initializer.
2528
EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2529
  auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2530
  if (!Eval) {
2531
    // Note: EvaluatedStmt contains an APValue, which usually holds
2532
    // resources not allocated from the ASTContext.  We need to do some
2533
    // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2534
    // where we can detect whether there's anything to clean up or not.
2535
    Eval = new (getASTContext()) EvaluatedStmt;
2536
    Eval->Value = Init.get<Stmt *>();
2537
    Init = Eval;
2538
  }
2539
  return Eval;
2540
}
2541

2542
EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2543
  return Init.dyn_cast<EvaluatedStmt *>();
2544
}
2545

2546
APValue *VarDecl::evaluateValue() const {
2547
  SmallVector<PartialDiagnosticAt, 8> Notes;
2548
  return evaluateValueImpl(Notes, hasConstantInitialization());
2549
}
2550

2551
APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2552
                                    bool IsConstantInitialization) const {
2553
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2554

2555
  const auto *Init = getInit();
2556
  assert(!Init->isValueDependent());
2557

2558
  // We only produce notes indicating why an initializer is non-constant the
2559
  // first time it is evaluated. FIXME: The notes won't always be emitted the
2560
  // first time we try evaluation, so might not be produced at all.
2561
  if (Eval->WasEvaluated)
2562
    return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2563

2564
  if (Eval->IsEvaluating) {
2565
    // FIXME: Produce a diagnostic for self-initialization.
2566
    return nullptr;
2567
  }
2568

2569
  Eval->IsEvaluating = true;
2570

2571
  ASTContext &Ctx = getASTContext();
2572
  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2573
                                            IsConstantInitialization);
2574

2575
  // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2576
  // a constant initializer if we produced notes. In that case, we can't keep
2577
  // the result, because it may only be correct under the assumption that the
2578
  // initializer is a constant context.
2579
  if (IsConstantInitialization &&
2580
      (Ctx.getLangOpts().CPlusPlus ||
2581
       (isConstexpr() && Ctx.getLangOpts().C23)) &&
2582
      !Notes.empty())
2583
    Result = false;
2584

2585
  // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2586
  // or that it's empty (so that there's nothing to clean up) if evaluation
2587
  // failed.
2588
  if (!Result)
2589
    Eval->Evaluated = APValue();
2590
  else if (Eval->Evaluated.needsCleanup())
2591
    Ctx.addDestruction(&Eval->Evaluated);
2592

2593
  Eval->IsEvaluating = false;
2594
  Eval->WasEvaluated = true;
2595

2596
  return Result ? &Eval->Evaluated : nullptr;
2597
}
2598

2599
APValue *VarDecl::getEvaluatedValue() const {
2600
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2601
    if (Eval->WasEvaluated)
2602
      return &Eval->Evaluated;
2603

2604
  return nullptr;
2605
}
2606

2607
bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2608
  const Expr *Init = getInit();
2609
  assert(Init && "no initializer");
2610

2611
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2612
  if (!Eval->CheckedForICEInit) {
2613
    Eval->CheckedForICEInit = true;
2614
    Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2615
  }
2616
  return Eval->HasICEInit;
2617
}
2618

2619
bool VarDecl::hasConstantInitialization() const {
2620
  // In C, all globals (and only globals) have constant initialization.
2621
  if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2622
    return true;
2623

2624
  // In C++, it depends on whether the evaluation at the point of definition
2625
  // was evaluatable as a constant initializer.
2626
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2627
    return Eval->HasConstantInitialization;
2628

2629
  return false;
2630
}
2631

2632
bool VarDecl::checkForConstantInitialization(
2633
    SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2634
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2635
  // If we ask for the value before we know whether we have a constant
2636
  // initializer, we can compute the wrong value (for example, due to
2637
  // std::is_constant_evaluated()).
2638
  assert(!Eval->WasEvaluated &&
2639
         "already evaluated var value before checking for constant init");
2640
  assert((getASTContext().getLangOpts().CPlusPlus ||
2641
          getASTContext().getLangOpts().C23) &&
2642
         "only meaningful in C++/C23");
2643

2644
  assert(!getInit()->isValueDependent());
2645

2646
  // Evaluate the initializer to check whether it's a constant expression.
2647
  Eval->HasConstantInitialization =
2648
      evaluateValueImpl(Notes, true) && Notes.empty();
2649

2650
  // If evaluation as a constant initializer failed, allow re-evaluation as a
2651
  // non-constant initializer if we later find we want the value.
2652
  if (!Eval->HasConstantInitialization)
2653
    Eval->WasEvaluated = false;
2654

2655
  return Eval->HasConstantInitialization;
2656
}
2657

2658
bool VarDecl::isParameterPack() const {
2659
  return isa<PackExpansionType>(getType());
2660
}
2661

2662
template<typename DeclT>
2663
static DeclT *getDefinitionOrSelf(DeclT *D) {
2664
  assert(D);
2665
  if (auto *Def = D->getDefinition())
2666
    return Def;
2667
  return D;
2668
}
2669

2670
bool VarDecl::isEscapingByref() const {
2671
  return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2672
}
2673

2674
bool VarDecl::isNonEscapingByref() const {
2675
  return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2676
}
2677

2678
bool VarDecl::hasDependentAlignment() const {
2679
  QualType T = getType();
2680
  return T->isDependentType() || T->isUndeducedType() ||
2681
         llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2682
           return AA->isAlignmentDependent();
2683
         });
2684
}
2685

2686
VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2687
  const VarDecl *VD = this;
2688

2689
  // If this is an instantiated member, walk back to the template from which
2690
  // it was instantiated.
2691
  if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2692
    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2693
      VD = VD->getInstantiatedFromStaticDataMember();
2694
      while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2695
        VD = NewVD;
2696
    }
2697
  }
2698

2699
  // If it's an instantiated variable template specialization, find the
2700
  // template or partial specialization from which it was instantiated.
2701
  if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2702
    if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2703
      auto From = VDTemplSpec->getInstantiatedFrom();
2704
      if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2705
        while (!VTD->isMemberSpecialization()) {
2706
          auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2707
          if (!NewVTD)
2708
            break;
2709
          VTD = NewVTD;
2710
        }
2711
        return getDefinitionOrSelf(VTD->getTemplatedDecl());
2712
      }
2713
      if (auto *VTPSD =
2714
              From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2715
        while (!VTPSD->isMemberSpecialization()) {
2716
          auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2717
          if (!NewVTPSD)
2718
            break;
2719
          VTPSD = NewVTPSD;
2720
        }
2721
        return getDefinitionOrSelf<VarDecl>(VTPSD);
2722
      }
2723
    }
2724
  }
2725

2726
  // If this is the pattern of a variable template, find where it was
2727
  // instantiated from. FIXME: Is this necessary?
2728
  if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2729
    while (!VarTemplate->isMemberSpecialization()) {
2730
      auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2731
      if (!NewVT)
2732
        break;
2733
      VarTemplate = NewVT;
2734
    }
2735

2736
    return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2737
  }
2738

2739
  if (VD == this)
2740
    return nullptr;
2741
  return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2742
}
2743

2744
VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2745
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2746
    return cast<VarDecl>(MSI->getInstantiatedFrom());
2747

2748
  return nullptr;
2749
}
2750

2751
TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2752
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2753
    return Spec->getSpecializationKind();
2754

2755
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2756
    return MSI->getTemplateSpecializationKind();
2757

2758
  return TSK_Undeclared;
2759
}
2760

2761
TemplateSpecializationKind
2762
VarDecl::getTemplateSpecializationKindForInstantiation() const {
2763
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2764
    return MSI->getTemplateSpecializationKind();
2765

2766
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2767
    return Spec->getSpecializationKind();
2768

2769
  return TSK_Undeclared;
2770
}
2771

2772
SourceLocation VarDecl::getPointOfInstantiation() const {
2773
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2774
    return Spec->getPointOfInstantiation();
2775

2776
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2777
    return MSI->getPointOfInstantiation();
2778

2779
  return SourceLocation();
2780
}
2781

2782
VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2783
  return getASTContext().getTemplateOrSpecializationInfo(this)
2784
      .dyn_cast<VarTemplateDecl *>();
2785
}
2786

2787
void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2788
  getASTContext().setTemplateOrSpecializationInfo(this, Template);
2789
}
2790

2791
bool VarDecl::isKnownToBeDefined() const {
2792
  const auto &LangOpts = getASTContext().getLangOpts();
2793
  // In CUDA mode without relocatable device code, variables of form 'extern
2794
  // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2795
  // memory pool.  These are never undefined variables, even if they appear
2796
  // inside of an anon namespace or static function.
2797
  //
2798
  // With CUDA relocatable device code enabled, these variables don't get
2799
  // special handling; they're treated like regular extern variables.
2800
  if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2801
      hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2802
      isa<IncompleteArrayType>(getType()))
2803
    return true;
2804

2805
  return hasDefinition();
2806
}
2807

2808
bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2809
  return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2810
                                (!Ctx.getLangOpts().RegisterStaticDestructors &&
2811
                                 !hasAttr<AlwaysDestroyAttr>()));
2812
}
2813

2814
QualType::DestructionKind
2815
VarDecl::needsDestruction(const ASTContext &Ctx) const {
2816
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2817
    if (Eval->HasConstantDestruction)
2818
      return QualType::DK_none;
2819

2820
  if (isNoDestroy(Ctx))
2821
    return QualType::DK_none;
2822

2823
  return getType().isDestructedType();
2824
}
2825

2826
bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
2827
  assert(hasInit() && "Expect initializer to check for flexible array init");
2828
  auto *Ty = getType()->getAs<RecordType>();
2829
  if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2830
    return false;
2831
  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2832
  if (!List)
2833
    return false;
2834
  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2835
  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2836
  if (!InitTy)
2837
    return false;
2838
  return !InitTy->isZeroSize();
2839
}
2840

2841
CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
2842
  assert(hasInit() && "Expect initializer to check for flexible array init");
2843
  auto *Ty = getType()->getAs<RecordType>();
2844
  if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2845
    return CharUnits::Zero();
2846
  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2847
  if (!List || List->getNumInits() == 0)
2848
    return CharUnits::Zero();
2849
  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2850
  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2851
  if (!InitTy)
2852
    return CharUnits::Zero();
2853
  CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2854
  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2855
  CharUnits FlexibleArrayOffset =
2856
      Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));
2857
  if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2858
    return CharUnits::Zero();
2859
  return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2860
}
2861

2862
MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2863
  if (isStaticDataMember())
2864
    // FIXME: Remove ?
2865
    // return getASTContext().getInstantiatedFromStaticDataMember(this);
2866
    return getASTContext().getTemplateOrSpecializationInfo(this)
2867
        .dyn_cast<MemberSpecializationInfo *>();
2868
  return nullptr;
2869
}
2870

2871
void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2872
                                         SourceLocation PointOfInstantiation) {
2873
  assert((isa<VarTemplateSpecializationDecl>(this) ||
2874
          getMemberSpecializationInfo()) &&
2875
         "not a variable or static data member template specialization");
2876

2877
  if (VarTemplateSpecializationDecl *Spec =
2878
          dyn_cast<VarTemplateSpecializationDecl>(this)) {
2879
    Spec->setSpecializationKind(TSK);
2880
    if (TSK != TSK_ExplicitSpecialization &&
2881
        PointOfInstantiation.isValid() &&
2882
        Spec->getPointOfInstantiation().isInvalid()) {
2883
      Spec->setPointOfInstantiation(PointOfInstantiation);
2884
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2885
        L->InstantiationRequested(this);
2886
    }
2887
  } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2888
    MSI->setTemplateSpecializationKind(TSK);
2889
    if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2890
        MSI->getPointOfInstantiation().isInvalid()) {
2891
      MSI->setPointOfInstantiation(PointOfInstantiation);
2892
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2893
        L->InstantiationRequested(this);
2894
    }
2895
  }
2896
}
2897

2898
void
2899
VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2900
                                            TemplateSpecializationKind TSK) {
2901
  assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2902
         "Previous template or instantiation?");
2903
  getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2904
}
2905

2906
//===----------------------------------------------------------------------===//
2907
// ParmVarDecl Implementation
2908
//===----------------------------------------------------------------------===//
2909

2910
ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2911
                                 SourceLocation StartLoc, SourceLocation IdLoc,
2912
                                 const IdentifierInfo *Id, QualType T,
2913
                                 TypeSourceInfo *TInfo, StorageClass S,
2914
                                 Expr *DefArg) {
2915
  return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2916
                                 S, DefArg);
2917
}
2918

2919
QualType ParmVarDecl::getOriginalType() const {
2920
  TypeSourceInfo *TSI = getTypeSourceInfo();
2921
  QualType T = TSI ? TSI->getType() : getType();
2922
  if (const auto *DT = dyn_cast<DecayedType>(T))
2923
    return DT->getOriginalType();
2924
  return T;
2925
}
2926

2927
ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2928
  return new (C, ID)
2929
      ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2930
                  nullptr, QualType(), nullptr, SC_None, nullptr);
2931
}
2932

2933
SourceRange ParmVarDecl::getSourceRange() const {
2934
  if (!hasInheritedDefaultArg()) {
2935
    SourceRange ArgRange = getDefaultArgRange();
2936
    if (ArgRange.isValid())
2937
      return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2938
  }
2939

2940
  // DeclaratorDecl considers the range of postfix types as overlapping with the
2941
  // declaration name, but this is not the case with parameters in ObjC methods.
2942
  if (isa<ObjCMethodDecl>(getDeclContext()))
2943
    return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2944

2945
  return DeclaratorDecl::getSourceRange();
2946
}
2947

2948
bool ParmVarDecl::isDestroyedInCallee() const {
2949
  // ns_consumed only affects code generation in ARC
2950
  if (hasAttr<NSConsumedAttr>())
2951
    return getASTContext().getLangOpts().ObjCAutoRefCount;
2952

2953
  // FIXME: isParamDestroyedInCallee() should probably imply
2954
  // isDestructedType()
2955
  const auto *RT = getType()->getAs<RecordType>();
2956
  if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2957
      getType().isDestructedType())
2958
    return true;
2959

2960
  return false;
2961
}
2962

2963
Expr *ParmVarDecl::getDefaultArg() {
2964
  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2965
  assert(!hasUninstantiatedDefaultArg() &&
2966
         "Default argument is not yet instantiated!");
2967

2968
  Expr *Arg = getInit();
2969
  if (auto *E = dyn_cast_if_present<FullExpr>(Arg))
2970
    return E->getSubExpr();
2971

2972
  return Arg;
2973
}
2974

2975
void ParmVarDecl::setDefaultArg(Expr *defarg) {
2976
  ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2977
  Init = defarg;
2978
}
2979

2980
SourceRange ParmVarDecl::getDefaultArgRange() const {
2981
  switch (ParmVarDeclBits.DefaultArgKind) {
2982
  case DAK_None:
2983
  case DAK_Unparsed:
2984
    // Nothing we can do here.
2985
    return SourceRange();
2986

2987
  case DAK_Uninstantiated:
2988
    return getUninstantiatedDefaultArg()->getSourceRange();
2989

2990
  case DAK_Normal:
2991
    if (const Expr *E = getInit())
2992
      return E->getSourceRange();
2993

2994
    // Missing an actual expression, may be invalid.
2995
    return SourceRange();
2996
  }
2997
  llvm_unreachable("Invalid default argument kind.");
2998
}
2999

3000
void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
3001
  ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
3002
  Init = arg;
3003
}
3004

3005
Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
3006
  assert(hasUninstantiatedDefaultArg() &&
3007
         "Wrong kind of initialization expression!");
3008
  return cast_if_present<Expr>(Init.get<Stmt *>());
3009
}
3010

3011
bool ParmVarDecl::hasDefaultArg() const {
3012
  // FIXME: We should just return false for DAK_None here once callers are
3013
  // prepared for the case that we encountered an invalid default argument and
3014
  // were unable to even build an invalid expression.
3015
  return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
3016
         !Init.isNull();
3017
}
3018

3019
void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3020
  getASTContext().setParameterIndex(this, parameterIndex);
3021
  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3022
}
3023

3024
unsigned ParmVarDecl::getParameterIndexLarge() const {
3025
  return getASTContext().getParameterIndex(this);
3026
}
3027

3028
//===----------------------------------------------------------------------===//
3029
// FunctionDecl Implementation
3030
//===----------------------------------------------------------------------===//
3031

3032
FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
3033
                           SourceLocation StartLoc,
3034
                           const DeclarationNameInfo &NameInfo, QualType T,
3035
                           TypeSourceInfo *TInfo, StorageClass S,
3036
                           bool UsesFPIntrin, bool isInlineSpecified,
3037
                           ConstexprSpecKind ConstexprKind,
3038
                           Expr *TrailingRequiresClause)
3039
    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3040
                     StartLoc),
3041
      DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3042
      EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3043
  assert(T.isNull() || T->isFunctionType());
3044
  FunctionDeclBits.SClass = S;
3045
  FunctionDeclBits.IsInline = isInlineSpecified;
3046
  FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3047
  FunctionDeclBits.IsVirtualAsWritten = false;
3048
  FunctionDeclBits.IsPureVirtual = false;
3049
  FunctionDeclBits.HasInheritedPrototype = false;
3050
  FunctionDeclBits.HasWrittenPrototype = true;
3051
  FunctionDeclBits.IsDeleted = false;
3052
  FunctionDeclBits.IsTrivial = false;
3053
  FunctionDeclBits.IsTrivialForCall = false;
3054
  FunctionDeclBits.IsDefaulted = false;
3055
  FunctionDeclBits.IsExplicitlyDefaulted = false;
3056
  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3057
  FunctionDeclBits.IsIneligibleOrNotSelected = false;
3058
  FunctionDeclBits.HasImplicitReturnZero = false;
3059
  FunctionDeclBits.IsLateTemplateParsed = false;
3060
  FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3061
  FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3062
  FunctionDeclBits.InstantiationIsPending = false;
3063
  FunctionDeclBits.UsesSEHTry = false;
3064
  FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3065
  FunctionDeclBits.HasSkippedBody = false;
3066
  FunctionDeclBits.WillHaveBody = false;
3067
  FunctionDeclBits.IsMultiVersion = false;
3068
  FunctionDeclBits.DeductionCandidateKind =
3069
      static_cast<unsigned char>(DeductionCandidate::Normal);
3070
  FunctionDeclBits.HasODRHash = false;
3071
  FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3072
  if (TrailingRequiresClause)
3073
    setTrailingRequiresClause(TrailingRequiresClause);
3074
}
3075

3076
void FunctionDecl::getNameForDiagnostic(
3077
    raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3078
  NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
3079
  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
3080
  if (TemplateArgs)
3081
    printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3082
}
3083

3084
bool FunctionDecl::isVariadic() const {
3085
  if (const auto *FT = getType()->getAs<FunctionProtoType>())
3086
    return FT->isVariadic();
3087
  return false;
3088
}
3089

3090
FunctionDecl::DefaultedOrDeletedFunctionInfo *
3091
FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
3092
    ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3093
    StringLiteral *DeletedMessage) {
3094
  static constexpr size_t Alignment =
3095
      std::max({alignof(DefaultedOrDeletedFunctionInfo),
3096
                alignof(DeclAccessPair), alignof(StringLiteral *)});
3097
  size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3098
      Lookups.size(), DeletedMessage != nullptr);
3099

3100
  DefaultedOrDeletedFunctionInfo *Info =
3101
      new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;
3102
  Info->NumLookups = Lookups.size();
3103
  Info->HasDeletedMessage = DeletedMessage != nullptr;
3104

3105
  std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3106
                          Info->getTrailingObjects<DeclAccessPair>());
3107
  if (DeletedMessage)
3108
    *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3109
  return Info;
3110
}
3111

3112
void FunctionDecl::setDefaultedOrDeletedInfo(
3113
    DefaultedOrDeletedFunctionInfo *Info) {
3114
  assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3115
  assert(!Body && "can't replace function body with defaulted function info");
3116

3117
  FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3118
  DefaultedOrDeletedInfo = Info;
3119
}
3120

3121
void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) {
3122
  FunctionDeclBits.IsDeleted = D;
3123

3124
  if (Message) {
3125
    assert(isDeletedAsWritten() && "Function must be deleted");
3126
    if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3127
      DefaultedOrDeletedInfo->setDeletedMessage(Message);
3128
    else
3129
      setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create(
3130
          getASTContext(), /*Lookups=*/{}, Message));
3131
  }
3132
}
3133

3134
void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage(
3135
    StringLiteral *Message) {
3136
  // We should never get here with the DefaultedOrDeletedInfo populated, but
3137
  // no space allocated for the deleted message, since that would require
3138
  // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3139
  // an already existing DefaultedOrDeletedFunctionInfo.
3140
  assert(HasDeletedMessage &&
3141
         "No space to store a delete message in this DefaultedOrDeletedInfo");
3142
  *getTrailingObjects<StringLiteral *>() = Message;
3143
}
3144

3145
FunctionDecl::DefaultedOrDeletedFunctionInfo *
3146
FunctionDecl::getDefalutedOrDeletedInfo() const {
3147
  return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3148
                                                    : nullptr;
3149
}
3150

3151
bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3152
  for (const auto *I : redecls()) {
3153
    if (I->doesThisDeclarationHaveABody()) {
3154
      Definition = I;
3155
      return true;
3156
    }
3157
  }
3158

3159
  return false;
3160
}
3161

3162
bool FunctionDecl::hasTrivialBody() const {
3163
  const Stmt *S = getBody();
3164
  if (!S) {
3165
    // Since we don't have a body for this function, we don't know if it's
3166
    // trivial or not.
3167
    return false;
3168
  }
3169

3170
  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3171
    return true;
3172
  return false;
3173
}
3174

3175
bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
3176
  if (!getFriendObjectKind())
3177
    return false;
3178

3179
  // Check for a friend function instantiated from a friend function
3180
  // definition in a templated class.
3181
  if (const FunctionDecl *InstantiatedFrom =
3182
          getInstantiatedFromMemberFunction())
3183
    return InstantiatedFrom->getFriendObjectKind() &&
3184
           InstantiatedFrom->isThisDeclarationADefinition();
3185

3186
  // Check for a friend function template instantiated from a friend
3187
  // function template definition in a templated class.
3188
  if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3189
    if (const FunctionTemplateDecl *InstantiatedFrom =
3190
            Template->getInstantiatedFromMemberTemplate())
3191
      return InstantiatedFrom->getFriendObjectKind() &&
3192
             InstantiatedFrom->isThisDeclarationADefinition();
3193
  }
3194

3195
  return false;
3196
}
3197

3198
bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3199
                             bool CheckForPendingFriendDefinition) const {
3200
  for (const FunctionDecl *FD : redecls()) {
3201
    if (FD->isThisDeclarationADefinition()) {
3202
      Definition = FD;
3203
      return true;
3204
    }
3205

3206
    // If this is a friend function defined in a class template, it does not
3207
    // have a body until it is used, nevertheless it is a definition, see
3208
    // [temp.inst]p2:
3209
    //
3210
    // ... for the purpose of determining whether an instantiated redeclaration
3211
    // is valid according to [basic.def.odr] and [class.mem], a declaration that
3212
    // corresponds to a definition in the template is considered to be a
3213
    // definition.
3214
    //
3215
    // The following code must produce redefinition error:
3216
    //
3217
    //     template<typename T> struct C20 { friend void func_20() {} };
3218
    //     C20<int> c20i;
3219
    //     void func_20() {}
3220
    //
3221
    if (CheckForPendingFriendDefinition &&
3222
        FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3223
      Definition = FD;
3224
      return true;
3225
    }
3226
  }
3227

3228
  return false;
3229
}
3230

3231
Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3232
  if (!hasBody(Definition))
3233
    return nullptr;
3234

3235
  assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3236
         "definition should not have a body");
3237
  if (Definition->Body)
3238
    return Definition->Body.get(getASTContext().getExternalSource());
3239

3240
  return nullptr;
3241
}
3242

3243
void FunctionDecl::setBody(Stmt *B) {
3244
  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3245
  Body = LazyDeclStmtPtr(B);
3246
  if (B)
3247
    EndRangeLoc = B->getEndLoc();
3248
}
3249

3250
void FunctionDecl::setIsPureVirtual(bool P) {
3251
  FunctionDeclBits.IsPureVirtual = P;
3252
  if (P)
3253
    if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3254
      Parent->markedVirtualFunctionPure();
3255
}
3256

3257
template<std::size_t Len>
3258
static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3259
  const IdentifierInfo *II = ND->getIdentifier();
3260
  return II && II->isStr(Str);
3261
}
3262

3263
bool FunctionDecl::isImmediateEscalating() const {
3264
  // C++23 [expr.const]/p17
3265
  // An immediate-escalating function is
3266
  //  - the call operator of a lambda that is not declared with the consteval
3267
  //  specifier,
3268
  if (isLambdaCallOperator(this) && !isConsteval())
3269
    return true;
3270
  // - a defaulted special member function that is not declared with the
3271
  // consteval specifier,
3272
  if (isDefaulted() && !isConsteval())
3273
    return true;
3274
  // - a function that results from the instantiation of a templated entity
3275
  // defined with the constexpr specifier.
3276
  TemplatedKind TK = getTemplatedKind();
3277
  if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3278
      isConstexprSpecified())
3279
    return true;
3280
  return false;
3281
}
3282

3283
bool FunctionDecl::isImmediateFunction() const {
3284
  // C++23 [expr.const]/p18
3285
  // An immediate function is a function or constructor that is
3286
  // - declared with the consteval specifier
3287
  if (isConsteval())
3288
    return true;
3289
  // - an immediate-escalating function F whose function body contains an
3290
  // immediate-escalating expression
3291
  if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions())
3292
    return true;
3293

3294
  if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3295
      MD && MD->isLambdaStaticInvoker())
3296
    return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3297

3298
  return false;
3299
}
3300

3301
bool FunctionDecl::isMain() const {
3302
  const TranslationUnitDecl *tunit =
3303
    dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3304
  return tunit &&
3305
         !tunit->getASTContext().getLangOpts().Freestanding &&
3306
         isNamed(this, "main");
3307
}
3308

3309
bool FunctionDecl::isMSVCRTEntryPoint() const {
3310
  const TranslationUnitDecl *TUnit =
3311
      dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3312
  if (!TUnit)
3313
    return false;
3314

3315
  // Even though we aren't really targeting MSVCRT if we are freestanding,
3316
  // semantic analysis for these functions remains the same.
3317

3318
  // MSVCRT entry points only exist on MSVCRT targets.
3319
  if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3320
    return false;
3321

3322
  // Nameless functions like constructors cannot be entry points.
3323
  if (!getIdentifier())
3324
    return false;
3325

3326
  return llvm::StringSwitch<bool>(getName())
3327
      .Cases("main",     // an ANSI console app
3328
             "wmain",    // a Unicode console App
3329
             "WinMain",  // an ANSI GUI app
3330
             "wWinMain", // a Unicode GUI app
3331
             "DllMain",  // a DLL
3332
             true)
3333
      .Default(false);
3334
}
3335

3336
bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3337
  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3338
    return false;
3339
  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3340
      getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3341
      getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3342
      getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3343
    return false;
3344

3345
  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3346
    return false;
3347

3348
  const auto *proto = getType()->castAs<FunctionProtoType>();
3349
  if (proto->getNumParams() != 2 || proto->isVariadic())
3350
    return false;
3351

3352
  const ASTContext &Context =
3353
      cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3354
          ->getASTContext();
3355

3356
  // The result type and first argument type are constant across all
3357
  // these operators.  The second argument must be exactly void*.
3358
  return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3359
}
3360

3361
bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3362
    std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3363
  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3364
    return false;
3365
  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3366
      getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3367
      getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3368
      getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3369
    return false;
3370

3371
  if (isa<CXXRecordDecl>(getDeclContext()))
3372
    return false;
3373

3374
  // This can only fail for an invalid 'operator new' declaration.
3375
  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3376
    return false;
3377

3378
  const auto *FPT = getType()->castAs<FunctionProtoType>();
3379
  if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())
3380
    return false;
3381

3382
  // If this is a single-parameter function, it must be a replaceable global
3383
  // allocation or deallocation function.
3384
  if (FPT->getNumParams() == 1)
3385
    return true;
3386

3387
  unsigned Params = 1;
3388
  QualType Ty = FPT->getParamType(Params);
3389
  const ASTContext &Ctx = getASTContext();
3390

3391
  auto Consume = [&] {
3392
    ++Params;
3393
    Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3394
  };
3395

3396
  // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3397
  bool IsSizedDelete = false;
3398
  if (Ctx.getLangOpts().SizedDeallocation &&
3399
      (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3400
       getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3401
      Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3402
    IsSizedDelete = true;
3403
    Consume();
3404
  }
3405

3406
  // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3407
  // new/delete.
3408
  if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3409
    Consume();
3410
    if (AlignmentParam)
3411
      *AlignmentParam = Params;
3412
  }
3413

3414
  // If this is not a sized delete, the next parameter can be a
3415
  // 'const std::nothrow_t&'.
3416
  if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3417
    Ty = Ty->getPointeeType();
3418
    if (Ty.getCVRQualifiers() != Qualifiers::Const)
3419
      return false;
3420
    if (Ty->isNothrowT()) {
3421
      if (IsNothrow)
3422
        *IsNothrow = true;
3423
      Consume();
3424
    }
3425
  }
3426

3427
  // Finally, recognize the not yet standard versions of new that take a
3428
  // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3429
  // tcmalloc (see
3430
  // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3431
  if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3432
    QualType T = Ty;
3433
    while (const auto *TD = T->getAs<TypedefType>())
3434
      T = TD->getDecl()->getUnderlyingType();
3435
    const IdentifierInfo *II =
3436
        T->castAs<EnumType>()->getDecl()->getIdentifier();
3437
    if (II && II->isStr("__hot_cold_t"))
3438
      Consume();
3439
  }
3440

3441
  return Params == FPT->getNumParams();
3442
}
3443

3444
bool FunctionDecl::isInlineBuiltinDeclaration() const {
3445
  if (!getBuiltinID())
3446
    return false;
3447

3448
  const FunctionDecl *Definition;
3449
  if (!hasBody(Definition))
3450
    return false;
3451

3452
  if (!Definition->isInlineSpecified() ||
3453
      !Definition->hasAttr<AlwaysInlineAttr>())
3454
    return false;
3455

3456
  ASTContext &Context = getASTContext();
3457
  switch (Context.GetGVALinkageForFunction(Definition)) {
3458
  case GVA_Internal:
3459
  case GVA_DiscardableODR:
3460
  case GVA_StrongODR:
3461
    return false;
3462
  case GVA_AvailableExternally:
3463
  case GVA_StrongExternal:
3464
    return true;
3465
  }
3466
  llvm_unreachable("Unknown GVALinkage");
3467
}
3468

3469
bool FunctionDecl::isDestroyingOperatorDelete() const {
3470
  // C++ P0722:
3471
  //   Within a class C, a single object deallocation function with signature
3472
  //     (T, std::destroying_delete_t, <more params>)
3473
  //   is a destroying operator delete.
3474
  if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3475
      getNumParams() < 2)
3476
    return false;
3477

3478
  auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3479
  return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3480
         RD->getIdentifier()->isStr("destroying_delete_t");
3481
}
3482

3483
LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3484
  return getDeclLanguageLinkage(*this);
3485
}
3486

3487
bool FunctionDecl::isExternC() const {
3488
  return isDeclExternC(*this);
3489
}
3490

3491
bool FunctionDecl::isInExternCContext() const {
3492
  if (hasAttr<OpenCLKernelAttr>())
3493
    return true;
3494
  return getLexicalDeclContext()->isExternCContext();
3495
}
3496

3497
bool FunctionDecl::isInExternCXXContext() const {
3498
  return getLexicalDeclContext()->isExternCXXContext();
3499
}
3500

3501
bool FunctionDecl::isGlobal() const {
3502
  if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3503
    return Method->isStatic();
3504

3505
  if (getCanonicalDecl()->getStorageClass() == SC_Static)
3506
    return false;
3507

3508
  for (const DeclContext *DC = getDeclContext();
3509
       DC->isNamespace();
3510
       DC = DC->getParent()) {
3511
    if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3512
      if (!Namespace->getDeclName())
3513
        return false;
3514
    }
3515
  }
3516

3517
  return true;
3518
}
3519

3520
bool FunctionDecl::isNoReturn() const {
3521
  if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3522
      hasAttr<C11NoReturnAttr>())
3523
    return true;
3524

3525
  if (auto *FnTy = getType()->getAs<FunctionType>())
3526
    return FnTy->getNoReturnAttr();
3527

3528
  return false;
3529
}
3530

3531
bool FunctionDecl::isMemberLikeConstrainedFriend() const {
3532
  // C++20 [temp.friend]p9:
3533
  //   A non-template friend declaration with a requires-clause [or]
3534
  //   a friend function template with a constraint that depends on a template
3535
  //   parameter from an enclosing template [...] does not declare the same
3536
  //   function or function template as a declaration in any other scope.
3537

3538
  // If this isn't a friend then it's not a member-like constrained friend.
3539
  if (!getFriendObjectKind()) {
3540
    return false;
3541
  }
3542

3543
  if (!getDescribedFunctionTemplate()) {
3544
    // If these friends don't have constraints, they aren't constrained, and
3545
    // thus don't fall under temp.friend p9. Else the simple presence of a
3546
    // constraint makes them unique.
3547
    return getTrailingRequiresClause();
3548
  }
3549

3550
  return FriendConstraintRefersToEnclosingTemplate();
3551
}
3552

3553
MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3554
  if (hasAttr<TargetAttr>())
3555
    return MultiVersionKind::Target;
3556
  if (hasAttr<TargetVersionAttr>())
3557
    return MultiVersionKind::TargetVersion;
3558
  if (hasAttr<CPUDispatchAttr>())
3559
    return MultiVersionKind::CPUDispatch;
3560
  if (hasAttr<CPUSpecificAttr>())
3561
    return MultiVersionKind::CPUSpecific;
3562
  if (hasAttr<TargetClonesAttr>())
3563
    return MultiVersionKind::TargetClones;
3564
  return MultiVersionKind::None;
3565
}
3566

3567
bool FunctionDecl::isCPUDispatchMultiVersion() const {
3568
  return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3569
}
3570

3571
bool FunctionDecl::isCPUSpecificMultiVersion() const {
3572
  return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3573
}
3574

3575
bool FunctionDecl::isTargetMultiVersion() const {
3576
  return isMultiVersion() &&
3577
         (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3578
}
3579

3580
bool FunctionDecl::isTargetMultiVersionDefault() const {
3581
  if (!isMultiVersion())
3582
    return false;
3583
  if (hasAttr<TargetAttr>())
3584
    return getAttr<TargetAttr>()->isDefaultVersion();
3585
  return hasAttr<TargetVersionAttr>() &&
3586
         getAttr<TargetVersionAttr>()->isDefaultVersion();
3587
}
3588

3589
bool FunctionDecl::isTargetClonesMultiVersion() const {
3590
  return isMultiVersion() && hasAttr<TargetClonesAttr>();
3591
}
3592

3593
bool FunctionDecl::isTargetVersionMultiVersion() const {
3594
  return isMultiVersion() && hasAttr<TargetVersionAttr>();
3595
}
3596

3597
void
3598
FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3599
  redeclarable_base::setPreviousDecl(PrevDecl);
3600

3601
  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3602
    FunctionTemplateDecl *PrevFunTmpl
3603
      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3604
    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3605
    FunTmpl->setPreviousDecl(PrevFunTmpl);
3606
  }
3607

3608
  if (PrevDecl && PrevDecl->isInlined())
3609
    setImplicitlyInline(true);
3610
}
3611

3612
FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3613

3614
/// Returns a value indicating whether this function corresponds to a builtin
3615
/// function.
3616
///
3617
/// The function corresponds to a built-in function if it is declared at
3618
/// translation scope or within an extern "C" block and its name matches with
3619
/// the name of a builtin. The returned value will be 0 for functions that do
3620
/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3621
/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3622
/// value.
3623
///
3624
/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3625
/// functions as their wrapped builtins. This shouldn't be done in general, but
3626
/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3627
unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3628
  unsigned BuiltinID = 0;
3629

3630
  if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3631
    BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3632
  } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3633
    BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3634
  } else if (const auto *A = getAttr<BuiltinAttr>()) {
3635
    BuiltinID = A->getID();
3636
  }
3637

3638
  if (!BuiltinID)
3639
    return 0;
3640

3641
  // If the function is marked "overloadable", it has a different mangled name
3642
  // and is not the C library function.
3643
  if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3644
      (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3645
    return 0;
3646

3647
  const ASTContext &Context = getASTContext();
3648
  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3649
    return BuiltinID;
3650

3651
  // This function has the name of a known C library
3652
  // function. Determine whether it actually refers to the C library
3653
  // function or whether it just has the same name.
3654

3655
  // If this is a static function, it's not a builtin.
3656
  if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3657
    return 0;
3658

3659
  // OpenCL v1.2 s6.9.f - The library functions defined in
3660
  // the C99 standard headers are not available.
3661
  if (Context.getLangOpts().OpenCL &&
3662
      Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3663
    return 0;
3664

3665
  // CUDA does not have device-side standard library. printf and malloc are the
3666
  // only special cases that are supported by device-side runtime.
3667
  if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3668
      !hasAttr<CUDAHostAttr>() &&
3669
      !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3670
    return 0;
3671

3672
  // As AMDGCN implementation of OpenMP does not have a device-side standard
3673
  // library, none of the predefined library functions except printf and malloc
3674
  // should be treated as a builtin i.e. 0 should be returned for them.
3675
  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3676
      Context.getLangOpts().OpenMPIsTargetDevice &&
3677
      Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3678
      !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3679
    return 0;
3680

3681
  return BuiltinID;
3682
}
3683

3684
/// getNumParams - Return the number of parameters this function must have
3685
/// based on its FunctionType.  This is the length of the ParamInfo array
3686
/// after it has been created.
3687
unsigned FunctionDecl::getNumParams() const {
3688
  const auto *FPT = getType()->getAs<FunctionProtoType>();
3689
  return FPT ? FPT->getNumParams() : 0;
3690
}
3691

3692
void FunctionDecl::setParams(ASTContext &C,
3693
                             ArrayRef<ParmVarDecl *> NewParamInfo) {
3694
  assert(!ParamInfo && "Already has param info!");
3695
  assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3696

3697
  // Zero params -> null pointer.
3698
  if (!NewParamInfo.empty()) {
3699
    ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3700
    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3701
  }
3702
}
3703

3704
/// getMinRequiredArguments - Returns the minimum number of arguments
3705
/// needed to call this function. This may be fewer than the number of
3706
/// function parameters, if some of the parameters have default
3707
/// arguments (in C++) or are parameter packs (C++11).
3708
unsigned FunctionDecl::getMinRequiredArguments() const {
3709
  if (!getASTContext().getLangOpts().CPlusPlus)
3710
    return getNumParams();
3711

3712
  // Note that it is possible for a parameter with no default argument to
3713
  // follow a parameter with a default argument.
3714
  unsigned NumRequiredArgs = 0;
3715
  unsigned MinParamsSoFar = 0;
3716
  for (auto *Param : parameters()) {
3717
    if (!Param->isParameterPack()) {
3718
      ++MinParamsSoFar;
3719
      if (!Param->hasDefaultArg())
3720
        NumRequiredArgs = MinParamsSoFar;
3721
    }
3722
  }
3723
  return NumRequiredArgs;
3724
}
3725

3726
bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const {
3727
  return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter();
3728
}
3729

3730
unsigned FunctionDecl::getNumNonObjectParams() const {
3731
  return getNumParams() -
3732
         static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3733
}
3734

3735
unsigned FunctionDecl::getMinRequiredExplicitArguments() const {
3736
  return getMinRequiredArguments() -
3737
         static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3738
}
3739

3740
bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3741
  return getNumParams() == 1 ||
3742
         (getNumParams() > 1 &&
3743
          llvm::all_of(llvm::drop_begin(parameters()),
3744
                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3745
}
3746

3747
/// The combination of the extern and inline keywords under MSVC forces
3748
/// the function to be required.
3749
///
3750
/// Note: This function assumes that we will only get called when isInlined()
3751
/// would return true for this FunctionDecl.
3752
bool FunctionDecl::isMSExternInline() const {
3753
  assert(isInlined() && "expected to get called on an inlined function!");
3754

3755
  const ASTContext &Context = getASTContext();
3756
  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3757
      !hasAttr<DLLExportAttr>())
3758
    return false;
3759

3760
  for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3761
       FD = FD->getPreviousDecl())
3762
    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3763
      return true;
3764

3765
  return false;
3766
}
3767

3768
static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3769
  if (Redecl->getStorageClass() != SC_Extern)
3770
    return false;
3771

3772
  for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3773
       FD = FD->getPreviousDecl())
3774
    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3775
      return false;
3776

3777
  return true;
3778
}
3779

3780
static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3781
  // Only consider file-scope declarations in this test.
3782
  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3783
    return false;
3784

3785
  // Only consider explicit declarations; the presence of a builtin for a
3786
  // libcall shouldn't affect whether a definition is externally visible.
3787
  if (Redecl->isImplicit())
3788
    return false;
3789

3790
  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3791
    return true; // Not an inline definition
3792

3793
  return false;
3794
}
3795

3796
/// For a function declaration in C or C++, determine whether this
3797
/// declaration causes the definition to be externally visible.
3798
///
3799
/// For instance, this determines if adding the current declaration to the set
3800
/// of redeclarations of the given functions causes
3801
/// isInlineDefinitionExternallyVisible to change from false to true.
3802
bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3803
  assert(!doesThisDeclarationHaveABody() &&
3804
         "Must have a declaration without a body.");
3805

3806
  const ASTContext &Context = getASTContext();
3807

3808
  if (Context.getLangOpts().MSVCCompat) {
3809
    const FunctionDecl *Definition;
3810
    if (hasBody(Definition) && Definition->isInlined() &&
3811
        redeclForcesDefMSVC(this))
3812
      return true;
3813
  }
3814

3815
  if (Context.getLangOpts().CPlusPlus)
3816
    return false;
3817

3818
  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3819
    // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3820
    // an externally visible definition.
3821
    //
3822
    // FIXME: What happens if gnu_inline gets added on after the first
3823
    // declaration?
3824
    if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3825
      return false;
3826

3827
    const FunctionDecl *Prev = this;
3828
    bool FoundBody = false;
3829
    while ((Prev = Prev->getPreviousDecl())) {
3830
      FoundBody |= Prev->doesThisDeclarationHaveABody();
3831

3832
      if (Prev->doesThisDeclarationHaveABody()) {
3833
        // If it's not the case that both 'inline' and 'extern' are
3834
        // specified on the definition, then it is always externally visible.
3835
        if (!Prev->isInlineSpecified() ||
3836
            Prev->getStorageClass() != SC_Extern)
3837
          return false;
3838
      } else if (Prev->isInlineSpecified() &&
3839
                 Prev->getStorageClass() != SC_Extern) {
3840
        return false;
3841
      }
3842
    }
3843
    return FoundBody;
3844
  }
3845

3846
  // C99 6.7.4p6:
3847
  //   [...] If all of the file scope declarations for a function in a
3848
  //   translation unit include the inline function specifier without extern,
3849
  //   then the definition in that translation unit is an inline definition.
3850
  if (isInlineSpecified() && getStorageClass() != SC_Extern)
3851
    return false;
3852
  const FunctionDecl *Prev = this;
3853
  bool FoundBody = false;
3854
  while ((Prev = Prev->getPreviousDecl())) {
3855
    FoundBody |= Prev->doesThisDeclarationHaveABody();
3856
    if (RedeclForcesDefC99(Prev))
3857
      return false;
3858
  }
3859
  return FoundBody;
3860
}
3861

3862
FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3863
  const TypeSourceInfo *TSI = getTypeSourceInfo();
3864
  return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3865
             : FunctionTypeLoc();
3866
}
3867

3868
SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3869
  FunctionTypeLoc FTL = getFunctionTypeLoc();
3870
  if (!FTL)
3871
    return SourceRange();
3872

3873
  // Skip self-referential return types.
3874
  const SourceManager &SM = getASTContext().getSourceManager();
3875
  SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3876
  SourceLocation Boundary = getNameInfo().getBeginLoc();
3877
  if (RTRange.isInvalid() || Boundary.isInvalid() ||
3878
      !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3879
    return SourceRange();
3880

3881
  return RTRange;
3882
}
3883

3884
SourceRange FunctionDecl::getParametersSourceRange() const {
3885
  unsigned NP = getNumParams();
3886
  SourceLocation EllipsisLoc = getEllipsisLoc();
3887

3888
  if (NP == 0 && EllipsisLoc.isInvalid())
3889
    return SourceRange();
3890

3891
  SourceLocation Begin =
3892
      NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3893
  SourceLocation End = EllipsisLoc.isValid()
3894
                           ? EllipsisLoc
3895
                           : ParamInfo[NP - 1]->getSourceRange().getEnd();
3896

3897
  return SourceRange(Begin, End);
3898
}
3899

3900
SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3901
  FunctionTypeLoc FTL = getFunctionTypeLoc();
3902
  return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3903
}
3904

3905
/// For an inline function definition in C, or for a gnu_inline function
3906
/// in C++, determine whether the definition will be externally visible.
3907
///
3908
/// Inline function definitions are always available for inlining optimizations.
3909
/// However, depending on the language dialect, declaration specifiers, and
3910
/// attributes, the definition of an inline function may or may not be
3911
/// "externally" visible to other translation units in the program.
3912
///
3913
/// In C99, inline definitions are not externally visible by default. However,
3914
/// if even one of the global-scope declarations is marked "extern inline", the
3915
/// inline definition becomes externally visible (C99 6.7.4p6).
3916
///
3917
/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3918
/// definition, we use the GNU semantics for inline, which are nearly the
3919
/// opposite of C99 semantics. In particular, "inline" by itself will create
3920
/// an externally visible symbol, but "extern inline" will not create an
3921
/// externally visible symbol.
3922
bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3923
  assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3924
          hasAttr<AliasAttr>()) &&
3925
         "Must be a function definition");
3926
  assert(isInlined() && "Function must be inline");
3927
  ASTContext &Context = getASTContext();
3928

3929
  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3930
    // Note: If you change the logic here, please change
3931
    // doesDeclarationForceExternallyVisibleDefinition as well.
3932
    //
3933
    // If it's not the case that both 'inline' and 'extern' are
3934
    // specified on the definition, then this inline definition is
3935
    // externally visible.
3936
    if (Context.getLangOpts().CPlusPlus)
3937
      return false;
3938
    if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3939
      return true;
3940

3941
    // If any declaration is 'inline' but not 'extern', then this definition
3942
    // is externally visible.
3943
    for (auto *Redecl : redecls()) {
3944
      if (Redecl->isInlineSpecified() &&
3945
          Redecl->getStorageClass() != SC_Extern)
3946
        return true;
3947
    }
3948

3949
    return false;
3950
  }
3951

3952
  // The rest of this function is C-only.
3953
  assert(!Context.getLangOpts().CPlusPlus &&
3954
         "should not use C inline rules in C++");
3955

3956
  // C99 6.7.4p6:
3957
  //   [...] If all of the file scope declarations for a function in a
3958
  //   translation unit include the inline function specifier without extern,
3959
  //   then the definition in that translation unit is an inline definition.
3960
  for (auto *Redecl : redecls()) {
3961
    if (RedeclForcesDefC99(Redecl))
3962
      return true;
3963
  }
3964

3965
  // C99 6.7.4p6:
3966
  //   An inline definition does not provide an external definition for the
3967
  //   function, and does not forbid an external definition in another
3968
  //   translation unit.
3969
  return false;
3970
}
3971

3972
/// getOverloadedOperator - Which C++ overloaded operator this
3973
/// function represents, if any.
3974
OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3975
  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3976
    return getDeclName().getCXXOverloadedOperator();
3977
  return OO_None;
3978
}
3979

3980
/// getLiteralIdentifier - The literal suffix identifier this function
3981
/// represents, if any.
3982
const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3983
  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3984
    return getDeclName().getCXXLiteralIdentifier();
3985
  return nullptr;
3986
}
3987

3988
FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3989
  if (TemplateOrSpecialization.isNull())
3990
    return TK_NonTemplate;
3991
  if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {
3992
    if (isa<FunctionDecl>(ND))
3993
      return TK_DependentNonTemplate;
3994
    assert(isa<FunctionTemplateDecl>(ND) &&
3995
           "No other valid types in NamedDecl");
3996
    return TK_FunctionTemplate;
3997
  }
3998
  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3999
    return TK_MemberSpecialization;
4000
  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
4001
    return TK_FunctionTemplateSpecialization;
4002
  if (TemplateOrSpecialization.is
4003
                               <DependentFunctionTemplateSpecializationInfo*>())
4004
    return TK_DependentFunctionTemplateSpecialization;
4005

4006
  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4007
}
4008

4009
FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
4010
  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
4011
    return cast<FunctionDecl>(Info->getInstantiatedFrom());
4012

4013
  return nullptr;
4014
}
4015

4016
MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
4017
  if (auto *MSI =
4018
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4019
    return MSI;
4020
  if (auto *FTSI = TemplateOrSpecialization
4021
                       .dyn_cast<FunctionTemplateSpecializationInfo *>())
4022
    return FTSI->getMemberSpecializationInfo();
4023
  return nullptr;
4024
}
4025

4026
void
4027
FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4028
                                               FunctionDecl *FD,
4029
                                               TemplateSpecializationKind TSK) {
4030
  assert(TemplateOrSpecialization.isNull() &&
4031
         "Member function is already a specialization");
4032
  MemberSpecializationInfo *Info
4033
    = new (C) MemberSpecializationInfo(FD, TSK);
4034
  TemplateOrSpecialization = Info;
4035
}
4036

4037
FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
4038
  return dyn_cast_if_present<FunctionTemplateDecl>(
4039
      TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4040
}
4041

4042
void FunctionDecl::setDescribedFunctionTemplate(
4043
    FunctionTemplateDecl *Template) {
4044
  assert(TemplateOrSpecialization.isNull() &&
4045
         "Member function is already a specialization");
4046
  TemplateOrSpecialization = Template;
4047
}
4048

4049
bool FunctionDecl::isFunctionTemplateSpecialization() const {
4050
  return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() ||
4051
         TemplateOrSpecialization
4052
             .is<DependentFunctionTemplateSpecializationInfo *>();
4053
}
4054

4055
void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {
4056
  assert(TemplateOrSpecialization.isNull() &&
4057
         "Function is already a specialization");
4058
  TemplateOrSpecialization = FD;
4059
}
4060

4061
FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {
4062
  return dyn_cast_if_present<FunctionDecl>(
4063
      TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4064
}
4065

4066
bool FunctionDecl::isImplicitlyInstantiable() const {
4067
  // If the function is invalid, it can't be implicitly instantiated.
4068
  if (isInvalidDecl())
4069
    return false;
4070

4071
  switch (getTemplateSpecializationKindForInstantiation()) {
4072
  case TSK_Undeclared:
4073
  case TSK_ExplicitInstantiationDefinition:
4074
  case TSK_ExplicitSpecialization:
4075
    return false;
4076

4077
  case TSK_ImplicitInstantiation:
4078
    return true;
4079

4080
  case TSK_ExplicitInstantiationDeclaration:
4081
    // Handled below.
4082
    break;
4083
  }
4084

4085
  // Find the actual template from which we will instantiate.
4086
  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4087
  bool HasPattern = false;
4088
  if (PatternDecl)
4089
    HasPattern = PatternDecl->hasBody(PatternDecl);
4090

4091
  // C++0x [temp.explicit]p9:
4092
  //   Except for inline functions, other explicit instantiation declarations
4093
  //   have the effect of suppressing the implicit instantiation of the entity
4094
  //   to which they refer.
4095
  if (!HasPattern || !PatternDecl)
4096
    return true;
4097

4098
  return PatternDecl->isInlined();
4099
}
4100

4101
bool FunctionDecl::isTemplateInstantiation() const {
4102
  // FIXME: Remove this, it's not clear what it means. (Which template
4103
  // specialization kind?)
4104
  return clang::isTemplateInstantiation(getTemplateSpecializationKind());
4105
}
4106

4107
FunctionDecl *
4108
FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
4109
  // If this is a generic lambda call operator specialization, its
4110
  // instantiation pattern is always its primary template's pattern
4111
  // even if its primary template was instantiated from another
4112
  // member template (which happens with nested generic lambdas).
4113
  // Since a lambda's call operator's body is transformed eagerly,
4114
  // we don't have to go hunting for a prototype definition template
4115
  // (i.e. instantiated-from-member-template) to use as an instantiation
4116
  // pattern.
4117

4118
  if (isGenericLambdaCallOperatorSpecialization(
4119
          dyn_cast<CXXMethodDecl>(this))) {
4120
    assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4121
    return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
4122
  }
4123

4124
  // Check for a declaration of this function that was instantiated from a
4125
  // friend definition.
4126
  const FunctionDecl *FD = nullptr;
4127
  if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4128
    FD = this;
4129

4130
  if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
4131
    if (ForDefinition &&
4132
        !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
4133
      return nullptr;
4134
    return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4135
  }
4136

4137
  if (ForDefinition &&
4138
      !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
4139
    return nullptr;
4140

4141
  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4142
    // If we hit a point where the user provided a specialization of this
4143
    // template, we're done looking.
4144
    while (!ForDefinition || !Primary->isMemberSpecialization()) {
4145
      auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4146
      if (!NewPrimary)
4147
        break;
4148
      Primary = NewPrimary;
4149
    }
4150

4151
    return getDefinitionOrSelf(Primary->getTemplatedDecl());
4152
  }
4153

4154
  return nullptr;
4155
}
4156

4157
FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
4158
  if (FunctionTemplateSpecializationInfo *Info
4159
        = TemplateOrSpecialization
4160
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4161
    return Info->getTemplate();
4162
  }
4163
  return nullptr;
4164
}
4165

4166
FunctionTemplateSpecializationInfo *
4167
FunctionDecl::getTemplateSpecializationInfo() const {
4168
  return TemplateOrSpecialization
4169
      .dyn_cast<FunctionTemplateSpecializationInfo *>();
4170
}
4171

4172
const TemplateArgumentList *
4173
FunctionDecl::getTemplateSpecializationArgs() const {
4174
  if (FunctionTemplateSpecializationInfo *Info
4175
        = TemplateOrSpecialization
4176
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4177
    return Info->TemplateArguments;
4178
  }
4179
  return nullptr;
4180
}
4181

4182
const ASTTemplateArgumentListInfo *
4183
FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
4184
  if (FunctionTemplateSpecializationInfo *Info
4185
        = TemplateOrSpecialization
4186
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4187
    return Info->TemplateArgumentsAsWritten;
4188
  }
4189
  if (DependentFunctionTemplateSpecializationInfo *Info =
4190
          TemplateOrSpecialization
4191
              .dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) {
4192
    return Info->TemplateArgumentsAsWritten;
4193
  }
4194
  return nullptr;
4195
}
4196

4197
void FunctionDecl::setFunctionTemplateSpecialization(
4198
    ASTContext &C, FunctionTemplateDecl *Template,
4199
    TemplateArgumentList *TemplateArgs, void *InsertPos,
4200
    TemplateSpecializationKind TSK,
4201
    const TemplateArgumentListInfo *TemplateArgsAsWritten,
4202
    SourceLocation PointOfInstantiation) {
4203
  assert((TemplateOrSpecialization.isNull() ||
4204
          TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
4205
         "Member function is already a specialization");
4206
  assert(TSK != TSK_Undeclared &&
4207
         "Must specify the type of function template specialization");
4208
  assert((TemplateOrSpecialization.isNull() ||
4209
          getFriendObjectKind() != FOK_None ||
4210
          TSK == TSK_ExplicitSpecialization) &&
4211
         "Member specialization must be an explicit specialization");
4212
  FunctionTemplateSpecializationInfo *Info =
4213
      FunctionTemplateSpecializationInfo::Create(
4214
          C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4215
          PointOfInstantiation,
4216
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
4217
  TemplateOrSpecialization = Info;
4218
  Template->addSpecialization(Info, InsertPos);
4219
}
4220

4221
void FunctionDecl::setDependentTemplateSpecialization(
4222
    ASTContext &Context, const UnresolvedSetImpl &Templates,
4223
    const TemplateArgumentListInfo *TemplateArgs) {
4224
  assert(TemplateOrSpecialization.isNull());
4225
  DependentFunctionTemplateSpecializationInfo *Info =
4226
      DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
4227
                                                          TemplateArgs);
4228
  TemplateOrSpecialization = Info;
4229
}
4230

4231
DependentFunctionTemplateSpecializationInfo *
4232
FunctionDecl::getDependentSpecializationInfo() const {
4233
  return TemplateOrSpecialization
4234
      .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
4235
}
4236

4237
DependentFunctionTemplateSpecializationInfo *
4238
DependentFunctionTemplateSpecializationInfo::Create(
4239
    ASTContext &Context, const UnresolvedSetImpl &Candidates,
4240
    const TemplateArgumentListInfo *TArgs) {
4241
  const auto *TArgsWritten =
4242
      TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4243
  return new (Context.Allocate(
4244
      totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4245
      DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4246
}
4247

4248
DependentFunctionTemplateSpecializationInfo::
4249
    DependentFunctionTemplateSpecializationInfo(
4250
        const UnresolvedSetImpl &Candidates,
4251
        const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4252
    : NumCandidates(Candidates.size()),
4253
      TemplateArgumentsAsWritten(TemplateArgsWritten) {
4254
  std::transform(Candidates.begin(), Candidates.end(),
4255
                 getTrailingObjects<FunctionTemplateDecl *>(),
4256
                 [](NamedDecl *ND) {
4257
                   return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());
4258
                 });
4259
}
4260

4261
TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
4262
  // For a function template specialization, query the specialization
4263
  // information object.
4264
  if (FunctionTemplateSpecializationInfo *FTSInfo =
4265
          TemplateOrSpecialization
4266
              .dyn_cast<FunctionTemplateSpecializationInfo *>())
4267
    return FTSInfo->getTemplateSpecializationKind();
4268

4269
  if (MemberSpecializationInfo *MSInfo =
4270
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4271
    return MSInfo->getTemplateSpecializationKind();
4272

4273
  // A dependent function template specialization is an explicit specialization,
4274
  // except when it's a friend declaration.
4275
  if (TemplateOrSpecialization
4276
          .is<DependentFunctionTemplateSpecializationInfo *>() &&
4277
      getFriendObjectKind() == FOK_None)
4278
    return TSK_ExplicitSpecialization;
4279

4280
  return TSK_Undeclared;
4281
}
4282

4283
TemplateSpecializationKind
4284
FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
4285
  // This is the same as getTemplateSpecializationKind(), except that for a
4286
  // function that is both a function template specialization and a member
4287
  // specialization, we prefer the member specialization information. Eg:
4288
  //
4289
  // template<typename T> struct A {
4290
  //   template<typename U> void f() {}
4291
  //   template<> void f<int>() {}
4292
  // };
4293
  //
4294
  // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4295
  // template specialization; both getTemplateSpecializationKind() and
4296
  // getTemplateSpecializationKindForInstantiation() will return
4297
  // TSK_ExplicitSpecialization.
4298
  //
4299
  // For A<int>::f<int>():
4300
  // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4301
  // * getTemplateSpecializationKindForInstantiation() will return
4302
  //       TSK_ImplicitInstantiation
4303
  //
4304
  // This reflects the facts that A<int>::f<int> is an explicit specialization
4305
  // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4306
  // from A::f<int> if a definition is needed.
4307
  if (FunctionTemplateSpecializationInfo *FTSInfo =
4308
          TemplateOrSpecialization
4309
              .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4310
    if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4311
      return MSInfo->getTemplateSpecializationKind();
4312
    return FTSInfo->getTemplateSpecializationKind();
4313
  }
4314

4315
  if (MemberSpecializationInfo *MSInfo =
4316
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4317
    return MSInfo->getTemplateSpecializationKind();
4318

4319
  if (TemplateOrSpecialization
4320
          .is<DependentFunctionTemplateSpecializationInfo *>() &&
4321
      getFriendObjectKind() == FOK_None)
4322
    return TSK_ExplicitSpecialization;
4323

4324
  return TSK_Undeclared;
4325
}
4326

4327
void
4328
FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4329
                                          SourceLocation PointOfInstantiation) {
4330
  if (FunctionTemplateSpecializationInfo *FTSInfo
4331
        = TemplateOrSpecialization.dyn_cast<
4332
                                    FunctionTemplateSpecializationInfo*>()) {
4333
    FTSInfo->setTemplateSpecializationKind(TSK);
4334
    if (TSK != TSK_ExplicitSpecialization &&
4335
        PointOfInstantiation.isValid() &&
4336
        FTSInfo->getPointOfInstantiation().isInvalid()) {
4337
      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4338
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4339
        L->InstantiationRequested(this);
4340
    }
4341
  } else if (MemberSpecializationInfo *MSInfo
4342
             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4343
    MSInfo->setTemplateSpecializationKind(TSK);
4344
    if (TSK != TSK_ExplicitSpecialization &&
4345
        PointOfInstantiation.isValid() &&
4346
        MSInfo->getPointOfInstantiation().isInvalid()) {
4347
      MSInfo->setPointOfInstantiation(PointOfInstantiation);
4348
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4349
        L->InstantiationRequested(this);
4350
    }
4351
  } else
4352
    llvm_unreachable("Function cannot have a template specialization kind");
4353
}
4354

4355
SourceLocation FunctionDecl::getPointOfInstantiation() const {
4356
  if (FunctionTemplateSpecializationInfo *FTSInfo
4357
        = TemplateOrSpecialization.dyn_cast<
4358
                                        FunctionTemplateSpecializationInfo*>())
4359
    return FTSInfo->getPointOfInstantiation();
4360
  if (MemberSpecializationInfo *MSInfo =
4361
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4362
    return MSInfo->getPointOfInstantiation();
4363

4364
  return SourceLocation();
4365
}
4366

4367
bool FunctionDecl::isOutOfLine() const {
4368
  if (Decl::isOutOfLine())
4369
    return true;
4370

4371
  // If this function was instantiated from a member function of a
4372
  // class template, check whether that member function was defined out-of-line.
4373
  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4374
    const FunctionDecl *Definition;
4375
    if (FD->hasBody(Definition))
4376
      return Definition->isOutOfLine();
4377
  }
4378

4379
  // If this function was instantiated from a function template,
4380
  // check whether that function template was defined out-of-line.
4381
  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4382
    const FunctionDecl *Definition;
4383
    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4384
      return Definition->isOutOfLine();
4385
  }
4386

4387
  return false;
4388
}
4389

4390
SourceRange FunctionDecl::getSourceRange() const {
4391
  return SourceRange(getOuterLocStart(), EndRangeLoc);
4392
}
4393

4394
unsigned FunctionDecl::getMemoryFunctionKind() const {
4395
  IdentifierInfo *FnInfo = getIdentifier();
4396

4397
  if (!FnInfo)
4398
    return 0;
4399

4400
  // Builtin handling.
4401
  switch (getBuiltinID()) {
4402
  case Builtin::BI__builtin_memset:
4403
  case Builtin::BI__builtin___memset_chk:
4404
  case Builtin::BImemset:
4405
    return Builtin::BImemset;
4406

4407
  case Builtin::BI__builtin_memcpy:
4408
  case Builtin::BI__builtin___memcpy_chk:
4409
  case Builtin::BImemcpy:
4410
    return Builtin::BImemcpy;
4411

4412
  case Builtin::BI__builtin_mempcpy:
4413
  case Builtin::BI__builtin___mempcpy_chk:
4414
  case Builtin::BImempcpy:
4415
    return Builtin::BImempcpy;
4416

4417
  case Builtin::BI__builtin_memmove:
4418
  case Builtin::BI__builtin___memmove_chk:
4419
  case Builtin::BImemmove:
4420
    return Builtin::BImemmove;
4421

4422
  case Builtin::BIstrlcpy:
4423
  case Builtin::BI__builtin___strlcpy_chk:
4424
    return Builtin::BIstrlcpy;
4425

4426
  case Builtin::BIstrlcat:
4427
  case Builtin::BI__builtin___strlcat_chk:
4428
    return Builtin::BIstrlcat;
4429

4430
  case Builtin::BI__builtin_memcmp:
4431
  case Builtin::BImemcmp:
4432
    return Builtin::BImemcmp;
4433

4434
  case Builtin::BI__builtin_bcmp:
4435
  case Builtin::BIbcmp:
4436
    return Builtin::BIbcmp;
4437

4438
  case Builtin::BI__builtin_strncpy:
4439
  case Builtin::BI__builtin___strncpy_chk:
4440
  case Builtin::BIstrncpy:
4441
    return Builtin::BIstrncpy;
4442

4443
  case Builtin::BI__builtin_strncmp:
4444
  case Builtin::BIstrncmp:
4445
    return Builtin::BIstrncmp;
4446

4447
  case Builtin::BI__builtin_strncasecmp:
4448
  case Builtin::BIstrncasecmp:
4449
    return Builtin::BIstrncasecmp;
4450

4451
  case Builtin::BI__builtin_strncat:
4452
  case Builtin::BI__builtin___strncat_chk:
4453
  case Builtin::BIstrncat:
4454
    return Builtin::BIstrncat;
4455

4456
  case Builtin::BI__builtin_strndup:
4457
  case Builtin::BIstrndup:
4458
    return Builtin::BIstrndup;
4459

4460
  case Builtin::BI__builtin_strlen:
4461
  case Builtin::BIstrlen:
4462
    return Builtin::BIstrlen;
4463

4464
  case Builtin::BI__builtin_bzero:
4465
  case Builtin::BIbzero:
4466
    return Builtin::BIbzero;
4467

4468
  case Builtin::BI__builtin_bcopy:
4469
  case Builtin::BIbcopy:
4470
    return Builtin::BIbcopy;
4471

4472
  case Builtin::BIfree:
4473
    return Builtin::BIfree;
4474

4475
  default:
4476
    if (isExternC()) {
4477
      if (FnInfo->isStr("memset"))
4478
        return Builtin::BImemset;
4479
      if (FnInfo->isStr("memcpy"))
4480
        return Builtin::BImemcpy;
4481
      if (FnInfo->isStr("mempcpy"))
4482
        return Builtin::BImempcpy;
4483
      if (FnInfo->isStr("memmove"))
4484
        return Builtin::BImemmove;
4485
      if (FnInfo->isStr("memcmp"))
4486
        return Builtin::BImemcmp;
4487
      if (FnInfo->isStr("bcmp"))
4488
        return Builtin::BIbcmp;
4489
      if (FnInfo->isStr("strncpy"))
4490
        return Builtin::BIstrncpy;
4491
      if (FnInfo->isStr("strncmp"))
4492
        return Builtin::BIstrncmp;
4493
      if (FnInfo->isStr("strncasecmp"))
4494
        return Builtin::BIstrncasecmp;
4495
      if (FnInfo->isStr("strncat"))
4496
        return Builtin::BIstrncat;
4497
      if (FnInfo->isStr("strndup"))
4498
        return Builtin::BIstrndup;
4499
      if (FnInfo->isStr("strlen"))
4500
        return Builtin::BIstrlen;
4501
      if (FnInfo->isStr("bzero"))
4502
        return Builtin::BIbzero;
4503
      if (FnInfo->isStr("bcopy"))
4504
        return Builtin::BIbcopy;
4505
    } else if (isInStdNamespace()) {
4506
      if (FnInfo->isStr("free"))
4507
        return Builtin::BIfree;
4508
    }
4509
    break;
4510
  }
4511
  return 0;
4512
}
4513

4514
unsigned FunctionDecl::getODRHash() const {
4515
  assert(hasODRHash());
4516
  return ODRHash;
4517
}
4518

4519
unsigned FunctionDecl::getODRHash() {
4520
  if (hasODRHash())
4521
    return ODRHash;
4522

4523
  if (auto *FT = getInstantiatedFromMemberFunction()) {
4524
    setHasODRHash(true);
4525
    ODRHash = FT->getODRHash();
4526
    return ODRHash;
4527
  }
4528

4529
  class ODRHash Hash;
4530
  Hash.AddFunctionDecl(this);
4531
  setHasODRHash(true);
4532
  ODRHash = Hash.CalculateHash();
4533
  return ODRHash;
4534
}
4535

4536
//===----------------------------------------------------------------------===//
4537
// FieldDecl Implementation
4538
//===----------------------------------------------------------------------===//
4539

4540
FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4541
                             SourceLocation StartLoc, SourceLocation IdLoc,
4542
                             const IdentifierInfo *Id, QualType T,
4543
                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4544
                             InClassInitStyle InitStyle) {
4545
  return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4546
                               BW, Mutable, InitStyle);
4547
}
4548

4549
FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
4550
  return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4551
                               SourceLocation(), nullptr, QualType(), nullptr,
4552
                               nullptr, false, ICIS_NoInit);
4553
}
4554

4555
bool FieldDecl::isAnonymousStructOrUnion() const {
4556
  if (!isImplicit() || getDeclName())
4557
    return false;
4558

4559
  if (const auto *Record = getType()->getAs<RecordType>())
4560
    return Record->getDecl()->isAnonymousStructOrUnion();
4561

4562
  return false;
4563
}
4564

4565
Expr *FieldDecl::getInClassInitializer() const {
4566
  if (!hasInClassInitializer())
4567
    return nullptr;
4568

4569
  LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4570
  return cast_if_present<Expr>(
4571
      InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4572
                         : InitPtr.get(nullptr));
4573
}
4574

4575
void FieldDecl::setInClassInitializer(Expr *NewInit) {
4576
  setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4577
}
4578

4579
void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4580
  assert(hasInClassInitializer() && !getInClassInitializer());
4581
  if (BitField)
4582
    InitAndBitWidth->Init = NewInit;
4583
  else
4584
    Init = NewInit;
4585
}
4586

4587
unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4588
  assert(isBitField() && "not a bitfield");
4589
  return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4590
}
4591

4592
bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4593
  return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&
4594
         getBitWidthValue(Ctx) == 0;
4595
}
4596

4597
bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4598
  if (isZeroLengthBitField(Ctx))
4599
    return true;
4600

4601
  // C++2a [intro.object]p7:
4602
  //   An object has nonzero size if it
4603
  //     -- is not a potentially-overlapping subobject, or
4604
  if (!hasAttr<NoUniqueAddressAttr>())
4605
    return false;
4606

4607
  //     -- is not of class type, or
4608
  const auto *RT = getType()->getAs<RecordType>();
4609
  if (!RT)
4610
    return false;
4611
  const RecordDecl *RD = RT->getDecl()->getDefinition();
4612
  if (!RD) {
4613
    assert(isInvalidDecl() && "valid field has incomplete type");
4614
    return false;
4615
  }
4616

4617
  //     -- [has] virtual member functions or virtual base classes, or
4618
  //     -- has subobjects of nonzero size or bit-fields of nonzero length
4619
  const auto *CXXRD = cast<CXXRecordDecl>(RD);
4620
  if (!CXXRD->isEmpty())
4621
    return false;
4622

4623
  // Otherwise, [...] the circumstances under which the object has zero size
4624
  // are implementation-defined.
4625
  if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4626
    return true;
4627

4628
  // MS ABI: has nonzero size if it is a class type with class type fields,
4629
  // whether or not they have nonzero size
4630
  return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4631
    return Field->getType()->getAs<RecordType>();
4632
  });
4633
}
4634

4635
bool FieldDecl::isPotentiallyOverlapping() const {
4636
  return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4637
}
4638

4639
unsigned FieldDecl::getFieldIndex() const {
4640
  const FieldDecl *Canonical = getCanonicalDecl();
4641
  if (Canonical != this)
4642
    return Canonical->getFieldIndex();
4643

4644
  if (CachedFieldIndex) return CachedFieldIndex - 1;
4645

4646
  unsigned Index = 0;
4647
  const RecordDecl *RD = getParent()->getDefinition();
4648
  assert(RD && "requested index for field of struct with no definition");
4649

4650
  for (auto *Field : RD->fields()) {
4651
    Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4652
    assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4653
           "overflow in field numbering");
4654
    ++Index;
4655
  }
4656

4657
  assert(CachedFieldIndex && "failed to find field in parent");
4658
  return CachedFieldIndex - 1;
4659
}
4660

4661
SourceRange FieldDecl::getSourceRange() const {
4662
  const Expr *FinalExpr = getInClassInitializer();
4663
  if (!FinalExpr)
4664
    FinalExpr = getBitWidth();
4665
  if (FinalExpr)
4666
    return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4667
  return DeclaratorDecl::getSourceRange();
4668
}
4669

4670
void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4671
  assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4672
         "capturing type in non-lambda or captured record.");
4673
  assert(StorageKind == ISK_NoInit && !BitField &&
4674
         "bit-field or field with default member initializer cannot capture "
4675
         "VLA type");
4676
  StorageKind = ISK_CapturedVLAType;
4677
  CapturedVLAType = VLAType;
4678
}
4679

4680
void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4681
  // Print unnamed members using name of their type.
4682
  if (isAnonymousStructOrUnion()) {
4683
    this->getType().print(OS, Policy);
4684
    return;
4685
  }
4686
  // Otherwise, do the normal printing.
4687
  DeclaratorDecl::printName(OS, Policy);
4688
}
4689

4690
//===----------------------------------------------------------------------===//
4691
// TagDecl Implementation
4692
//===----------------------------------------------------------------------===//
4693

4694
TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4695
                 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4696
                 SourceLocation StartL)
4697
    : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4698
      TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4699
  assert((DK != Enum || TK == TagTypeKind::Enum) &&
4700
         "EnumDecl not matched with TagTypeKind::Enum");
4701
  setPreviousDecl(PrevDecl);
4702
  setTagKind(TK);
4703
  setCompleteDefinition(false);
4704
  setBeingDefined(false);
4705
  setEmbeddedInDeclarator(false);
4706
  setFreeStanding(false);
4707
  setCompleteDefinitionRequired(false);
4708
  TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4709
}
4710

4711
SourceLocation TagDecl::getOuterLocStart() const {
4712
  return getTemplateOrInnerLocStart(this);
4713
}
4714

4715
SourceRange TagDecl::getSourceRange() const {
4716
  SourceLocation RBraceLoc = BraceRange.getEnd();
4717
  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4718
  return SourceRange(getOuterLocStart(), E);
4719
}
4720

4721
TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4722

4723
void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4724
  TypedefNameDeclOrQualifier = TDD;
4725
  if (const Type *T = getTypeForDecl()) {
4726
    (void)T;
4727
    assert(T->isLinkageValid());
4728
  }
4729
  assert(isLinkageValid());
4730
}
4731

4732
void TagDecl::startDefinition() {
4733
  setBeingDefined(true);
4734

4735
  if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4736
    struct CXXRecordDecl::DefinitionData *Data =
4737
      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4738
    for (auto *I : redecls())
4739
      cast<CXXRecordDecl>(I)->DefinitionData = Data;
4740
  }
4741
}
4742

4743
void TagDecl::completeDefinition() {
4744
  assert((!isa<CXXRecordDecl>(this) ||
4745
          cast<CXXRecordDecl>(this)->hasDefinition()) &&
4746
         "definition completed but not started");
4747

4748
  setCompleteDefinition(true);
4749
  setBeingDefined(false);
4750

4751
  if (ASTMutationListener *L = getASTMutationListener())
4752
    L->CompletedTagDefinition(this);
4753
}
4754

4755
TagDecl *TagDecl::getDefinition() const {
4756
  if (isCompleteDefinition())
4757
    return const_cast<TagDecl *>(this);
4758

4759
  // If it's possible for us to have an out-of-date definition, check now.
4760
  if (mayHaveOutOfDateDef()) {
4761
    if (IdentifierInfo *II = getIdentifier()) {
4762
      if (II->isOutOfDate()) {
4763
        updateOutOfDate(*II);
4764
      }
4765
    }
4766
  }
4767

4768
  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4769
    return CXXRD->getDefinition();
4770

4771
  for (auto *R : redecls())
4772
    if (R->isCompleteDefinition())
4773
      return R;
4774

4775
  return nullptr;
4776
}
4777

4778
void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4779
  if (QualifierLoc) {
4780
    // Make sure the extended qualifier info is allocated.
4781
    if (!hasExtInfo())
4782
      TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4783
    // Set qualifier info.
4784
    getExtInfo()->QualifierLoc = QualifierLoc;
4785
  } else {
4786
    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4787
    if (hasExtInfo()) {
4788
      if (getExtInfo()->NumTemplParamLists == 0) {
4789
        getASTContext().Deallocate(getExtInfo());
4790
        TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4791
      }
4792
      else
4793
        getExtInfo()->QualifierLoc = QualifierLoc;
4794
    }
4795
  }
4796
}
4797

4798
void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4799
  DeclarationName Name = getDeclName();
4800
  // If the name is supposed to have an identifier but does not have one, then
4801
  // the tag is anonymous and we should print it differently.
4802
  if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4803
    // If the caller wanted to print a qualified name, they've already printed
4804
    // the scope. And if the caller doesn't want that, the scope information
4805
    // is already printed as part of the type.
4806
    PrintingPolicy Copy(Policy);
4807
    Copy.SuppressScope = true;
4808
    getASTContext().getTagDeclType(this).print(OS, Copy);
4809
    return;
4810
  }
4811
  // Otherwise, do the normal printing.
4812
  Name.print(OS, Policy);
4813
}
4814

4815
void TagDecl::setTemplateParameterListsInfo(
4816
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4817
  assert(!TPLists.empty());
4818
  // Make sure the extended decl info is allocated.
4819
  if (!hasExtInfo())
4820
    // Allocate external info struct.
4821
    TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4822
  // Set the template parameter lists info.
4823
  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4824
}
4825

4826
//===----------------------------------------------------------------------===//
4827
// EnumDecl Implementation
4828
//===----------------------------------------------------------------------===//
4829

4830
EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4831
                   SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4832
                   bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4833
    : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4834
  assert(Scoped || !ScopedUsingClassTag);
4835
  IntegerType = nullptr;
4836
  setNumPositiveBits(0);
4837
  setNumNegativeBits(0);
4838
  setScoped(Scoped);
4839
  setScopedUsingClassTag(ScopedUsingClassTag);
4840
  setFixed(Fixed);
4841
  setHasODRHash(false);
4842
  ODRHash = 0;
4843
}
4844

4845
void EnumDecl::anchor() {}
4846

4847
EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4848
                           SourceLocation StartLoc, SourceLocation IdLoc,
4849
                           IdentifierInfo *Id,
4850
                           EnumDecl *PrevDecl, bool IsScoped,
4851
                           bool IsScopedUsingClassTag, bool IsFixed) {
4852
  auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4853
                                    IsScoped, IsScopedUsingClassTag, IsFixed);
4854
  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4855
  C.getTypeDeclType(Enum, PrevDecl);
4856
  return Enum;
4857
}
4858

4859
EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
4860
  EnumDecl *Enum =
4861
      new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4862
                           nullptr, nullptr, false, false, false);
4863
  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4864
  return Enum;
4865
}
4866

4867
SourceRange EnumDecl::getIntegerTypeRange() const {
4868
  if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4869
    return TI->getTypeLoc().getSourceRange();
4870
  return SourceRange();
4871
}
4872

4873
void EnumDecl::completeDefinition(QualType NewType,
4874
                                  QualType NewPromotionType,
4875
                                  unsigned NumPositiveBits,
4876
                                  unsigned NumNegativeBits) {
4877
  assert(!isCompleteDefinition() && "Cannot redefine enums!");
4878
  if (!IntegerType)
4879
    IntegerType = NewType.getTypePtr();
4880
  PromotionType = NewPromotionType;
4881
  setNumPositiveBits(NumPositiveBits);
4882
  setNumNegativeBits(NumNegativeBits);
4883
  TagDecl::completeDefinition();
4884
}
4885

4886
bool EnumDecl::isClosed() const {
4887
  if (const auto *A = getAttr<EnumExtensibilityAttr>())
4888
    return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4889
  return true;
4890
}
4891

4892
bool EnumDecl::isClosedFlag() const {
4893
  return isClosed() && hasAttr<FlagEnumAttr>();
4894
}
4895

4896
bool EnumDecl::isClosedNonFlag() const {
4897
  return isClosed() && !hasAttr<FlagEnumAttr>();
4898
}
4899

4900
TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4901
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4902
    return MSI->getTemplateSpecializationKind();
4903

4904
  return TSK_Undeclared;
4905
}
4906

4907
void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4908
                                         SourceLocation PointOfInstantiation) {
4909
  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4910
  assert(MSI && "Not an instantiated member enumeration?");
4911
  MSI->setTemplateSpecializationKind(TSK);
4912
  if (TSK != TSK_ExplicitSpecialization &&
4913
      PointOfInstantiation.isValid() &&
4914
      MSI->getPointOfInstantiation().isInvalid())
4915
    MSI->setPointOfInstantiation(PointOfInstantiation);
4916
}
4917

4918
EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4919
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4920
    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4921
      EnumDecl *ED = getInstantiatedFromMemberEnum();
4922
      while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4923
        ED = NewED;
4924
      return getDefinitionOrSelf(ED);
4925
    }
4926
  }
4927

4928
  assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4929
         "couldn't find pattern for enum instantiation");
4930
  return nullptr;
4931
}
4932

4933
EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4934
  if (SpecializationInfo)
4935
    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4936

4937
  return nullptr;
4938
}
4939

4940
void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4941
                                            TemplateSpecializationKind TSK) {
4942
  assert(!SpecializationInfo && "Member enum is already a specialization");
4943
  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4944
}
4945

4946
unsigned EnumDecl::getODRHash() {
4947
  if (hasODRHash())
4948
    return ODRHash;
4949

4950
  class ODRHash Hash;
4951
  Hash.AddEnumDecl(this);
4952
  setHasODRHash(true);
4953
  ODRHash = Hash.CalculateHash();
4954
  return ODRHash;
4955
}
4956

4957
SourceRange EnumDecl::getSourceRange() const {
4958
  auto Res = TagDecl::getSourceRange();
4959
  // Set end-point to enum-base, e.g. enum foo : ^bar
4960
  if (auto *TSI = getIntegerTypeSourceInfo()) {
4961
    // TagDecl doesn't know about the enum base.
4962
    if (!getBraceRange().getEnd().isValid())
4963
      Res.setEnd(TSI->getTypeLoc().getEndLoc());
4964
  }
4965
  return Res;
4966
}
4967

4968
void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
4969
  unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
4970
  unsigned NumNegativeBits = getNumNegativeBits();
4971
  unsigned NumPositiveBits = getNumPositiveBits();
4972

4973
  if (NumNegativeBits) {
4974
    unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
4975
    Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
4976
    Min = -Max;
4977
  } else {
4978
    Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
4979
    Min = llvm::APInt::getZero(Bitwidth);
4980
  }
4981
}
4982

4983
//===----------------------------------------------------------------------===//
4984
// RecordDecl Implementation
4985
//===----------------------------------------------------------------------===//
4986

4987
RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4988
                       DeclContext *DC, SourceLocation StartLoc,
4989
                       SourceLocation IdLoc, IdentifierInfo *Id,
4990
                       RecordDecl *PrevDecl)
4991
    : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4992
  assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4993
  setHasFlexibleArrayMember(false);
4994
  setAnonymousStructOrUnion(false);
4995
  setHasObjectMember(false);
4996
  setHasVolatileMember(false);
4997
  setHasLoadedFieldsFromExternalStorage(false);
4998
  setNonTrivialToPrimitiveDefaultInitialize(false);
4999
  setNonTrivialToPrimitiveCopy(false);
5000
  setNonTrivialToPrimitiveDestroy(false);
5001
  setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
5002
  setHasNonTrivialToPrimitiveDestructCUnion(false);
5003
  setHasNonTrivialToPrimitiveCopyCUnion(false);
5004
  setParamDestroyedInCallee(false);
5005
  setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);
5006
  setIsRandomized(false);
5007
  setODRHash(0);
5008
}
5009

5010
RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
5011
                               SourceLocation StartLoc, SourceLocation IdLoc,
5012
                               IdentifierInfo *Id, RecordDecl* PrevDecl) {
5013
  RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
5014
                                         StartLoc, IdLoc, Id, PrevDecl);
5015
  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5016

5017
  C.getTypeDeclType(R, PrevDecl);
5018
  return R;
5019
}
5020

5021
RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C,
5022
                                           GlobalDeclID ID) {
5023
  RecordDecl *R = new (C, ID)
5024
      RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(),
5025
                 SourceLocation(), nullptr, nullptr);
5026
  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5027
  return R;
5028
}
5029

5030
bool RecordDecl::isInjectedClassName() const {
5031
  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
5032
    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
5033
}
5034

5035
bool RecordDecl::isLambda() const {
5036
  if (auto RD = dyn_cast<CXXRecordDecl>(this))
5037
    return RD->isLambda();
5038
  return false;
5039
}
5040

5041
bool RecordDecl::isCapturedRecord() const {
5042
  return hasAttr<CapturedRecordAttr>();
5043
}
5044

5045
void RecordDecl::setCapturedRecord() {
5046
  addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
5047
}
5048

5049
bool RecordDecl::isOrContainsUnion() const {
5050
  if (isUnion())
5051
    return true;
5052

5053
  if (const RecordDecl *Def = getDefinition()) {
5054
    for (const FieldDecl *FD : Def->fields()) {
5055
      const RecordType *RT = FD->getType()->getAs<RecordType>();
5056
      if (RT && RT->getDecl()->isOrContainsUnion())
5057
        return true;
5058
    }
5059
  }
5060

5061
  return false;
5062
}
5063

5064
RecordDecl::field_iterator RecordDecl::field_begin() const {
5065
  if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
5066
    LoadFieldsFromExternalStorage();
5067
  // This is necessary for correctness for C++ with modules.
5068
  // FIXME: Come up with a test case that breaks without definition.
5069
  if (RecordDecl *D = getDefinition(); D && D != this)
5070
    return D->field_begin();
5071
  return field_iterator(decl_iterator(FirstDecl));
5072
}
5073

5074
/// completeDefinition - Notes that the definition of this type is now
5075
/// complete.
5076
void RecordDecl::completeDefinition() {
5077
  assert(!isCompleteDefinition() && "Cannot redefine record!");
5078
  TagDecl::completeDefinition();
5079

5080
  ASTContext &Ctx = getASTContext();
5081

5082
  // Layouts are dumped when computed, so if we are dumping for all complete
5083
  // types, we need to force usage to get types that wouldn't be used elsewhere.
5084
  //
5085
  // If the type is dependent, then we can't compute its layout because there
5086
  // is no way for us to know the size or alignment of a dependent type. Also
5087
  // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5088
  // on that.
5089
  if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5090
      !isInvalidDecl())
5091
    (void)Ctx.getASTRecordLayout(this);
5092
}
5093

5094
/// isMsStruct - Get whether or not this record uses ms_struct layout.
5095
/// This which can be turned on with an attribute, pragma, or the
5096
/// -mms-bitfields command-line option.
5097
bool RecordDecl::isMsStruct(const ASTContext &C) const {
5098
  return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
5099
}
5100

5101
void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {
5102
  std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
5103
  LastDecl->NextInContextAndBits.setPointer(nullptr);
5104
  setIsRandomized(true);
5105
}
5106

5107
void RecordDecl::LoadFieldsFromExternalStorage() const {
5108
  ExternalASTSource *Source = getASTContext().getExternalSource();
5109
  assert(hasExternalLexicalStorage() && Source && "No external storage?");
5110

5111
  // Notify that we have a RecordDecl doing some initialization.
5112
  ExternalASTSource::Deserializing TheFields(Source);
5113

5114
  SmallVector<Decl*, 64> Decls;
5115
  setHasLoadedFieldsFromExternalStorage(true);
5116
  Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
5117
    return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
5118
  }, Decls);
5119

5120
#ifndef NDEBUG
5121
  // Check that all decls we got were FieldDecls.
5122
  for (unsigned i=0, e=Decls.size(); i != e; ++i)
5123
    assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5124
#endif
5125

5126
  if (Decls.empty())
5127
    return;
5128

5129
  auto [ExternalFirst, ExternalLast] =
5130
      BuildDeclChain(Decls,
5131
                     /*FieldsAlreadyLoaded=*/false);
5132
  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5133
  FirstDecl = ExternalFirst;
5134
  if (!LastDecl)
5135
    LastDecl = ExternalLast;
5136
}
5137

5138
bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5139
  ASTContext &Context = getASTContext();
5140
  const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5141
      (SanitizerKind::Address | SanitizerKind::KernelAddress);
5142
  if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5143
    return false;
5144
  const auto &NoSanitizeList = Context.getNoSanitizeList();
5145
  const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
5146
  // We may be able to relax some of these requirements.
5147
  int ReasonToReject = -1;
5148
  if (!CXXRD || CXXRD->isExternCContext())
5149
    ReasonToReject = 0;  // is not C++.
5150
  else if (CXXRD->hasAttr<PackedAttr>())
5151
    ReasonToReject = 1;  // is packed.
5152
  else if (CXXRD->isUnion())
5153
    ReasonToReject = 2;  // is a union.
5154
  else if (CXXRD->isTriviallyCopyable())
5155
    ReasonToReject = 3;  // is trivially copyable.
5156
  else if (CXXRD->hasTrivialDestructor())
5157
    ReasonToReject = 4;  // has trivial destructor.
5158
  else if (CXXRD->isStandardLayout())
5159
    ReasonToReject = 5;  // is standard layout.
5160
  else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
5161
                                           "field-padding"))
5162
    ReasonToReject = 6;  // is in an excluded file.
5163
  else if (NoSanitizeList.containsType(
5164
               EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
5165
    ReasonToReject = 7;  // The type is excluded.
5166

5167
  if (EmitRemark) {
5168
    if (ReasonToReject >= 0)
5169
      Context.getDiagnostics().Report(
5170
          getLocation(),
5171
          diag::remark_sanitize_address_insert_extra_padding_rejected)
5172
          << getQualifiedNameAsString() << ReasonToReject;
5173
    else
5174
      Context.getDiagnostics().Report(
5175
          getLocation(),
5176
          diag::remark_sanitize_address_insert_extra_padding_accepted)
5177
          << getQualifiedNameAsString();
5178
  }
5179
  return ReasonToReject < 0;
5180
}
5181

5182
const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
5183
  for (const auto *I : fields()) {
5184
    if (I->getIdentifier())
5185
      return I;
5186

5187
    if (const auto *RT = I->getType()->getAs<RecordType>())
5188
      if (const FieldDecl *NamedDataMember =
5189
              RT->getDecl()->findFirstNamedDataMember())
5190
        return NamedDataMember;
5191
  }
5192

5193
  // We didn't find a named data member.
5194
  return nullptr;
5195
}
5196

5197
unsigned RecordDecl::getODRHash() {
5198
  if (hasODRHash())
5199
    return RecordDeclBits.ODRHash;
5200

5201
  // Only calculate hash on first call of getODRHash per record.
5202
  ODRHash Hash;
5203
  Hash.AddRecordDecl(this);
5204
  // For RecordDecl the ODRHash is stored in the remaining 26
5205
  // bit of RecordDeclBits, adjust the hash to accomodate.
5206
  setODRHash(Hash.CalculateHash() >> 6);
5207
  return RecordDeclBits.ODRHash;
5208
}
5209

5210
//===----------------------------------------------------------------------===//
5211
// BlockDecl Implementation
5212
//===----------------------------------------------------------------------===//
5213

5214
BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
5215
    : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5216
  setIsVariadic(false);
5217
  setCapturesCXXThis(false);
5218
  setBlockMissingReturnType(true);
5219
  setIsConversionFromLambda(false);
5220
  setDoesNotEscape(false);
5221
  setCanAvoidCopyToHeap(false);
5222
}
5223

5224
void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
5225
  assert(!ParamInfo && "Already has param info!");
5226

5227
  // Zero params -> null pointer.
5228
  if (!NewParamInfo.empty()) {
5229
    NumParams = NewParamInfo.size();
5230
    ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5231
    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
5232
  }
5233
}
5234

5235
void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
5236
                            bool CapturesCXXThis) {
5237
  this->setCapturesCXXThis(CapturesCXXThis);
5238
  this->NumCaptures = Captures.size();
5239

5240
  if (Captures.empty()) {
5241
    this->Captures = nullptr;
5242
    return;
5243
  }
5244

5245
  this->Captures = Captures.copy(Context).data();
5246
}
5247

5248
bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5249
  for (const auto &I : captures())
5250
    // Only auto vars can be captured, so no redeclaration worries.
5251
    if (I.getVariable() == variable)
5252
      return true;
5253

5254
  return false;
5255
}
5256

5257
SourceRange BlockDecl::getSourceRange() const {
5258
  return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5259
}
5260

5261
//===----------------------------------------------------------------------===//
5262
// Other Decl Allocation/Deallocation Method Implementations
5263
//===----------------------------------------------------------------------===//
5264

5265
void TranslationUnitDecl::anchor() {}
5266

5267
TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
5268
  return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5269
}
5270

5271
void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) {
5272
  AnonymousNamespace = D;
5273

5274
  if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5275
    Listener->AddedAnonymousNamespace(this, D);
5276
}
5277

5278
void PragmaCommentDecl::anchor() {}
5279

5280
PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
5281
                                             TranslationUnitDecl *DC,
5282
                                             SourceLocation CommentLoc,
5283
                                             PragmaMSCommentKind CommentKind,
5284
                                             StringRef Arg) {
5285
  PragmaCommentDecl *PCD =
5286
      new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
5287
          PragmaCommentDecl(DC, CommentLoc, CommentKind);
5288
  memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
5289
  PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
5290
  return PCD;
5291
}
5292

5293
PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
5294
                                                         GlobalDeclID ID,
5295
                                                         unsigned ArgSize) {
5296
  return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
5297
      PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
5298
}
5299

5300
void PragmaDetectMismatchDecl::anchor() {}
5301

5302
PragmaDetectMismatchDecl *
5303
PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
5304
                                 SourceLocation Loc, StringRef Name,
5305
                                 StringRef Value) {
5306
  size_t ValueStart = Name.size() + 1;
5307
  PragmaDetectMismatchDecl *PDMD =
5308
      new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
5309
          PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5310
  memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
5311
  PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
5312
  memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
5313
         Value.size());
5314
  PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
5315
  return PDMD;
5316
}
5317

5318
PragmaDetectMismatchDecl *
5319
PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5320
                                             unsigned NameValueSize) {
5321
  return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5322
      PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
5323
}
5324

5325
void ExternCContextDecl::anchor() {}
5326

5327
ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
5328
                                               TranslationUnitDecl *DC) {
5329
  return new (C, DC) ExternCContextDecl(DC);
5330
}
5331

5332
void LabelDecl::anchor() {}
5333

5334
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5335
                             SourceLocation IdentL, IdentifierInfo *II) {
5336
  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5337
}
5338

5339
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5340
                             SourceLocation IdentL, IdentifierInfo *II,
5341
                             SourceLocation GnuLabelL) {
5342
  assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5343
  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5344
}
5345

5346
LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5347
  return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5348
                               SourceLocation());
5349
}
5350

5351
void LabelDecl::setMSAsmLabel(StringRef Name) {
5352
char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5353
  memcpy(Buffer, Name.data(), Name.size());
5354
  Buffer[Name.size()] = '\0';
5355
  MSAsmName = Buffer;
5356
}
5357

5358
void ValueDecl::anchor() {}
5359

5360
bool ValueDecl::isWeak() const {
5361
  auto *MostRecent = getMostRecentDecl();
5362
  return MostRecent->hasAttr<WeakAttr>() ||
5363
         MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5364
}
5365

5366
bool ValueDecl::isInitCapture() const {
5367
  if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5368
    return Var->isInitCapture();
5369
  return false;
5370
}
5371

5372
void ImplicitParamDecl::anchor() {}
5373

5374
ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
5375
                                             SourceLocation IdLoc,
5376
                                             IdentifierInfo *Id, QualType Type,
5377
                                             ImplicitParamKind ParamKind) {
5378
  return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5379
}
5380

5381
ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
5382
                                             ImplicitParamKind ParamKind) {
5383
  return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5384
}
5385

5386
ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
5387
                                                         GlobalDeclID ID) {
5388
  return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
5389
}
5390

5391
FunctionDecl *
5392
FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5393
                     const DeclarationNameInfo &NameInfo, QualType T,
5394
                     TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5395
                     bool isInlineSpecified, bool hasWrittenPrototype,
5396
                     ConstexprSpecKind ConstexprKind,
5397
                     Expr *TrailingRequiresClause) {
5398
  FunctionDecl *New = new (C, DC) FunctionDecl(
5399
      Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5400
      isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5401
  New->setHasWrittenPrototype(hasWrittenPrototype);
5402
  return New;
5403
}
5404

5405
FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5406
  return new (C, ID) FunctionDecl(
5407
      Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
5408
      nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
5409
}
5410

5411
BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5412
  return new (C, DC) BlockDecl(DC, L);
5413
}
5414

5415
BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5416
  return new (C, ID) BlockDecl(nullptr, SourceLocation());
5417
}
5418

5419
CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5420
    : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5421
      NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5422

5423
CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
5424
                                   unsigned NumParams) {
5425
  return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5426
      CapturedDecl(DC, NumParams);
5427
}
5428

5429
CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5430
                                               unsigned NumParams) {
5431
  return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5432
      CapturedDecl(nullptr, NumParams);
5433
}
5434

5435
Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5436
void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5437

5438
bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5439
void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5440

5441
EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC,
5442
                                   SourceLocation L, IdentifierInfo *Id,
5443
                                   QualType T, Expr *E, const llvm::APSInt &V)
5444
    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5445
  setInitVal(C, V);
5446
}
5447

5448
EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
5449
                                           SourceLocation L,
5450
                                           IdentifierInfo *Id, QualType T,
5451
                                           Expr *E, const llvm::APSInt &V) {
5452
  return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5453
}
5454

5455
EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C,
5456
                                                       GlobalDeclID ID) {
5457
  return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5458
                                      QualType(), nullptr, llvm::APSInt());
5459
}
5460

5461
void IndirectFieldDecl::anchor() {}
5462

5463
IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5464
                                     SourceLocation L, DeclarationName N,
5465
                                     QualType T,
5466
                                     MutableArrayRef<NamedDecl *> CH)
5467
    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5468
      ChainingSize(CH.size()) {
5469
  // In C++, indirect field declarations conflict with tag declarations in the
5470
  // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5471
  if (C.getLangOpts().CPlusPlus)
5472
    IdentifierNamespace |= IDNS_Tag;
5473
}
5474

5475
IndirectFieldDecl *
5476
IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
5477
                          const IdentifierInfo *Id, QualType T,
5478
                          llvm::MutableArrayRef<NamedDecl *> CH) {
5479
  return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5480
}
5481

5482
IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
5483
                                                         GlobalDeclID ID) {
5484
  return new (C, ID)
5485
      IndirectFieldDecl(C, nullptr, SourceLocation(), DeclarationName(),
5486
                        QualType(), std::nullopt);
5487
}
5488

5489
SourceRange EnumConstantDecl::getSourceRange() const {
5490
  SourceLocation End = getLocation();
5491
  if (Init)
5492
    End = Init->getEndLoc();
5493
  return SourceRange(getLocation(), End);
5494
}
5495

5496
void TypeDecl::anchor() {}
5497

5498
TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
5499
                                 SourceLocation StartLoc, SourceLocation IdLoc,
5500
                                 const IdentifierInfo *Id,
5501
                                 TypeSourceInfo *TInfo) {
5502
  return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5503
}
5504

5505
void TypedefNameDecl::anchor() {}
5506

5507
TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
5508
  if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5509
    auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5510
    auto *ThisTypedef = this;
5511
    if (AnyRedecl && OwningTypedef) {
5512
      OwningTypedef = OwningTypedef->getCanonicalDecl();
5513
      ThisTypedef = ThisTypedef->getCanonicalDecl();
5514
    }
5515
    if (OwningTypedef == ThisTypedef)
5516
      return TT->getDecl();
5517
  }
5518

5519
  return nullptr;
5520
}
5521

5522
bool TypedefNameDecl::isTransparentTagSlow() const {
5523
  auto determineIsTransparent = [&]() {
5524
    if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5525
      if (auto *TD = TT->getDecl()) {
5526
        if (TD->getName() != getName())
5527
          return false;
5528
        SourceLocation TTLoc = getLocation();
5529
        SourceLocation TDLoc = TD->getLocation();
5530
        if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5531
          return false;
5532
        SourceManager &SM = getASTContext().getSourceManager();
5533
        return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5534
      }
5535
    }
5536
    return false;
5537
  };
5538

5539
  bool isTransparent = determineIsTransparent();
5540
  MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5541
  return isTransparent;
5542
}
5543

5544
TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5545
  return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5546
                                 nullptr, nullptr);
5547
}
5548

5549
TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
5550
                                     SourceLocation StartLoc,
5551
                                     SourceLocation IdLoc,
5552
                                     const IdentifierInfo *Id,
5553
                                     TypeSourceInfo *TInfo) {
5554
  return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5555
}
5556

5557
TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C,
5558
                                                 GlobalDeclID ID) {
5559
  return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5560
                                   SourceLocation(), nullptr, nullptr);
5561
}
5562

5563
SourceRange TypedefDecl::getSourceRange() const {
5564
  SourceLocation RangeEnd = getLocation();
5565
  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5566
    if (typeIsPostfix(TInfo->getType()))
5567
      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5568
  }
5569
  return SourceRange(getBeginLoc(), RangeEnd);
5570
}
5571

5572
SourceRange TypeAliasDecl::getSourceRange() const {
5573
  SourceLocation RangeEnd = getBeginLoc();
5574
  if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5575
    RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5576
  return SourceRange(getBeginLoc(), RangeEnd);
5577
}
5578

5579
void FileScopeAsmDecl::anchor() {}
5580

5581
FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5582
                                           StringLiteral *Str,
5583
                                           SourceLocation AsmLoc,
5584
                                           SourceLocation RParenLoc) {
5585
  return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5586
}
5587

5588
FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5589
                                                       GlobalDeclID ID) {
5590
  return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5591
                                      SourceLocation());
5592
}
5593

5594
void TopLevelStmtDecl::anchor() {}
5595

5596
TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {
5597
  assert(C.getLangOpts().IncrementalExtensions &&
5598
         "Must be used only in incremental mode");
5599

5600
  SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5601
  DeclContext *DC = C.getTranslationUnitDecl();
5602

5603
  return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5604
}
5605

5606
TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,
5607
                                                       GlobalDeclID ID) {
5608
  return new (C, ID)
5609
      TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5610
}
5611

5612
SourceRange TopLevelStmtDecl::getSourceRange() const {
5613
  return SourceRange(getLocation(), Statement->getEndLoc());
5614
}
5615

5616
void TopLevelStmtDecl::setStmt(Stmt *S) {
5617
  assert(S);
5618
  Statement = S;
5619
  setLocation(Statement->getBeginLoc());
5620
}
5621

5622
void EmptyDecl::anchor() {}
5623

5624
EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5625
  return new (C, DC) EmptyDecl(DC, L);
5626
}
5627

5628
EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5629
  return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5630
}
5631

5632
HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5633
                               SourceLocation KwLoc, IdentifierInfo *ID,
5634
                               SourceLocation IDLoc, SourceLocation LBrace)
5635
    : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5636
      DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5637
      IsCBuffer(CBuffer) {}
5638

5639
HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,
5640
                                       DeclContext *LexicalParent, bool CBuffer,
5641
                                       SourceLocation KwLoc, IdentifierInfo *ID,
5642
                                       SourceLocation IDLoc,
5643
                                       SourceLocation LBrace) {
5644
  // For hlsl like this
5645
  // cbuffer A {
5646
  //     cbuffer B {
5647
  //     }
5648
  // }
5649
  // compiler should treat it as
5650
  // cbuffer A {
5651
  // }
5652
  // cbuffer B {
5653
  // }
5654
  // FIXME: support nested buffers if required for back-compat.
5655
  DeclContext *DC = LexicalParent;
5656
  HLSLBufferDecl *Result =
5657
      new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5658
  return Result;
5659
}
5660

5661
HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,
5662
                                                   GlobalDeclID ID) {
5663
  return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
5664
                                    SourceLocation(), SourceLocation());
5665
}
5666

5667
//===----------------------------------------------------------------------===//
5668
// ImportDecl Implementation
5669
//===----------------------------------------------------------------------===//
5670

5671
/// Retrieve the number of module identifiers needed to name the given
5672
/// module.
5673
static unsigned getNumModuleIdentifiers(Module *Mod) {
5674
  unsigned Result = 1;
5675
  while (Mod->Parent) {
5676
    Mod = Mod->Parent;
5677
    ++Result;
5678
  }
5679
  return Result;
5680
}
5681

5682
ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5683
                       Module *Imported,
5684
                       ArrayRef<SourceLocation> IdentifierLocs)
5685
    : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5686
      NextLocalImportAndComplete(nullptr, true) {
5687
  assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5688
  auto *StoredLocs = getTrailingObjects<SourceLocation>();
5689
  std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5690
                          StoredLocs);
5691
}
5692

5693
ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5694
                       Module *Imported, SourceLocation EndLoc)
5695
    : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5696
      NextLocalImportAndComplete(nullptr, false) {
5697
  *getTrailingObjects<SourceLocation>() = EndLoc;
5698
}
5699

5700
ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5701
                               SourceLocation StartLoc, Module *Imported,
5702
                               ArrayRef<SourceLocation> IdentifierLocs) {
5703
  return new (C, DC,
5704
              additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5705
      ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5706
}
5707

5708
ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5709
                                       SourceLocation StartLoc,
5710
                                       Module *Imported,
5711
                                       SourceLocation EndLoc) {
5712
  ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5713
      ImportDecl(DC, StartLoc, Imported, EndLoc);
5714
  Import->setImplicit();
5715
  return Import;
5716
}
5717

5718
ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5719
                                           unsigned NumLocations) {
5720
  return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5721
      ImportDecl(EmptyShell());
5722
}
5723

5724
ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5725
  if (!isImportComplete())
5726
    return std::nullopt;
5727

5728
  const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5729
  return llvm::ArrayRef(StoredLocs,
5730
                        getNumModuleIdentifiers(getImportedModule()));
5731
}
5732

5733
SourceRange ImportDecl::getSourceRange() const {
5734
  if (!isImportComplete())
5735
    return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5736

5737
  return SourceRange(getLocation(), getIdentifierLocs().back());
5738
}
5739

5740
//===----------------------------------------------------------------------===//
5741
// ExportDecl Implementation
5742
//===----------------------------------------------------------------------===//
5743

5744
void ExportDecl::anchor() {}
5745

5746
ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5747
                               SourceLocation ExportLoc) {
5748
  return new (C, DC) ExportDecl(DC, ExportLoc);
5749
}
5750

5751
ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5752
  return new (C, ID) ExportDecl(nullptr, SourceLocation());
5753
}
5754

5755
bool clang::IsArmStreamingFunction(const FunctionDecl *FD,
5756
                                   bool IncludeLocallyStreaming) {
5757
  if (IncludeLocallyStreaming)
5758
    if (FD->hasAttr<ArmLocallyStreamingAttr>())
5759
      return true;
5760

5761
  if (const Type *Ty = FD->getType().getTypePtrOrNull())
5762
    if (const auto *FPT = Ty->getAs<FunctionProtoType>())
5763
      if (FPT->getAArch64SMEAttributes() &
5764
          FunctionType::SME_PStateSMEnabledMask)
5765
        return true;
5766

5767
  return false;
5768
}
5769

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.