Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/Decl.cpp
Line
Count
Source (jump to first uncovered line)
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/None.h"
58
#include "llvm/ADT/Optional.h"
59
#include "llvm/ADT/STLExtras.h"
60
#include "llvm/ADT/SmallVector.h"
61
#include "llvm/ADT/StringRef.h"
62
#include "llvm/ADT/StringSwitch.h"
63
#include "llvm/ADT/Triple.h"
64
#include "llvm/Support/Casting.h"
65
#include "llvm/Support/ErrorHandling.h"
66
#include "llvm/Support/raw_ostream.h"
67
#include <algorithm>
68
#include <cassert>
69
#include <cstddef>
70
#include <cstring>
71
#include <memory>
72
#include <string>
73
#include <tuple>
74
#include <type_traits>
75
76
using namespace clang;
77
78
1.88M
Decl *clang::getPrimaryMergedDecl(Decl *D) {
79
1.88M
  return D->getASTContext().getPrimaryMergedDecl(D);
80
1.88M
}
81
82
0
void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
83
0
  SourceLocation Loc = this->Loc;
84
0
  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
85
0
  if (Loc.isValid()) {
86
0
    Loc.print(OS, Context.getSourceManager());
87
0
    OS << ": ";
88
0
  }
89
0
  OS << Message;
90
91
0
  if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
92
0
    OS << " '";
93
0
    ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
94
0
    OS << "'";
95
0
  }
96
97
0
  OS << '\n';
98
0
}
99
100
// Defined here so that it can be inlined into its direct callers.
101
103M
bool Decl::isOutOfLine() const {
102
103M
  return !getLexicalDeclContext()->Equals(getDeclContext());
103
103M
}
104
105
TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
106
    : Decl(TranslationUnit, nullptr, SourceLocation()),
107
96.7k
      DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
108
109
//===----------------------------------------------------------------------===//
110
// NamedDecl Implementation
111
//===----------------------------------------------------------------------===//
112
113
// Visibility rules aren't rigorously externally specified, but here
114
// are the basic principles behind what we implement:
115
//
116
// 1. An explicit visibility attribute is generally a direct expression
117
// of the user's intent and should be honored.  Only the innermost
118
// visibility attribute applies.  If no visibility attribute applies,
119
// global visibility settings are considered.
120
//
121
// 2. There is one caveat to the above: on or in a template pattern,
122
// an explicit visibility attribute is just a default rule, and
123
// visibility can be decreased by the visibility of template
124
// arguments.  But this, too, has an exception: an attribute on an
125
// explicit specialization or instantiation causes all the visibility
126
// restrictions of the template arguments to be ignored.
127
//
128
// 3. A variable that does not otherwise have explicit visibility can
129
// be restricted by the visibility of its type.
130
//
131
// 4. A visibility restriction is explicit if it comes from an
132
// attribute (or something like it), not a global visibility setting.
133
// When emitting a reference to an external symbol, visibility
134
// restrictions are ignored unless they are explicit.
135
//
136
// 5. When computing the visibility of a non-type, including a
137
// non-type member of a class, only non-type visibility restrictions
138
// are considered: the 'visibility' attribute, global value-visibility
139
// settings, and a few special cases like __private_extern.
140
//
141
// 6. When computing the visibility of a type, including a type member
142
// of a class, only type visibility restrictions are considered:
143
// the 'type_visibility' attribute and global type-visibility settings.
144
// However, a 'visibility' attribute counts as a 'type_visibility'
145
// attribute on any declaration that only has the former.
146
//
147
// The visibility of a "secondary" entity, like a template argument,
148
// is computed using the kind of that entity, not the kind of the
149
// primary entity for which we are computing visibility.  For example,
150
// the visibility of a specialization of either of these templates:
151
//   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
152
//   template <class T, bool (&compare)(T, X)> class matcher;
153
// is restricted according to the type visibility of the argument 'T',
154
// the type visibility of 'bool(&)(T,X)', and the value visibility of
155
// the argument function 'compare'.  That 'has_match' is a value
156
// and 'matcher' is a type only matters when looking for attributes
157
// and settings from the immediate context.
158
159
/// Does this computation kind permit us to consider additional
160
/// visibility settings from attributes and the like?
161
11.4M
static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
162
11.4M
  return computation.IgnoreExplicitVisibility;
163
11.4M
}
164
165
/// Given an LVComputationKind, return one of the same type/value sort
166
/// that records that it already has explicit visibility.
167
static LVComputationKind
168
177k
withExplicitVisibilityAlready(LVComputationKind Kind) {
169
177k
  Kind.IgnoreExplicitVisibility = true;
170
177k
  return Kind;
171
177k
}
172
173
static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
174
2.48M
                                                  LVComputationKind kind) {
175
2.48M
  assert(!kind.IgnoreExplicitVisibility &&
176
2.48M
         "asking for explicit visibility when we shouldn't be");
177
0
  return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
178
2.48M
}
179
180
/// Is the given declaration a "type" or a "value" for the purposes of
181
/// visibility computation?
182
1.99M
static bool usesTypeVisibility(const NamedDecl *D) {
183
1.99M
  return isa<TypeDecl>(D) ||
184
1.99M
         
isa<ClassTemplateDecl>(D)1.15M
||
185
1.99M
         
isa<ObjCInterfaceDecl>(D)1.15M
;
186
1.99M
}
187
188
/// Does the given declaration have member specialization information,
189
/// and if so, is it an explicit specialization?
190
template <class T> static typename
191
std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
192
1.73M
isExplicitMemberSpecialization(const T *D) {
193
1.73M
  if (const MemberSpecializationInfo *member =
194
1.73M
        D->getMemberSpecializationInfo()) {
195
715k
    return member->isExplicitSpecialization();
196
715k
  }
197
1.01M
  return false;
198
1.73M
}
Decl.cpp:std::__1::enable_if<!(std::is_base_of<clang::RedeclarableTemplateDecl, clang::CXXMethodDecl>::value), bool>::type isExplicitMemberSpecialization<clang::CXXMethodDecl>(clang::CXXMethodDecl const*)
Line
Count
Source
192
1.54M
isExplicitMemberSpecialization(const T *D) {
193
1.54M
  if (const MemberSpecializationInfo *member =
194
1.54M
        D->getMemberSpecializationInfo()) {
195
655k
    return member->isExplicitSpecialization();
196
655k
  }
197
888k
  return false;
198
1.54M
}
Decl.cpp:std::__1::enable_if<!(std::is_base_of<clang::RedeclarableTemplateDecl, clang::CXXRecordDecl>::value), bool>::type isExplicitMemberSpecialization<clang::CXXRecordDecl>(clang::CXXRecordDecl const*)
Line
Count
Source
192
42.5k
isExplicitMemberSpecialization(const T *D) {
193
42.5k
  if (const MemberSpecializationInfo *member =
194
42.5k
        D->getMemberSpecializationInfo()) {
195
22.1k
    return member->isExplicitSpecialization();
196
22.1k
  }
197
20.3k
  return false;
198
42.5k
}
Decl.cpp:std::__1::enable_if<!(std::is_base_of<clang::RedeclarableTemplateDecl, clang::VarDecl>::value), bool>::type isExplicitMemberSpecialization<clang::VarDecl>(clang::VarDecl const*)
Line
Count
Source
192
144k
isExplicitMemberSpecialization(const T *D) {
193
144k
  if (const MemberSpecializationInfo *member =
194
144k
        D->getMemberSpecializationInfo()) {
195
38.2k
    return member->isExplicitSpecialization();
196
38.2k
  }
197
106k
  return false;
198
144k
}
199
200
/// For templates, this question is easier: a member template can't be
201
/// explicitly instantiated, so there's a single bit indicating whether
202
/// or not this is an explicit member specialization.
203
319k
static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
204
319k
  return D->isMemberSpecialization();
205
319k
}
206
207
/// Given a visibility attribute, return the explicit visibility
208
/// associated with it.
209
template <class T>
210
743k
static Visibility getVisibilityFromAttr(const T *attr) {
211
743k
  switch (attr->getVisibility()) {
212
485k
  case T::Default:
213
485k
    return DefaultVisibility;
214
257k
  case T::Hidden:
215
257k
    return HiddenVisibility;
216
183
  case T::Protected:
217
183
    return ProtectedVisibility;
218
743k
  }
219
0
  llvm_unreachable("bad visibility kind");
220
0
}
Decl.cpp:clang::Visibility getVisibilityFromAttr<clang::TypeVisibilityAttr>(clang::TypeVisibilityAttr const*)
Line
Count
Source
210
404k
static Visibility getVisibilityFromAttr(const T *attr) {
211
404k
  switch (attr->getVisibility()) {
212
404k
  case T::Default:
213
404k
    return DefaultVisibility;
214
32
  case T::Hidden:
215
32
    return HiddenVisibility;
216
9
  case T::Protected:
217
9
    return ProtectedVisibility;
218
404k
  }
219
0
  llvm_unreachable("bad visibility kind");
220
0
}
Decl.cpp:clang::Visibility getVisibilityFromAttr<clang::VisibilityAttr>(clang::VisibilityAttr const*)
Line
Count
Source
210
338k
static Visibility getVisibilityFromAttr(const T *attr) {
211
338k
  switch (attr->getVisibility()) {
212
80.7k
  case T::Default:
213
80.7k
    return DefaultVisibility;
214
257k
  case T::Hidden:
215
257k
    return HiddenVisibility;
216
174
  case T::Protected:
217
174
    return ProtectedVisibility;
218
338k
  }
219
0
  llvm_unreachable("bad visibility kind");
220
0
}
221
222
/// Return the explicit visibility of the given declaration.
223
static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
224
3.56M
                                    NamedDecl::ExplicitVisibilityKind kind) {
225
  // If we're ultimately computing the visibility of a type, look for
226
  // a 'type_visibility' attribute before looking for 'visibility'.
227
3.56M
  if (kind == NamedDecl::VisibilityForType) {
228
1.29M
    if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
229
404k
      return getVisibilityFromAttr(A);
230
404k
    }
231
1.29M
  }
232
233
  // If this declaration has an explicit visibility attribute, use it.
234
3.16M
  if (const auto *A = D->getAttr<VisibilityAttr>()) {
235
338k
    return getVisibilityFromAttr(A);
236
338k
  }
237
238
2.82M
  return None;
239
3.16M
}
240
241
LinkageInfo LinkageComputer::getLVForType(const Type &T,
242
2.61M
                                          LVComputationKind computation) {
243
2.61M
  if (computation.IgnoreAllVisibility)
244
1.05M
    return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
245
1.56M
  return getTypeLinkageAndVisibility(&T);
246
2.61M
}
247
248
/// Get the most restrictive linkage for the types in the given
249
/// template parameter list.  For visibility purposes, template
250
/// parameters are part of the signature of a template.
251
LinkageInfo LinkageComputer::getLVForTemplateParameterList(
252
1.86M
    const TemplateParameterList *Params, LVComputationKind computation) {
253
1.86M
  LinkageInfo LV;
254
3.22M
  for (const NamedDecl *P : *Params) {
255
    // Template type parameters are the most common and never
256
    // contribute to visibility, pack or not.
257
3.22M
    if (isa<TemplateTypeParmDecl>(P))
258
2.79M
      continue;
259
260
    // Non-type template parameters can be restricted by the value type, e.g.
261
    //   template <enum X> class A { ... };
262
    // We have to be careful here, though, because we can be dealing with
263
    // dependent types.
264
429k
    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
265
      // Handle the non-pack case first.
266
423k
      if (!NTTP->isExpandedParameterPack()) {
267
423k
        if (!NTTP->getType()->isDependentType()) {
268
359k
          LV.merge(getLVForType(*NTTP->getType(), computation));
269
359k
        }
270
423k
        continue;
271
423k
      }
272
273
      // Look at all the types in an expanded pack.
274
233
      
for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); 83
i != n;
++i150
) {
275
150
        QualType type = NTTP->getExpansionType(i);
276
150
        if (!type->isDependentType())
277
150
          LV.merge(getTypeLinkageAndVisibility(type));
278
150
      }
279
83
      continue;
280
423k
    }
281
282
    // Template template parameters can be restricted by their
283
    // template parameters, recursively.
284
6.24k
    const auto *TTP = cast<TemplateTemplateParmDecl>(P);
285
286
    // Handle the non-pack case first.
287
6.24k
    if (!TTP->isExpandedParameterPack()) {
288
6.19k
      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
289
6.19k
                                             computation));
290
6.19k
      continue;
291
6.19k
    }
292
293
    // Look at all expansions in an expanded pack.
294
53
    for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
295
130
           i != n; 
++i77
) {
296
77
      LV.merge(getLVForTemplateParameterList(
297
77
          TTP->getExpansionTemplateParameters(i), computation));
298
77
    }
299
53
  }
300
301
1.86M
  return LV;
302
1.86M
}
303
304
18.0k
static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
305
18.0k
  const Decl *Ret = nullptr;
306
18.0k
  const DeclContext *DC = D->getDeclContext();
307
43.3k
  while (DC->getDeclKind() != Decl::TranslationUnit) {
308
25.3k
    if (isa<FunctionDecl>(DC) || 
isa<BlockDecl>(DC)7.15k
)
309
18.2k
      Ret = cast<Decl>(DC);
310
25.3k
    DC = DC->getParent();
311
25.3k
  }
312
18.0k
  return Ret;
313
18.0k
}
314
315
/// Get the most restrictive linkage for the types and
316
/// declarations in the given template argument list.
317
///
318
/// Note that we don't take an LVComputationKind because we always
319
/// want to honor the visibility of template arguments in the same way.
320
LinkageInfo
321
LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
322
1.42M
                                              LVComputationKind computation) {
323
1.42M
  LinkageInfo LV;
324
325
2.38M
  for (const TemplateArgument &Arg : Args) {
326
2.38M
    switch (Arg.getKind()) {
327
0
    case TemplateArgument::Null:
328
287k
    case TemplateArgument::Integral:
329
289k
    case TemplateArgument::Expression:
330
289k
      continue;
331
332
1.99M
    case TemplateArgument::Type:
333
1.99M
      LV.merge(getLVForType(*Arg.getAsType(), computation));
334
1.99M
      continue;
335
336
2.30k
    case TemplateArgument::Declaration: {
337
2.30k
      const NamedDecl *ND = Arg.getAsDecl();
338
2.30k
      assert(!usesTypeVisibility(ND));
339
0
      LV.merge(getLVForDecl(ND, computation));
340
2.30k
      continue;
341
287k
    }
342
343
3.65k
    case TemplateArgument::NullPtr:
344
3.65k
      LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
345
3.65k
      continue;
346
347
3.11k
    case TemplateArgument::Template:
348
3.11k
    case TemplateArgument::TemplateExpansion:
349
3.11k
      if (TemplateDecl *Template =
350
3.11k
              Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
351
3.11k
        LV.merge(getLVForDecl(Template, computation));
352
3.11k
      continue;
353
354
88.1k
    case TemplateArgument::Pack:
355
88.1k
      LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
356
88.1k
      continue;
357
2.38M
    }
358
0
    llvm_unreachable("bad template argument kind");
359
0
  }
360
361
1.42M
  return LV;
362
1.42M
}
363
364
LinkageInfo
365
LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
366
1.33M
                                              LVComputationKind computation) {
367
1.33M
  return getLVForTemplateArgumentList(TArgs.asArray(), computation);
368
1.33M
}
369
370
static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
371
310k
                        const FunctionTemplateSpecializationInfo *specInfo) {
372
  // Include visibility from the template parameters and arguments
373
  // only if this is not an explicit instantiation or specialization
374
  // with direct explicit visibility.  (Implicit instantiations won't
375
  // have a direct attribute.)
376
310k
  if (!specInfo->isExplicitInstantiationOrSpecialization())
377
301k
    return true;
378
379
8.66k
  return !fn->hasAttr<VisibilityAttr>();
380
310k
}
381
382
/// Merge in template-related linkage and visibility for the given
383
/// function template specialization.
384
///
385
/// We don't need a computation kind here because we can assume
386
/// LVForValue.
387
///
388
/// \param[out] LV the computation to use for the parent
389
void LinkageComputer::mergeTemplateLV(
390
    LinkageInfo &LV, const FunctionDecl *fn,
391
    const FunctionTemplateSpecializationInfo *specInfo,
392
310k
    LVComputationKind computation) {
393
310k
  bool considerVisibility =
394
310k
    shouldConsiderTemplateVisibility(fn, specInfo);
395
396
310k
  FunctionTemplateDecl *temp = specInfo->getTemplate();
397
398
  // Merge information from the template declaration.
399
310k
  LinkageInfo tempLV = getLVForDecl(temp, computation);
400
  // The linkage of the specialization should be consistent with the
401
  // template declaration.
402
310k
  LV.setLinkage(tempLV.getLinkage());
403
404
  // Merge information from the template parameters.
405
310k
  LinkageInfo paramsLV =
406
310k
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
407
310k
  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
408
409
  // Merge information from the template arguments.
410
310k
  const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
411
310k
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
412
310k
  LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
413
310k
}
414
415
/// Does the given declaration have a direct visibility attribute
416
/// that would match the given rules?
417
static bool hasDirectVisibilityAttribute(const NamedDecl *D,
418
84.2k
                                         LVComputationKind computation) {
419
84.2k
  if (computation.IgnoreAllVisibility)
420
2.06k
    return false;
421
422
82.1k
  return (computation.isTypeVisibility() && 
D->hasAttr<TypeVisibilityAttr>()70.0k
) ||
423
82.1k
         
D->hasAttr<VisibilityAttr>()22.8k
;
424
84.2k
}
425
426
/// Should we consider visibility associated with the template
427
/// arguments and parameters of the given class template specialization?
428
static bool shouldConsiderTemplateVisibility(
429
                                 const ClassTemplateSpecializationDecl *spec,
430
1.02M
                                 LVComputationKind computation) {
431
  // Include visibility from the template parameters and arguments
432
  // only if this is not an explicit instantiation or specialization
433
  // with direct explicit visibility (and note that implicit
434
  // instantiations won't have a direct attribute).
435
  //
436
  // Furthermore, we want to ignore template parameters and arguments
437
  // for an explicit specialization when computing the visibility of a
438
  // member thereof with explicit visibility.
439
  //
440
  // This is a bit complex; let's unpack it.
441
  //
442
  // An explicit class specialization is an independent, top-level
443
  // declaration.  As such, if it or any of its members has an
444
  // explicit visibility attribute, that must directly express the
445
  // user's intent, and we should honor it.  The same logic applies to
446
  // an explicit instantiation of a member of such a thing.
447
448
  // Fast path: if this is not an explicit instantiation or
449
  // specialization, we always want to consider template-related
450
  // visibility restrictions.
451
1.02M
  if (!spec->isExplicitInstantiationOrSpecialization())
452
878k
    return true;
453
454
  // This is the 'member thereof' check.
455
142k
  if (spec->isExplicitSpecialization() &&
456
142k
      
hasExplicitVisibilityAlready(computation)133k
)
457
59.3k
    return false;
458
459
83.2k
  return !hasDirectVisibilityAttribute(spec, computation);
460
142k
}
461
462
/// Merge in template-related linkage and visibility for the given
463
/// class template specialization.
464
void LinkageComputer::mergeTemplateLV(
465
    LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
466
1.02M
    LVComputationKind computation) {
467
1.02M
  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
468
469
  // Merge information from the template parameters, but ignore
470
  // visibility if we're only considering template arguments.
471
472
1.02M
  ClassTemplateDecl *temp = spec->getSpecializedTemplate();
473
1.02M
  LinkageInfo tempLV =
474
1.02M
    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
475
1.02M
  LV.mergeMaybeWithVisibility(tempLV,
476
1.02M
           considerVisibility && 
!hasExplicitVisibilityAlready(computation)889k
);
477
478
  // Merge information from the template arguments.  We ignore
479
  // template-argument visibility if we've got an explicit
480
  // instantiation with a visibility attribute.
481
1.02M
  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
482
1.02M
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
483
1.02M
  if (considerVisibility)
484
889k
    LV.mergeVisibility(argsLV);
485
1.02M
  LV.mergeExternalVisibility(argsLV);
486
1.02M
}
487
488
/// Should we consider visibility associated with the template
489
/// arguments and parameters of the given variable template
490
/// specialization? As usual, follow class template specialization
491
/// logic up to initialization.
492
static bool shouldConsiderTemplateVisibility(
493
                                 const VarTemplateSpecializationDecl *spec,
494
5.56k
                                 LVComputationKind computation) {
495
  // Include visibility from the template parameters and arguments
496
  // only if this is not an explicit instantiation or specialization
497
  // with direct explicit visibility (and note that implicit
498
  // instantiations won't have a direct attribute).
499
5.56k
  if (!spec->isExplicitInstantiationOrSpecialization())
500
3.82k
    return true;
501
502
  // An explicit variable specialization is an independent, top-level
503
  // declaration.  As such, if it has an explicit visibility attribute,
504
  // that must directly express the user's intent, and we should honor
505
  // it.
506
1.74k
  if (spec->isExplicitSpecialization() &&
507
1.74k
      
hasExplicitVisibilityAlready(computation)1.09k
)
508
830
    return false;
509
510
913
  return !hasDirectVisibilityAttribute(spec, computation);
511
1.74k
}
512
513
/// Merge in template-related linkage and visibility for the given
514
/// variable template specialization. As usual, follow class template
515
/// specialization logic up to initialization.
516
void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
517
                                      const VarTemplateSpecializationDecl *spec,
518
5.56k
                                      LVComputationKind computation) {
519
5.56k
  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
520
521
  // Merge information from the template parameters, but ignore
522
  // visibility if we're only considering template arguments.
523
524
5.56k
  VarTemplateDecl *temp = spec->getSpecializedTemplate();
525
5.56k
  LinkageInfo tempLV =
526
5.56k
    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
527
5.56k
  LV.mergeMaybeWithVisibility(tempLV,
528
5.56k
           considerVisibility && 
!hasExplicitVisibilityAlready(computation)4.73k
);
529
530
  // Merge information from the template arguments.  We ignore
531
  // template-argument visibility if we've got an explicit
532
  // instantiation with a visibility attribute.
533
5.56k
  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
534
5.56k
  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
535
5.56k
  if (considerVisibility)
536
4.73k
    LV.mergeVisibility(argsLV);
537
5.56k
  LV.mergeExternalVisibility(argsLV);
538
5.56k
}
539
540
1.35M
static bool useInlineVisibilityHidden(const NamedDecl *D) {
541
  // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
542
1.35M
  const LangOptions &Opts = D->getASTContext().getLangOpts();
543
1.35M
  if (!Opts.CPlusPlus || 
!Opts.InlineVisibilityHidden1.03M
)
544
1.35M
    return false;
545
546
365
  const auto *FD = dyn_cast<FunctionDecl>(D);
547
365
  if (!FD)
548
100
    return false;
549
550
265
  TemplateSpecializationKind TSK = TSK_Undeclared;
551
265
  if (FunctionTemplateSpecializationInfo *spec
552
265
      = FD->getTemplateSpecializationInfo()) {
553
16
    TSK = spec->getTemplateSpecializationKind();
554
249
  } else if (MemberSpecializationInfo *MSI =
555
249
             FD->getMemberSpecializationInfo()) {
556
28
    TSK = MSI->getTemplateSpecializationKind();
557
28
  }
558
559
265
  const FunctionDecl *Def = nullptr;
560
  // InlineVisibilityHidden only applies to definitions, and
561
  // isInlined() only gives meaningful answers on definitions
562
  // anyway.
563
265
  return TSK != TSK_ExplicitInstantiationDeclaration &&
564
265
    
TSK != TSK_ExplicitInstantiationDefinition261
&&
565
265
    
FD->hasBody(Def)253
&&
Def->isInlined()239
&&
!Def->hasAttr<GNUInlineAttr>()151
;
566
365
}
567
568
8.94M
template <typename T> static bool isFirstInExternCContext(T *D) {
569
8.94M
  const T *First = D->getFirstDecl();
570
8.94M
  return First->isInExternCContext();
571
8.94M
}
Decl.cpp:bool isFirstInExternCContext<clang::VarDecl const>(clang::VarDecl const*)
Line
Count
Source
568
576k
template <typename T> static bool isFirstInExternCContext(T *D) {
569
576k
  const T *First = D->getFirstDecl();
570
576k
  return First->isInExternCContext();
571
576k
}
Decl.cpp:bool isFirstInExternCContext<clang::FunctionDecl const>(clang::FunctionDecl const*)
Line
Count
Source
568
8.37M
template <typename T> static bool isFirstInExternCContext(T *D) {
569
8.37M
  const T *First = D->getFirstDecl();
570
8.37M
  return First->isInExternCContext();
571
8.37M
}
572
573
15.5M
static bool isSingleLineLanguageLinkage(const Decl &D) {
574
15.5M
  if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
575
168k
    if (!SD->hasBraces())
576
166k
      return true;
577
15.3M
  return false;
578
15.5M
}
579
580
/// Determine whether D is declared in the purview of a named module.
581
28.2M
static bool isInModulePurview(const NamedDecl *D) {
582
28.2M
  if (auto *M = D->getOwningModule())
583
690k
    return M->isModulePurview();
584
27.5M
  return false;
585
28.2M
}
586
587
134k
static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
588
  // FIXME: Handle isModulePrivate.
589
134k
  switch (D->getModuleOwnershipKind()) {
590
120k
  case Decl::ModuleOwnershipKind::Unowned:
591
121k
  case Decl::ModuleOwnershipKind::ReachableWhenImported:
592
121k
  case Decl::ModuleOwnershipKind::ModulePrivate:
593
121k
    return false;
594
13.0k
  case Decl::ModuleOwnershipKind::Visible:
595
13.5k
  case Decl::ModuleOwnershipKind::VisibleWhenImported:
596
13.5k
    return isInModulePurview(D);
597
134k
  }
598
0
  llvm_unreachable("unexpected module ownership kind");
599
0
}
600
601
20.3M
static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
602
  // (for the modules ts) Internal linkage declarations within a module
603
  // interface unit are modeled as "module-internal linkage", which means that
604
  // they have internal linkage formally but can be indirectly accessed from
605
  // outside the module via inline functions and templates defined within the
606
  // module.
607
20.3M
  if (isInModulePurview(D) && 
D->getASTContext().getLangOpts().ModulesTS158
)
608
73
    return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
609
610
20.3M
  return LinkageInfo::internal();
611
20.3M
}
612
613
7.85M
static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
614
  // C++ Modules TS [basic.link]/6.8:
615
  //   - A name declared at namespace scope that does not have internal linkage
616
  //     by the previous rules and that is introduced by a non-exported
617
  //     declaration has module linkage.
618
  //
619
  // [basic.namespace.general]/p2
620
  //   A namespace is never attached to a named module and never has a name with
621
  //   module linkage.
622
7.85M
  if (isInModulePurview(D) &&
623
7.85M
      !isExportedFromModuleInterfaceUnit(
624
894
          cast<NamedDecl>(D->getCanonicalDecl())) &&
625
7.85M
      
!isa<NamespaceDecl>(D)449
)
626
437
    return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
627
628
7.85M
  return LinkageInfo::external();
629
7.85M
}
630
631
28.1M
static StorageClass getStorageClass(const Decl *D) {
632
28.1M
  if (auto *TD = dyn_cast<TemplateDecl>(D))
633
303k
    D = TD->getTemplatedDecl();
634
28.1M
  if (D) {
635
28.1M
    if (auto *VD = dyn_cast<VarDecl>(D))
636
1.14M
      return VD->getStorageClass();
637
27.0M
    if (auto *FD = dyn_cast<FunctionDecl>(D))
638
25.4M
      return FD->getStorageClass();
639
27.0M
  }
640
1.63M
  return SC_None;
641
28.1M
}
642
643
LinkageInfo
644
LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
645
                                            LVComputationKind computation,
646
28.1M
                                            bool IgnoreVarTypeLinkage) {
647
28.1M
  assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
648
28.1M
         "Not a name having namespace scope");
649
0
  ASTContext &Context = D->getASTContext();
650
651
  // C++ [basic.link]p3:
652
  //   A name having namespace scope (3.3.6) has internal linkage if it
653
  //   is the name of
654
655
28.1M
  if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
656
    // - a variable, variable template, function, or function template
657
    //   that is explicitly declared static; or
658
    // (This bullet corresponds to C99 6.2.2p3.)
659
20.3M
    return getInternalLinkageFor(D);
660
20.3M
  }
661
662
7.87M
  if (const auto *Var = dyn_cast<VarDecl>(D)) {
663
    // - a non-template variable of non-volatile const-qualified type, unless
664
    //   - it is explicitly declared extern, or
665
    //   - it is inline or exported, or
666
    //   - it was previously declared and the prior declaration did not have
667
    //     internal linkage
668
    // (There is no equivalent in C99.)
669
1.10M
    if (Context.getLangOpts().CPlusPlus &&
670
1.10M
        
Var->getType().isConstQualified()258k
&&
671
1.10M
        
!Var->getType().isVolatileQualified()139k
&&
672
1.10M
        
!Var->isInline()139k
&&
673
1.10M
        
!isExportedFromModuleInterfaceUnit(Var)134k
&&
674
1.10M
        
!isa<VarTemplateSpecializationDecl>(Var)134k
&&
675
1.10M
        
!Var->getDescribedVarTemplate()133k
) {
676
133k
      const VarDecl *PrevVar = Var->getPreviousDecl();
677
133k
      if (PrevVar)
678
155
        return getLVForDecl(PrevVar, computation);
679
680
133k
      if (Var->getStorageClass() != SC_Extern &&
681
133k
          
Var->getStorageClass() != SC_PrivateExtern56.5k
&&
682
133k
          
!isSingleLineLanguageLinkage(*Var)56.5k
)
683
14.7k
        return getInternalLinkageFor(Var);
684
133k
    }
685
686
1.09M
    
for (const VarDecl *PrevVar = Var->getPreviousDecl(); 1.08M
PrevVar;
687
1.08M
         
PrevVar = PrevVar->getPreviousDecl()4.83k
) {
688
4.85k
      if (PrevVar->getStorageClass() == SC_PrivateExtern &&
689
4.85k
          
Var->getStorageClass() == SC_None22
)
690
19
        return getDeclLinkageAndVisibility(PrevVar);
691
      // Explicitly declared static.
692
4.83k
      if (PrevVar->getStorageClass() == SC_Static)
693
0
        return getInternalLinkageFor(Var);
694
4.83k
    }
695
6.77M
  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
696
    //   - a data member of an anonymous union.
697
6
    const VarDecl *VD = IFD->getVarDecl();
698
6
    assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
699
0
    return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
700
6
  }
701
7.85M
  assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
702
703
  // FIXME: This gives internal linkage to names that should have no linkage
704
  // (those not covered by [basic.link]p6).
705
7.85M
  if (D->isInAnonymousNamespace()) {
706
3.36k
    const auto *Var = dyn_cast<VarDecl>(D);
707
3.36k
    const auto *Func = dyn_cast<FunctionDecl>(D);
708
    // FIXME: The check for extern "C" here is not justified by the standard
709
    // wording, but we retain it from the pre-DR1113 model to avoid breaking
710
    // code.
711
    //
712
    // C++11 [basic.link]p4:
713
    //   An unnamed namespace or a namespace declared directly or indirectly
714
    //   within an unnamed namespace has internal linkage.
715
3.36k
    if ((!Var || 
!isFirstInExternCContext(Var)834
) &&
716
3.36k
        
(3.34k
!Func3.34k
||
!isFirstInExternCContext(Func)962
))
717
3.31k
      return getInternalLinkageFor(D);
718
3.36k
  }
719
720
  // Set up the defaults.
721
722
  // C99 6.2.2p5:
723
  //   If the declaration of an identifier for an object has file
724
  //   scope and no storage-class specifier, its linkage is
725
  //   external.
726
7.85M
  LinkageInfo LV = getExternalLinkageFor(D);
727
728
7.85M
  if (!hasExplicitVisibilityAlready(computation)) {
729
1.61M
    if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
730
565k
      LV.mergeVisibility(*Vis, true);
731
1.05M
    } else {
732
      // If we're declared in a namespace with a visibility attribute,
733
      // use that namespace's visibility, and it still counts as explicit.
734
1.05M
      for (const DeclContext *DC = D->getDeclContext();
735
1.49M
           !isa<TranslationUnitDecl>(DC);
736
1.05M
           
DC = DC->getParent()443k
) {
737
443k
        const auto *ND = dyn_cast<NamespaceDecl>(DC);
738
443k
        if (!ND) 
continue55.0k
;
739
388k
        if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
740
97
          LV.mergeVisibility(*Vis, true);
741
97
          break;
742
97
        }
743
388k
      }
744
1.05M
    }
745
746
    // Add in global settings if the above didn't give us direct visibility.
747
1.61M
    if (!LV.isVisibilityExplicit()) {
748
      // Use global type/value visibility as appropriate.
749
1.05M
      Visibility globalVisibility =
750
1.05M
          computation.isValueVisibility()
751
1.05M
              ? 
Context.getLangOpts().getValueVisibilityMode()877k
752
1.05M
              : 
Context.getLangOpts().getTypeVisibilityMode()176k
;
753
1.05M
      LV.mergeVisibility(globalVisibility, /*explicit*/ false);
754
755
      // If we're paying attention to global visibility, apply
756
      // -finline-visibility-hidden if this is an inline method.
757
1.05M
      if (useInlineVisibilityHidden(D))
758
42
        LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
759
1.05M
    }
760
1.61M
  }
761
762
  // C++ [basic.link]p4:
763
764
  //   A name having namespace scope that has not been given internal linkage
765
  //   above and that is the name of
766
  //   [...bullets...]
767
  //   has its linkage determined as follows:
768
  //     - if the enclosing namespace has internal linkage, the name has
769
  //       internal linkage; [handled above]
770
  //     - otherwise, if the declaration of the name is attached to a named
771
  //       module and is not exported, the name has module linkage;
772
  //     - otherwise, the name has external linkage.
773
  // LV is currently set up to handle the last two bullets.
774
  //
775
  //   The bullets are:
776
777
  //     - a variable; or
778
7.85M
  if (const auto *Var = dyn_cast<VarDecl>(D)) {
779
    // GCC applies the following optimization to variables and static
780
    // data members, but not to functions:
781
    //
782
    // Modify the variable's LV by the LV of its type unless this is
783
    // C or extern "C".  This follows from [basic.link]p9:
784
    //   A type without linkage shall not be used as the type of a
785
    //   variable or function with external linkage unless
786
    //    - the entity has C language linkage, or
787
    //    - the entity is declared within an unnamed namespace, or
788
    //    - the entity is not used or is defined in the same
789
    //      translation unit.
790
    // and [basic.link]p10:
791
    //   ...the types specified by all declarations referring to a
792
    //   given variable or function shall be identical...
793
    // C does not have an equivalent rule.
794
    //
795
    // Ignore this if we've got an explicit attribute;  the user
796
    // probably knows what they're doing.
797
    //
798
    // Note that we don't want to make the variable non-external
799
    // because of this, but unique-external linkage suits us.
800
801
1.08M
    if (Context.getLangOpts().CPlusPlus && 
!isFirstInExternCContext(Var)242k
&&
802
1.08M
        
!IgnoreVarTypeLinkage115k
) {
803
115k
      LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
804
115k
      if (!isExternallyVisible(TypeLV.getLinkage()))
805
1.12k
        return LinkageInfo::uniqueExternal();
806
114k
      if (!LV.isVisibilityExplicit())
807
114k
        LV.mergeVisibility(TypeLV);
808
114k
    }
809
810
1.08M
    if (Var->getStorageClass() == SC_PrivateExtern)
811
73
      LV.mergeVisibility(HiddenVisibility, true);
812
813
    // Note that Sema::MergeVarDecl already takes care of implementing
814
    // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
815
    // to do it here.
816
817
    // As per function and class template specializations (below),
818
    // consider LV for the template and template arguments.  We're at file
819
    // scope, so we do not need to worry about nested specializations.
820
1.08M
    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
821
4.49k
      mergeTemplateLV(LV, spec, computation);
822
4.49k
    }
823
824
  //     - a function; or
825
6.76M
  } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
826
    // In theory, we can modify the function's LV by the LV of its
827
    // type unless it has C linkage (see comment above about variables
828
    // for justification).  In practice, GCC doesn't do this, so it's
829
    // just too painful to make work.
830
831
4.87M
    if (Function->getStorageClass() == SC_PrivateExtern)
832
40
      LV.mergeVisibility(HiddenVisibility, true);
833
834
    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
835
    // merging storage classes and visibility attributes, so we don't have to
836
    // look at previous decls in here.
837
838
    // In C++, then if the type of the function uses a type with
839
    // unique-external linkage, it's not legally usable from outside
840
    // this translation unit.  However, we should use the C linkage
841
    // rules instead for extern "C" declarations.
842
4.87M
    if (Context.getLangOpts().CPlusPlus && 
!isFirstInExternCContext(Function)2.26M
) {
843
      // Only look at the type-as-written. Otherwise, deducing the return type
844
      // of a function could change its linkage.
845
1.31M
      QualType TypeAsWritten = Function->getType();
846
1.31M
      if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
847
1.31M
        TypeAsWritten = TSI->getType();
848
1.31M
      if (!isExternallyVisible(TypeAsWritten->getLinkage()))
849
1.85k
        return LinkageInfo::uniqueExternal();
850
1.31M
    }
851
852
    // Consider LV from the template and the template arguments.
853
    // We're at file scope, so we do not need to worry about nested
854
    // specializations.
855
4.87M
    if (FunctionTemplateSpecializationInfo *specInfo
856
4.87M
                               = Function->getTemplateSpecializationInfo()) {
857
215k
      mergeTemplateLV(LV, Function, specInfo, computation);
858
215k
    }
859
860
  //     - a named class (Clause 9), or an unnamed class defined in a
861
  //       typedef declaration in which the class has the typedef name
862
  //       for linkage purposes (7.1.3); or
863
  //     - a named enumeration (7.2), or an unnamed enumeration
864
  //       defined in a typedef declaration in which the enumeration
865
  //       has the typedef name for linkage purposes (7.1.3); or
866
4.87M
  } else 
if (const auto *1.89M
Tag1.89M
= dyn_cast<TagDecl>(D)) {
867
    // Unnamed tags have no linkage.
868
1.51M
    if (!Tag->hasNameForLinkage())
869
4.63k
      return LinkageInfo::none();
870
871
    // If this is a class template specialization, consider the
872
    // linkage of the template and template arguments.  We're at file
873
    // scope, so we do not need to worry about nested specializations.
874
1.51M
    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
875
1.01M
      mergeTemplateLV(LV, spec, computation);
876
1.01M
    }
877
878
  // FIXME: This is not part of the C++ standard any more.
879
  //     - an enumerator belonging to an enumeration with external linkage; or
880
1.51M
  } else 
if (371k
isa<EnumConstantDecl>(D)371k
) {
881
0
    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
882
0
                                      computation);
883
0
    if (!isExternalFormalLinkage(EnumLV.getLinkage()))
884
0
      return LinkageInfo::none();
885
0
    LV.merge(EnumLV);
886
887
  //     - a template
888
371k
  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
889
303k
    bool considerVisibility = !hasExplicitVisibilityAlready(computation);
890
303k
    LinkageInfo tempLV =
891
303k
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
892
303k
    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
893
894
  //     An unnamed namespace or a namespace declared directly or indirectly
895
  //     within an unnamed namespace has internal linkage. All other namespaces
896
  //     have external linkage.
897
  //
898
  // We handled names in anonymous namespaces above.
899
303k
  } else 
if (68.2k
isa<NamespaceDecl>(D)68.2k
) {
900
63.0k
    return LV;
901
902
  // By extension, we assign external linkage to Objective-C
903
  // interfaces.
904
63.0k
  } else 
if (5.22k
isa<ObjCInterfaceDecl>(D)5.22k
) {
905
    // fallout
906
907
5.05k
  } else 
if (auto *172
TD172
= dyn_cast<TypedefNameDecl>(D)) {
908
    // A typedef declaration has linkage if it gives a type a name for
909
    // linkage purposes.
910
46
    if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
911
0
      return LinkageInfo::none();
912
913
126
  } else if (isa<MSGuidDecl>(D)) {
914
    // A GUID behaves like an inline variable with external linkage. Fall
915
    // through.
916
917
  // Everything not covered here has no linkage.
918
121
  } else {
919
5
    return LinkageInfo::none();
920
5
  }
921
922
  // If we ended up with non-externally-visible linkage, visibility should
923
  // always be default.
924
7.78M
  if (!isExternallyVisible(LV.getLinkage()))
925
8.54k
    return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
926
927
7.77M
  return LV;
928
7.78M
}
929
930
LinkageInfo
931
LinkageComputer::getLVForClassMember(const NamedDecl *D,
932
                                     LVComputationKind computation,
933
2.07M
                                     bool IgnoreVarTypeLinkage) {
934
  // Only certain class members have linkage.  Note that fields don't
935
  // really have linkage, but it's convenient to say they do for the
936
  // purposes of calculating linkage of pointer-to-data-member
937
  // template arguments.
938
  //
939
  // Templates also don't officially have linkage, but since we ignore
940
  // the C++ standard and look at template arguments when determining
941
  // linkage and visibility of a template specialization, we might hit
942
  // a template template argument that way. If we do, we need to
943
  // consider its linkage.
944
2.07M
  if (!(isa<CXXMethodDecl>(D) ||
945
2.07M
        
isa<VarDecl>(D)420k
||
946
2.07M
        
isa<FieldDecl>(D)275k
||
947
2.07M
        
isa<IndirectFieldDecl>(D)270k
||
948
2.07M
        
isa<TagDecl>(D)270k
||
949
2.07M
        
isa<TemplateDecl>(D)223k
))
950
56
    return LinkageInfo::none();
951
952
2.07M
  LinkageInfo LV;
953
954
  // If we have an explicit visibility attribute, merge that in.
955
2.07M
  if (!hasExplicitVisibilityAlready(computation)) {
956
475k
    if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
957
177k
      LV.mergeVisibility(*Vis, true);
958
    // If we're paying attention to global visibility, apply
959
    // -finline-visibility-hidden if this is an inline method.
960
    //
961
    // Note that we do this before merging information about
962
    // the class visibility.
963
475k
    if (!LV.isVisibilityExplicit() && 
useInlineVisibilityHidden(D)298k
)
964
71
      LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
965
475k
  }
966
967
  // If this class member has an explicit visibility attribute, the only
968
  // thing that can change its visibility is the template arguments, so
969
  // only look for them when processing the class.
970
2.07M
  LVComputationKind classComputation = computation;
971
2.07M
  if (LV.isVisibilityExplicit())
972
177k
    classComputation = withExplicitVisibilityAlready(computation);
973
974
2.07M
  LinkageInfo classLV =
975
2.07M
    getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
976
  // The member has the same linkage as the class. If that's not externally
977
  // visible, we don't need to compute anything about the linkage.
978
  // FIXME: If we're only computing linkage, can we bail out here?
979
2.07M
  if (!isExternallyVisible(classLV.getLinkage()))
980
16.0k
    return classLV;
981
982
983
  // Otherwise, don't merge in classLV yet, because in certain cases
984
  // we need to completely ignore the visibility from it.
985
986
  // Specifically, if this decl exists and has an explicit attribute.
987
2.05M
  const NamedDecl *explicitSpecSuppressor = nullptr;
988
989
2.05M
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
990
    // Only look at the type-as-written. Otherwise, deducing the return type
991
    // of a function could change its linkage.
992
1.63M
    QualType TypeAsWritten = MD->getType();
993
1.63M
    if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
994
1.56M
      TypeAsWritten = TSI->getType();
995
1.63M
    if (!isExternallyVisible(TypeAsWritten->getLinkage()))
996
250
      return LinkageInfo::uniqueExternal();
997
998
    // If this is a method template specialization, use the linkage for
999
    // the template parameters and arguments.
1000
1.63M
    if (FunctionTemplateSpecializationInfo *spec
1001
1.63M
           = MD->getTemplateSpecializationInfo()) {
1002
94.5k
      mergeTemplateLV(LV, MD, spec, computation);
1003
94.5k
      if (spec->isExplicitSpecialization()) {
1004
1.92k
        explicitSpecSuppressor = MD;
1005
92.6k
      } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
1006
55
        explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
1007
55
      }
1008
1.54M
    } else if (isExplicitMemberSpecialization(MD)) {
1009
2.15k
      explicitSpecSuppressor = MD;
1010
2.15k
    }
1011
1012
1.63M
  } else 
if (const auto *418k
RD418k
= dyn_cast<CXXRecordDecl>(D)) {
1013
46.1k
    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1014
3.58k
      mergeTemplateLV(LV, spec, computation);
1015
3.58k
      if (spec->isExplicitSpecialization()) {
1016
83
        explicitSpecSuppressor = spec;
1017
3.50k
      } else {
1018
3.50k
        const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1019
3.50k
        if (isExplicitMemberSpecialization(temp)) {
1020
47
          explicitSpecSuppressor = temp->getTemplatedDecl();
1021
47
        }
1022
3.50k
      }
1023
42.5k
    } else if (isExplicitMemberSpecialization(RD)) {
1024
73
      explicitSpecSuppressor = RD;
1025
73
    }
1026
1027
  // Static data members.
1028
372k
  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1029
144k
    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1030
1.07k
      mergeTemplateLV(LV, spec, computation);
1031
1032
    // Modify the variable's linkage by its type, but ignore the
1033
    // type's visibility unless it's a definition.
1034
144k
    if (!IgnoreVarTypeLinkage) {
1035
144k
      LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1036
      // FIXME: If the type's linkage is not externally visible, we can
1037
      // give this static data member UniqueExternalLinkage.
1038
144k
      if (!LV.isVisibilityExplicit() && 
!classLV.isVisibilityExplicit()144k
)
1039
137k
        LV.mergeVisibility(typeLV);
1040
144k
      LV.mergeExternalVisibility(typeLV);
1041
144k
    }
1042
1043
144k
    if (isExplicitMemberSpecialization(VD)) {
1044
159
      explicitSpecSuppressor = VD;
1045
159
    }
1046
1047
  // Template members.
1048
227k
  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1049
223k
    bool considerVisibility =
1050
223k
      (!LV.isVisibilityExplicit() &&
1051
223k
       
!classLV.isVisibilityExplicit()221k
&&
1052
223k
       
!hasExplicitVisibilityAlready(computation)173k
);
1053
223k
    LinkageInfo tempLV =
1054
223k
      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1055
223k
    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1056
1057
223k
    if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1058
223k
      if (isExplicitMemberSpecialization(redeclTemp)) {
1059
73
        explicitSpecSuppressor = temp->getTemplatedDecl();
1060
73
      }
1061
223k
    }
1062
223k
  }
1063
1064
  // We should never be looking for an attribute directly on a template.
1065
2.05M
  assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1066
1067
  // If this member is an explicit member specialization, and it has
1068
  // an explicit attribute, ignore visibility from the parent.
1069
0
  bool considerClassVisibility = true;
1070
2.05M
  if (explicitSpecSuppressor &&
1071
      // optimization: hasDVA() is true only with explicit visibility.
1072
2.05M
      
LV.isVisibilityExplicit()4.57k
&&
1073
2.05M
      
classLV.getVisibility() != DefaultVisibility1.67k
&&
1074
2.05M
      
hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)120
) {
1075
120
    considerClassVisibility = false;
1076
120
  }
1077
1078
  // Finally, merge in information from the class.
1079
2.05M
  LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1080
1081
2.05M
  return LV;
1082
2.05M
}
1083
1084
0
void NamedDecl::anchor() {}
1085
1086
11.0M
bool NamedDecl::isLinkageValid() const {
1087
11.0M
  if (!hasCachedLinkage())
1088
11.0M
    return true;
1089
1090
454
  Linkage L = LinkageComputer{}
1091
454
                  .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1092
454
                  .getLinkage();
1093
454
  return L == getCachedLinkage();
1094
11.0M
}
1095
1096
ReservedIdentifierStatus
1097
47.3M
NamedDecl::isReserved(const LangOptions &LangOpts) const {
1098
47.3M
  const IdentifierInfo *II = getIdentifier();
1099
1100
  // This triggers at least for CXXLiteralIdentifiers, which we already checked
1101
  // at lexing time.
1102
47.3M
  if (!II)
1103
976k
    return ReservedIdentifierStatus::NotReserved;
1104
1105
46.3M
  ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1106
46.3M
  if (isReservedAtGlobalScope(Status) && 
!isReservedInAllContexts(Status)13.7M
) {
1107
    // This name is only reserved at global scope. Check if this declaration
1108
    // conflicts with a global scope declaration.
1109
1.38M
    if (isa<ParmVarDecl>(this) || 
isTemplateParameter()1.33M
)
1110
46.9k
      return ReservedIdentifierStatus::NotReserved;
1111
1112
    // C++ [dcl.link]/7:
1113
    //   Two declarations [conflict] if [...] one declares a function or
1114
    //   variable with C language linkage, and the other declares [...] a
1115
    //   variable that belongs to the global scope.
1116
    //
1117
    // Therefore names that are reserved at global scope are also reserved as
1118
    // names of variables and functions with C language linkage.
1119
1.33M
    const DeclContext *DC = getDeclContext()->getRedeclContext();
1120
1.33M
    if (DC->isTranslationUnit())
1121
1.28M
      return Status;
1122
53.3k
    if (auto *VD = dyn_cast<VarDecl>(this))
1123
9.11k
      if (VD->isExternC())
1124
1
        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1125
53.3k
    if (auto *FD = dyn_cast<FunctionDecl>(this))
1126
10
      if (FD->isExternC())
1127
1
        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1128
53.3k
    return ReservedIdentifierStatus::NotReserved;
1129
53.3k
  }
1130
1131
44.9M
  return Status;
1132
46.3M
}
1133
1134
246k
ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1135
246k
  StringRef name = getName();
1136
246k
  if (name.empty()) 
return SFF_None0
;
1137
1138
246k
  if (name.front() == 'C')
1139
11.7k
    if (name == "CFStringCreateWithFormat" ||
1140
11.7k
        
name == "CFStringCreateWithFormatAndArguments"11.7k
||
1141
11.7k
        
name == "CFStringAppendFormat"11.7k
||
1142
11.7k
        
name == "CFStringAppendFormatAndArguments"11.7k
)
1143
24
      return SFF_CFString;
1144
246k
  return SFF_None;
1145
246k
}
1146
1147
128M
Linkage NamedDecl::getLinkageInternal() const {
1148
  // We don't care about visibility here, so ask for the cheapest
1149
  // possible visibility analysis.
1150
128M
  return LinkageComputer{}
1151
128M
      .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1152
128M
      .getLinkage();
1153
128M
}
1154
1155
1.15M
LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1156
1.15M
  return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1157
1.15M
}
1158
1159
static Optional<Visibility>
1160
getExplicitVisibilityAux(const NamedDecl *ND,
1161
                         NamedDecl::ExplicitVisibilityKind kind,
1162
2.48M
                         bool IsMostRecent) {
1163
2.48M
  assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1164
1165
  // Check the declaration itself first.
1166
2.48M
  if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1167
153k
    return V;
1168
1169
  // If this is a member class of a specialization of a class template
1170
  // and the corresponding decl has explicit visibility, use that.
1171
2.33M
  if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1172
747k
    CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1173
747k
    if (InstantiatedFrom)
1174
11.3k
      return getVisibilityOf(InstantiatedFrom, kind);
1175
747k
  }
1176
1177
  // If there wasn't explicit visibility there, and this is a
1178
  // specialization of a class template, check for visibility
1179
  // on the pattern.
1180
2.32M
  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1181
    // Walk all the template decl till this point to see if there are
1182
    // explicit visibility attributes.
1183
551k
    const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1184
820k
    while (TD != nullptr) {
1185
614k
      auto Vis = getVisibilityOf(TD, kind);
1186
614k
      if (Vis != None)
1187
344k
        return Vis;
1188
269k
      TD = TD->getPreviousDecl();
1189
269k
    }
1190
206k
    return None;
1191
551k
  }
1192
1193
  // Use the most recent declaration.
1194
1.77M
  if (!IsMostRecent && 
!isa<NamespaceDecl>(ND)1.76M
) {
1195
1.37M
    const NamedDecl *MostRecent = ND->getMostRecentDecl();
1196
1.37M
    if (MostRecent != ND)
1197
5.70k
      return getExplicitVisibilityAux(MostRecent, kind, true);
1198
1.37M
  }
1199
1200
1.76M
  if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1201
69.2k
    if (Var->isStaticDataMember()) {
1202
2.81k
      VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1203
2.81k
      if (InstantiatedFrom)
1204
989
        return getVisibilityOf(InstantiatedFrom, kind);
1205
2.81k
    }
1206
1207
68.2k
    if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1208
1.07k
      return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1209
1.07k
                             kind);
1210
1211
67.1k
    return None;
1212
68.2k
  }
1213
  // Also handle function template specializations.
1214
1.69M
  if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1215
    // If the function is a specialization of a template with an
1216
    // explicit visibility attribute, use that.
1217
1.00M
    if (FunctionTemplateSpecializationInfo *templateInfo
1218
1.00M
          = fn->getTemplateSpecializationInfo())
1219
111k
      return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1220
111k
                             kind);
1221
1222
    // If the function is a member of a specialization of a class template
1223
    // and the corresponding decl has explicit visibility, use that.
1224
897k
    FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1225
897k
    if (InstantiatedFrom)
1226
229k
      return getVisibilityOf(InstantiatedFrom, kind);
1227
1228
667k
    return None;
1229
897k
  }
1230
1231
  // The visibility of a template is stored in the templated decl.
1232
690k
  if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1233
110k
    return getVisibilityOf(TD->getTemplatedDecl(), kind);
1234
1235
579k
  return None;
1236
690k
}
1237
1238
Optional<Visibility>
1239
2.48M
NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1240
2.48M
  return getExplicitVisibilityAux(this, kind, false);
1241
2.48M
}
1242
1243
LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1244
                                             Decl *ContextDecl,
1245
5.13k
                                             LVComputationKind computation) {
1246
  // This lambda has its linkage/visibility determined by its owner.
1247
5.13k
  const NamedDecl *Owner;
1248
5.13k
  if (!ContextDecl)
1249
4.68k
    Owner = dyn_cast<NamedDecl>(DC);
1250
451
  else if (isa<ParmVarDecl>(ContextDecl))
1251
187
    Owner =
1252
187
        dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1253
264
  else
1254
264
    Owner = cast<NamedDecl>(ContextDecl);
1255
1256
5.13k
  if (!Owner)
1257
1.73k
    return LinkageInfo::none();
1258
1259
  // If the owner has a deduced type, we need to skip querying the linkage and
1260
  // visibility of that type, because it might involve this closure type.  The
1261
  // only effect of this is that we might give a lambda VisibleNoLinkage rather
1262
  // than NoLinkage when we don't strictly need to, which is benign.
1263
3.39k
  auto *VD = dyn_cast<VarDecl>(Owner);
1264
3.39k
  LinkageInfo OwnerLV =
1265
3.39k
      VD && 
VD->getType()->getContainedDeducedType()179
1266
3.39k
          ? 
computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)121
1267
3.39k
          : 
getLVForDecl(Owner, computation)3.27k
;
1268
1269
  // A lambda never formally has linkage. But if the owner is externally
1270
  // visible, then the lambda is too. We apply the same rules to blocks.
1271
3.39k
  if (!isExternallyVisible(OwnerLV.getLinkage()))
1272
337
    return LinkageInfo::none();
1273
3.05k
  return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1274
3.05k
                     OwnerLV.isVisibilityExplicit());
1275
3.39k
}
1276
1277
LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1278
849k
                                               LVComputationKind computation) {
1279
849k
  if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1280
105
    if (Function->isInAnonymousNamespace() &&
1281
105
        
!isFirstInExternCContext(Function)0
)
1282
0
      return getInternalLinkageFor(Function);
1283
1284
    // This is a "void f();" which got merged with a file static.
1285
105
    if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1286
0
      return getInternalLinkageFor(Function);
1287
1288
105
    LinkageInfo LV;
1289
105
    if (!hasExplicitVisibilityAlready(computation)) {
1290
0
      if (Optional<Visibility> Vis =
1291
0
              getExplicitVisibility(Function, computation))
1292
0
        LV.mergeVisibility(*Vis, true);
1293
0
    }
1294
1295
    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1296
    // merging storage classes and visibility attributes, so we don't have to
1297
    // look at previous decls in here.
1298
1299
105
    return LV;
1300
105
  }
1301
1302
849k
  if (const auto *Var = dyn_cast<VarDecl>(D)) {
1303
844k
    if (Var->hasExternalStorage()) {
1304
78
      if (Var->isInAnonymousNamespace() && 
!isFirstInExternCContext(Var)0
)
1305
0
        return getInternalLinkageFor(Var);
1306
1307
78
      LinkageInfo LV;
1308
78
      if (Var->getStorageClass() == SC_PrivateExtern)
1309
24
        LV.mergeVisibility(HiddenVisibility, true);
1310
54
      else if (!hasExplicitVisibilityAlready(computation)) {
1311
0
        if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1312
0
          LV.mergeVisibility(*Vis, true);
1313
0
      }
1314
1315
78
      if (const VarDecl *Prev = Var->getPreviousDecl()) {
1316
23
        LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1317
23
        if (PrevLV.getLinkage())
1318
23
          LV.setLinkage(PrevLV.getLinkage());
1319
23
        LV.mergeVisibility(PrevLV);
1320
23
      }
1321
1322
78
      return LV;
1323
78
    }
1324
1325
844k
    if (!Var->isStaticLocal())
1326
830k
      return LinkageInfo::none();
1327
844k
  }
1328
1329
19.5k
  ASTContext &Context = D->getASTContext();
1330
19.5k
  if (!Context.getLangOpts().CPlusPlus)
1331
1.46k
    return LinkageInfo::none();
1332
1333
18.0k
  const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1334
18.0k
  if (!OuterD || 
OuterD->isInvalidDecl()17.9k
)
1335
114
    return LinkageInfo::none();
1336
1337
17.9k
  LinkageInfo LV;
1338
17.9k
  if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1339
41
    if (!BD->getBlockManglingNumber())
1340
9
      return LinkageInfo::none();
1341
1342
32
    LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1343
32
                         BD->getBlockManglingContextDecl(), computation);
1344
17.9k
  } else {
1345
17.9k
    const auto *FD = cast<FunctionDecl>(OuterD);
1346
17.9k
    if (!FD->isInlined() &&
1347
17.9k
        
!isTemplateInstantiation(FD->getTemplateSpecializationKind())16.5k
)
1348
16.2k
      return LinkageInfo::none();
1349
1350
    // If a function is hidden by -fvisibility-inlines-hidden option and
1351
    // is not explicitly attributed as a hidden function,
1352
    // we should not make static local variables in the function hidden.
1353
1.68k
    LV = getLVForDecl(FD, computation);
1354
1.68k
    if (isa<VarDecl>(D) && 
useInlineVisibilityHidden(FD)771
&&
1355
1.68k
        
!LV.isVisibilityExplicit()34
&&
1356
1.68k
        
!Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar27
) {
1357
18
      assert(cast<VarDecl>(D)->isStaticLocal());
1358
      // If this was an implicitly hidden inline method, check again for
1359
      // explicit visibility on the parent class, and use that for static locals
1360
      // if present.
1361
18
      if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1362
6
        LV = getLVForDecl(MD->getParent(), computation);
1363
18
      if (!LV.isVisibilityExplicit()) {
1364
15
        Visibility globalVisibility =
1365
15
            computation.isValueVisibility()
1366
15
                ? Context.getLangOpts().getValueVisibilityMode()
1367
15
                : 
Context.getLangOpts().getTypeVisibilityMode()0
;
1368
15
        return LinkageInfo(VisibleNoLinkage, globalVisibility,
1369
15
                           /*visibilityExplicit=*/false);
1370
15
      }
1371
18
    }
1372
1.68k
  }
1373
1.70k
  if (!isExternallyVisible(LV.getLinkage()))
1374
258
    return LinkageInfo::none();
1375
1.44k
  return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1376
1.44k
                     LV.isVisibilityExplicit());
1377
1.70k
}
1378
1379
LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1380
                                              LVComputationKind computation,
1381
32.6M
                                              bool IgnoreVarTypeLinkage) {
1382
  // Internal_linkage attribute overrides other considerations.
1383
32.6M
  if (D->hasAttr<InternalLinkageAttr>())
1384
0
    return getInternalLinkageFor(D);
1385
1386
  // Objective-C: treat all Objective-C declarations as having external
1387
  // linkage.
1388
32.6M
  switch (D->getKind()) {
1389
30.5M
    default:
1390
30.5M
      break;
1391
1392
    // Per C++ [basic.link]p2, only the names of objects, references,
1393
    // functions, types, templates, namespaces, and values ever have linkage.
1394
    //
1395
    // Note that the name of a typedef, namespace alias, using declaration,
1396
    // and so on are not the name of the corresponding type, namespace, or
1397
    // declaration, so they do *not* have linkage.
1398
30.5M
    case Decl::ImplicitParam:
1399
224k
    case Decl::Label:
1400
224k
    case Decl::NamespaceAlias:
1401
1.49M
    case Decl::ParmVar:
1402
1.49M
    case Decl::Using:
1403
1.49M
    case Decl::UsingEnum:
1404
1.49M
    case Decl::UsingShadow:
1405
1.49M
    case Decl::UsingDirective:
1406
1.49M
      return LinkageInfo::none();
1407
1408
15
    case Decl::EnumConstant:
1409
      // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1410
15
      if (D->getASTContext().getLangOpts().CPlusPlus)
1411
14
        return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1412
1
      return LinkageInfo::visible_none();
1413
1414
20.3k
    case Decl::Typedef:
1415
22.3k
    case Decl::TypeAlias:
1416
      // A typedef declaration has linkage if it gives a type a name for
1417
      // linkage purposes.
1418
22.3k
      if (!cast<TypedefNameDecl>(D)
1419
22.3k
               ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1420
22.2k
        return LinkageInfo::none();
1421
46
      break;
1422
1423
46
    case Decl::TemplateTemplateParm: // count these as external
1424
2
    case Decl::NonTypeTemplateParm:
1425
2
    case Decl::ObjCAtDefsField:
1426
2
    case Decl::ObjCCategory:
1427
2
    case Decl::ObjCCategoryImpl:
1428
2
    case Decl::ObjCCompatibleAlias:
1429
2
    case Decl::ObjCImplementation:
1430
2.54k
    case Decl::ObjCMethod:
1431
2.54k
    case Decl::ObjCProperty:
1432
2.54k
    case Decl::ObjCPropertyImpl:
1433
2.55k
    case Decl::ObjCProtocol:
1434
2.55k
      return getExternalLinkageFor(D);
1435
1436
547k
    case Decl::CXXRecord: {
1437
547k
      const auto *Record = cast<CXXRecordDecl>(D);
1438
547k
      if (Record->isLambda()) {
1439
12.0k
        if (Record->hasKnownLambdaInternalLinkage() ||
1440
12.0k
            
!Record->getLambdaManglingNumber()11.7k
) {
1441
          // This lambda has no mangling number, so it's internal.
1442
6.97k
          return getInternalLinkageFor(D);
1443
6.97k
        }
1444
1445
5.10k
        return getLVForClosure(
1446
5.10k
                  Record->getDeclContext()->getRedeclContext(),
1447
5.10k
                  Record->getLambdaContextDecl(), computation);
1448
12.0k
      }
1449
1450
535k
      break;
1451
547k
    }
1452
1453
535k
    case Decl::TemplateParamObject: {
1454
      // The template parameter object can be referenced from anywhere its type
1455
      // and value can be referenced.
1456
786
      auto *TPO = cast<TemplateParamObjectDecl>(D);
1457
786
      LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1458
786
      LV.merge(getLVForValue(TPO->getValue(), computation));
1459
786
      return LV;
1460
547k
    }
1461
32.6M
  }
1462
1463
  // Handle linkage for namespace-scope names.
1464
31.1M
  if (D->getDeclContext()->getRedeclContext()->isFileContext())
1465
28.1M
    return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1466
1467
  // C++ [basic.link]p5:
1468
  //   In addition, a member function, static data member, a named
1469
  //   class or enumeration of class scope, or an unnamed class or
1470
  //   enumeration defined in a class-scope typedef declaration such
1471
  //   that the class or enumeration has the typedef name for linkage
1472
  //   purposes (7.1.3), has external linkage if the name of the class
1473
  //   has external linkage.
1474
2.92M
  if (D->getDeclContext()->isRecord())
1475
2.07M
    return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1476
1477
  // C++ [basic.link]p6:
1478
  //   The name of a function declared in block scope and the name of
1479
  //   an object declared by a block scope extern declaration have
1480
  //   linkage. If there is a visible declaration of an entity with
1481
  //   linkage having the same name and type, ignoring entities
1482
  //   declared outside the innermost enclosing namespace scope, the
1483
  //   block scope declaration declares that same entity and receives
1484
  //   the linkage of the previous declaration. If there is more than
1485
  //   one such matching entity, the program is ill-formed. Otherwise,
1486
  //   if no matching entity is found, the block scope entity receives
1487
  //   external linkage.
1488
850k
  if (D->getDeclContext()->isFunctionOrMethod())
1489
849k
    return getLVForLocalDecl(D, computation);
1490
1491
  // C++ [basic.link]p6:
1492
  //   Names not covered by these rules have no linkage.
1493
782
  return LinkageInfo::none();
1494
850k
}
1495
1496
/// getLVForDecl - Get the linkage and visibility for the given declaration.
1497
LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1498
133M
                                          LVComputationKind computation) {
1499
  // Internal_linkage attribute overrides other considerations.
1500
133M
  if (D->hasAttr<InternalLinkageAttr>())
1501
1.87k
    return getInternalLinkageFor(D);
1502
1503
133M
  if (computation.IgnoreAllVisibility && 
D->hasCachedLinkage()130M
)
1504
100M
    return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1505
1506
32.8M
  if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1507
245k
    return *LI;
1508
1509
32.6M
  LinkageInfo LV = computeLVForDecl(D, computation);
1510
32.6M
  if (D->hasCachedLinkage())
1511
2.33M
    assert(D->getCachedLinkage() == LV.getLinkage());
1512
1513
0
  D->setCachedLinkage(LV.getLinkage());
1514
32.6M
  cache(D, computation, LV);
1515
1516
32.6M
#ifndef NDEBUG
1517
  // In C (because of gnu inline) and in c++ with microsoft extensions an
1518
  // static can follow an extern, so we can have two decls with different
1519
  // linkages.
1520
32.6M
  const LangOptions &Opts = D->getASTContext().getLangOpts();
1521
32.6M
  if (!Opts.CPlusPlus || 
Opts.MicrosoftExt15.7M
)
1522
16.9M
    return LV;
1523
1524
  // We have just computed the linkage for this decl. By induction we know
1525
  // that all other computed linkages match, check that the one we just
1526
  // computed also does.
1527
15.6M
  NamedDecl *Old = nullptr;
1528
17.8M
  for (auto I : D->redecls()) {
1529
17.8M
    auto *T = cast<NamedDecl>(I);
1530
17.8M
    if (T == D)
1531
15.6M
      continue;
1532
2.16M
    if (!T->isInvalidDecl() && 
T->hasCachedLinkage()2.16M
) {
1533
314k
      Old = T;
1534
314k
      break;
1535
314k
    }
1536
2.16M
  }
1537
15.6M
  assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1538
0
#endif
1539
1540
0
  return LV;
1541
32.6M
}
1542
1543
1.99M
LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1544
1.99M
  NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1545
1.99M
                                             ? 
NamedDecl::VisibilityForType843k
1546
1.99M
                                             : 
NamedDecl::VisibilityForValue1.14M
;
1547
1.99M
  LVComputationKind CK(EK);
1548
1.99M
  return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1549
1.99M
                             ? 
CK.forLinkageOnly()85
1550
1.99M
                             : 
CK1.99M
);
1551
1.99M
}
1552
1553
40.4M
Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1554
40.4M
  if (isa<NamespaceDecl>(this))
1555
    // Namespaces never have module linkage.  It is the entities within them
1556
    // that [may] do.
1557
2.47M
    return nullptr;
1558
1559
37.9M
  Module *M = getOwningModule();
1560
37.9M
  if (!M)
1561
36.4M
    return nullptr;
1562
1563
1.46M
  switch (M->Kind) {
1564
1.46M
  case Module::ModuleMapModule:
1565
    // Module map modules have no special linkage semantics.
1566
1.46M
    return nullptr;
1567
1568
927
  case Module::ModuleInterfaceUnit:
1569
962
  case Module::ModulePartitionInterface:
1570
994
  case Module::ModulePartitionImplementation:
1571
994
    return M;
1572
1573
19
  case Module::ModuleHeaderUnit:
1574
418
  case Module::GlobalModuleFragment: {
1575
    // External linkage declarations in the global module have no owning module
1576
    // for linkage purposes. But internal linkage declarations in the global
1577
    // module fragment of a particular module are owned by that module for
1578
    // linkage purposes.
1579
    // FIXME: p1815 removes the need for this distinction -- there are no
1580
    // internal linkage declarations that need to be referred to from outside
1581
    // this TU.
1582
418
    if (IgnoreLinkage)
1583
332
      return nullptr;
1584
86
    bool InternalLinkage;
1585
86
    if (auto *ND = dyn_cast<NamedDecl>(this))
1586
86
      InternalLinkage = !ND->hasExternalFormalLinkage();
1587
0
    else
1588
0
      InternalLinkage = isInAnonymousNamespace();
1589
86
    return InternalLinkage ? 
M->Kind == Module::ModuleHeaderUnit6
?
M0
:
M->Parent6
1590
86
                           : 
nullptr80
;
1591
418
  }
1592
1593
14
  case Module::PrivateModuleFragment:
1594
    // The private module fragment is part of its containing module for linkage
1595
    // purposes.
1596
14
    return M->Parent;
1597
1.46M
  }
1598
1599
0
  llvm_unreachable("unknown module kind");
1600
0
}
1601
1602
2.71M
void NamedDecl::printName(raw_ostream &os) const {
1603
2.71M
  os << Name;
1604
2.71M
}
1605
1606
20.3k
std::string NamedDecl::getQualifiedNameAsString() const {
1607
20.3k
  std::string QualName;
1608
20.3k
  llvm::raw_string_ostream OS(QualName);
1609
20.3k
  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1610
20.3k
  return QualName;
1611
20.3k
}
1612
1613
21.6k
void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1614
21.6k
  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1615
21.6k
}
1616
1617
void NamedDecl::printQualifiedName(raw_ostream &OS,
1618
514k
                                   const PrintingPolicy &P) const {
1619
514k
  if (getDeclContext()->isFunctionOrMethod()) {
1620
    // We do not print '(anonymous)' for function parameters without name.
1621
35.3k
    printName(OS);
1622
35.3k
    return;
1623
35.3k
  }
1624
478k
  printNestedNameSpecifier(OS, P);
1625
478k
  if (getDeclName())
1626
477k
    OS << *this;
1627
1.27k
  else {
1628
    // Give the printName override a chance to pick a different name before we
1629
    // fall back to "(anonymous)".
1630
1.27k
    SmallString<64> NameBuffer;
1631
1.27k
    llvm::raw_svector_ostream NameOS(NameBuffer);
1632
1.27k
    printName(NameOS);
1633
1.27k
    if (NameBuffer.empty())
1634
1.27k
      OS << "(anonymous)";
1635
5
    else
1636
5
      OS << NameBuffer;
1637
1.27k
  }
1638
478k
}
1639
1640
2
void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1641
2
  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1642
2
}
1643
1644
void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1645
478k
                                         const PrintingPolicy &P) const {
1646
478k
  const DeclContext *Ctx = getDeclContext();
1647
1648
  // For ObjC methods and properties, look through categories and use the
1649
  // interface as context.
1650
478k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1651
1.08k
    if (auto *ID = MD->getClassInterface())
1652
1.07k
      Ctx = ID;
1653
477k
  } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1654
29
    if (auto *MD = PD->getGetterMethodDecl())
1655
29
      if (auto *ID = MD->getClassInterface())
1656
29
        Ctx = ID;
1657
477k
  } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1658
110
    if (auto *CI = ID->getContainingInterface())
1659
110
      Ctx = CI;
1660
110
  }
1661
1662
478k
  if (Ctx->isFunctionOrMethod())
1663
0
    return;
1664
1665
478k
  using ContextsTy = SmallVector<const DeclContext *, 8>;
1666
478k
  ContextsTy Contexts;
1667
1668
  // Collect named contexts.
1669
478k
  DeclarationName NameInScope = getDeclName();
1670
1.54M
  for (; Ctx; 
Ctx = Ctx->getParent()1.06M
) {
1671
    // Suppress anonymous namespace if requested.
1672
1.06M
    if (P.SuppressUnwrittenScope && 
isa<NamespaceDecl>(Ctx)127k
&&
1673
1.06M
        
cast<NamespaceDecl>(Ctx)->isAnonymousNamespace()23.0k
)
1674
115
      continue;
1675
1676
    // Suppress inline namespace if it doesn't make the result ambiguous.
1677
1.06M
    if (P.SuppressInlineNamespace && 
Ctx->isInlineNamespace()192k
&&
NameInScope645
&&
1678
1.06M
        
cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope)644
)
1679
609
      continue;
1680
1681
    // Skip non-named contexts such as linkage specifications and ExportDecls.
1682
1.06M
    const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1683
1.06M
    if (!ND)
1684
481k
      continue;
1685
1686
581k
    Contexts.push_back(Ctx);
1687
581k
    NameInScope = ND->getDeclName();
1688
581k
  }
1689
1690
581k
  for (const DeclContext *DC : llvm::reverse(Contexts)) {
1691
581k
    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1692
118k
      OS << Spec->getName();
1693
118k
      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1694
118k
      printTemplateArgumentList(
1695
118k
          OS, TemplateArgs.asArray(), P,
1696
118k
          Spec->getSpecializedTemplate()->getTemplateParameters());
1697
462k
    } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1698
384k
      if (ND->isAnonymousNamespace()) {
1699
1.31k
        OS << (P.MSVCFormatting ? 
"`anonymous namespace\'"0
1700
1.31k
                                : "(anonymous namespace)");
1701
1.31k
      }
1702
382k
      else
1703
382k
        OS << *ND;
1704
384k
    } else 
if (const auto *78.1k
RD78.1k
= dyn_cast<RecordDecl>(DC)) {
1705
73.8k
      if (!RD->getIdentifier())
1706
1.26k
        OS << "(anonymous " << RD->getKindName() << ')';
1707
72.5k
      else
1708
72.5k
        OS << *RD;
1709
73.8k
    } else 
if (const auto *4.27k
FD4.27k
= dyn_cast<FunctionDecl>(DC)) {
1710
1.19k
      const FunctionProtoType *FT = nullptr;
1711
1.19k
      if (FD->hasWrittenPrototype())
1712
1.19k
        FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1713
1714
1.19k
      OS << *FD << '(';
1715
1.19k
      if (FT) {
1716
1.19k
        unsigned NumParams = FD->getNumParams();
1717
1.61k
        for (unsigned i = 0; i < NumParams; 
++i426
) {
1718
426
          if (i)
1719
39
            OS << ", ";
1720
426
          OS << FD->getParamDecl(i)->getType().stream(P);
1721
426
        }
1722
1723
1.19k
        if (FT->isVariadic()) {
1724
0
          if (NumParams > 0)
1725
0
            OS << ", ";
1726
0
          OS << "...";
1727
0
        }
1728
1.19k
      }
1729
1.19k
      OS << ')';
1730
3.08k
    } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1731
      // C++ [dcl.enum]p10: Each enum-name and each unscoped
1732
      // enumerator is declared in the scope that immediately contains
1733
      // the enum-specifier. Each scoped enumerator is declared in the
1734
      // scope of the enumeration.
1735
      // For the case of unscoped enumerator, do not include in the qualified
1736
      // name any information about its enum enclosing scope, as its visibility
1737
      // is global.
1738
1.86k
      if (ED->isScoped())
1739
1.11k
        OS << *ED;
1740
751
      else
1741
751
        continue;
1742
1.86k
    } else {
1743
1.21k
      OS << *cast<NamedDecl>(DC);
1744
1.21k
    }
1745
580k
    OS << "::";
1746
580k
  }
1747
478k
}
1748
1749
void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1750
                                     const PrintingPolicy &Policy,
1751
883k
                                     bool Qualified) const {
1752
883k
  if (Qualified)
1753
10.3k
    printQualifiedName(OS, Policy);
1754
873k
  else
1755
873k
    printName(OS);
1756
883k
}
1757
1758
85.2M
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
85.2M
  return true;
1760
85.2M
}
Decl.cpp:bool isRedeclarableImpl<clang::NamespaceDecl>(clang::Redeclarable<clang::NamespaceDecl>*)
Line
Count
Source
1758
608k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
608k
  return true;
1760
608k
}
Decl.cpp:bool isRedeclarableImpl<clang::NamespaceAliasDecl>(clang::Redeclarable<clang::NamespaceAliasDecl>*)
Line
Count
Source
1758
23
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
23
  return true;
1760
23
}
Decl.cpp:bool isRedeclarableImpl<clang::ObjCInterfaceDecl>(clang::Redeclarable<clang::ObjCInterfaceDecl>*)
Line
Count
Source
1758
141k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
141k
  return true;
1760
141k
}
Decl.cpp:bool isRedeclarableImpl<clang::ObjCProtocolDecl>(clang::Redeclarable<clang::ObjCProtocolDecl>*)
Line
Count
Source
1758
5.67k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
5.67k
  return true;
1760
5.67k
}
Decl.cpp:bool isRedeclarableImpl<clang::RedeclarableTemplateDecl>(clang::Redeclarable<clang::RedeclarableTemplateDecl>*)
Line
Count
Source
1758
4.28M
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
4.28M
  return true;
1760
4.28M
}
Decl.cpp:bool isRedeclarableImpl<clang::TagDecl>(clang::Redeclarable<clang::TagDecl>*)
Line
Count
Source
1758
103k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
103k
  return true;
1760
103k
}
Decl.cpp:bool isRedeclarableImpl<clang::TypedefNameDecl>(clang::Redeclarable<clang::TypedefNameDecl>*)
Line
Count
Source
1758
14.7k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
14.7k
  return true;
1760
14.7k
}
Decl.cpp:bool isRedeclarableImpl<clang::UsingShadowDecl>(clang::Redeclarable<clang::UsingShadowDecl>*)
Line
Count
Source
1758
904k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
904k
  return true;
1760
904k
}
Decl.cpp:bool isRedeclarableImpl<clang::FunctionDecl>(clang::Redeclarable<clang::FunctionDecl>*)
Line
Count
Source
1758
79.1M
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
79.1M
  return true;
1760
79.1M
}
Decl.cpp:bool isRedeclarableImpl<clang::VarDecl>(clang::Redeclarable<clang::VarDecl>*)
Line
Count
Source
1758
70.8k
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1759
70.8k
  return true;
1760
70.8k
}
Unexecuted instantiation: Decl.cpp:bool isRedeclarableImpl<clang::TranslationUnitDecl>(clang::Redeclarable<clang::TranslationUnitDecl>*)
1761
1.65k
static bool isRedeclarableImpl(...) { return false; }
1762
85.2M
static bool isRedeclarable(Decl::Kind K) {
1763
85.2M
  switch (K) {
1764
0
#define DECL(Type, Base) \
1765
85.2M
  case Decl::Type: \
1766
85.2M
    return isRedeclarableImpl((Type##Decl *)nullptr);
1767
0
#define ABSTRACT_DECL(DECL)
1768
85.2M
#include 
"clang/AST/DeclNodes.inc"0
1769
85.2M
  }
1770
0
  llvm_unreachable("unknown decl kind");
1771
0
}
1772
1773
89.0M
bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1774
89.0M
  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1775
1776
  // Never replace one imported declaration with another; we need both results
1777
  // when re-exporting.
1778
89.0M
  if (OldD->isFromASTFile() && 
isFromASTFile()119k
)
1779
27.7k
    return false;
1780
1781
  // A kind mismatch implies that the declaration is not replaced.
1782
89.0M
  if (OldD->getKind() != getKind())
1783
3.76M
    return false;
1784
1785
  // For method declarations, we never replace. (Why?)
1786
85.2M
  if (isa<ObjCMethodDecl>(this))
1787
7.18k
    return false;
1788
1789
  // For parameters, pick the newer one. This is either an error or (in
1790
  // Objective-C) permitted as an extension.
1791
85.2M
  if (isa<ParmVarDecl>(this))
1792
1
    return true;
1793
1794
  // Inline namespaces can give us two declarations with the same
1795
  // name and kind in the same scope but different contexts; we should
1796
  // keep both declarations in this case.
1797
85.2M
  if (!this->getDeclContext()->getRedeclContext()->Equals(
1798
85.2M
          OldD->getDeclContext()->getRedeclContext()))
1799
10.1k
    return false;
1800
1801
  // Using declarations can be replaced if they import the same name from the
1802
  // same context.
1803
85.2M
  if (auto *UD = dyn_cast<UsingDecl>(this)) {
1804
9.58k
    ASTContext &Context = getASTContext();
1805
9.58k
    return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1806
9.58k
           Context.getCanonicalNestedNameSpecifier(
1807
9.58k
               cast<UsingDecl>(OldD)->getQualifier());
1808
9.58k
  }
1809
85.2M
  if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1810
18
    ASTContext &Context = getASTContext();
1811
18
    return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1812
18
           Context.getCanonicalNestedNameSpecifier(
1813
18
                        cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1814
18
  }
1815
1816
85.2M
  if (isRedeclarable(getKind())) {
1817
85.2M
    if (getCanonicalDecl() != OldD->getCanonicalDecl())
1818
83.8M
      return false;
1819
1820
1.43M
    if (IsKnownNewer)
1821
1.42M
      return true;
1822
1823
    // Check whether this is actually newer than OldD. We want to keep the
1824
    // newer declaration. This loop will usually only iterate once, because
1825
    // OldD is usually the previous declaration.
1826
20.3k
    
for (auto D : redecls())13.9k
{
1827
20.3k
      if (D == OldD)
1828
13.2k
        break;
1829
1830
      // If we reach the canonical declaration, then OldD is not actually older
1831
      // than this one.
1832
      //
1833
      // FIXME: In this case, we should not add this decl to the lookup table.
1834
7.16k
      if (D->isCanonicalDecl())
1835
773
        return false;
1836
7.16k
    }
1837
1838
    // It's a newer declaration of the same kind of declaration in the same
1839
    // scope: we want this decl instead of the existing one.
1840
13.2k
    return true;
1841
13.9k
  }
1842
1843
  // In all other cases, we need to keep both declarations in case they have
1844
  // different visibility. Any attempt to use the name will result in an
1845
  // ambiguity if more than one is visible.
1846
1.65k
  return false;
1847
85.2M
}
1848
1849
1.88M
bool NamedDecl::hasLinkage() const {
1850
1.88M
  return getFormalLinkage() != NoLinkage;
1851
1.88M
}
1852
1853
2.05M
NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1854
2.05M
  NamedDecl *ND = this;
1855
2.05M
  if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1856
2.04M
    ND = UD->getTargetDecl();
1857
1858
2.05M
  if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1859
441
    return AD->getClassInterface();
1860
1861
2.04M
  if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1862
1.68k
    return AD->getNamespace();
1863
1864
2.04M
  return ND;
1865
2.04M
}
1866
1867
7.99M
bool NamedDecl::isCXXInstanceMember() const {
1868
7.99M
  if (!isCXXClassMember())
1869
1.60M
    return false;
1870
1871
6.39M
  const NamedDecl *D = this;
1872
6.39M
  if (isa<UsingShadowDecl>(D))
1873
101
    D = cast<UsingShadowDecl>(D)->getTargetDecl();
1874
1875
6.39M
  if (isa<FieldDecl>(D) || 
isa<IndirectFieldDecl>(D)5.22M
||
isa<MSPropertyDecl>(D)5.22M
)
1876
1.17M
    return true;
1877
5.22M
  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1878
3.62M
    return MD->isInstance();
1879
1.60M
  return false;
1880
5.22M
}
1881
1882
//===----------------------------------------------------------------------===//
1883
// DeclaratorDecl Implementation
1884
//===----------------------------------------------------------------------===//
1885
1886
template <typename DeclT>
1887
9.48M
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1888
9.48M
  if (decl->getNumTemplateParameterLists() > 0)
1889
203k
    return decl->getTemplateParameterList(0)->getTemplateLoc();
1890
9.28M
  return decl->getInnerLocStart();
1891
9.48M
}
Decl.cpp:clang::SourceLocation getTemplateOrInnerLocStart<clang::DeclaratorDecl>(clang::DeclaratorDecl const*)
Line
Count
Source
1887
9.05M
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1888
9.05M
  if (decl->getNumTemplateParameterLists() > 0)
1889
203k
    return decl->getTemplateParameterList(0)->getTemplateLoc();
1890
8.84M
  return decl->getInnerLocStart();
1891
9.05M
}
Decl.cpp:clang::SourceLocation getTemplateOrInnerLocStart<clang::TagDecl>(clang::TagDecl const*)
Line
Count
Source
1887
433k
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1888
433k
  if (decl->getNumTemplateParameterLists() > 0)
1889
10
    return decl->getTemplateParameterList(0)->getTemplateLoc();
1890
433k
  return decl->getInnerLocStart();
1891
433k
}
1892
1893
2.49M
SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1894
2.49M
  TypeSourceInfo *TSI = getTypeSourceInfo();
1895
2.49M
  if (TSI) return TSI->getTypeLoc().getBeginLoc();
1896
0
  return SourceLocation();
1897
2.49M
}
1898
1899
167
SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1900
167
  TypeSourceInfo *TSI = getTypeSourceInfo();
1901
167
  if (TSI) return TSI->getTypeLoc().getEndLoc();
1902
0
  return SourceLocation();
1903
167
}
1904
1905
1.65M
void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1906
1.65M
  if (QualifierLoc) {
1907
    // Make sure the extended decl info is allocated.
1908
387k
    if (!hasExtInfo()) {
1909
      // Save (non-extended) type source info pointer.
1910
387k
      auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1911
      // Allocate external info struct.
1912
387k
      DeclInfo = new (getASTContext()) ExtInfo;
1913
      // Restore savedTInfo into (extended) decl info.
1914
387k
      getExtInfo()->TInfo = savedTInfo;
1915
387k
    }
1916
    // Set qualifier info.
1917
387k
    getExtInfo()->QualifierLoc = QualifierLoc;
1918
1.26M
  } else if (hasExtInfo()) {
1919
    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1920
0
    getExtInfo()->QualifierLoc = QualifierLoc;
1921
0
  }
1922
1.65M
}
1923
1924
1.01k
void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1925
1.01k
  assert(TrailingRequiresClause);
1926
  // Make sure the extended decl info is allocated.
1927
1.01k
  if (!hasExtInfo()) {
1928
    // Save (non-extended) type source info pointer.
1929
882
    auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1930
    // Allocate external info struct.
1931
882
    DeclInfo = new (getASTContext()) ExtInfo;
1932
    // Restore savedTInfo into (extended) decl info.
1933
882
    getExtInfo()->TInfo = savedTInfo;
1934
882
  }
1935
  // Set requires clause info.
1936
1.01k
  getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1937
1.01k
}
1938
1939
void DeclaratorDecl::setTemplateParameterListsInfo(
1940
250k
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1941
250k
  assert(!TPLists.empty());
1942
  // Make sure the extended decl info is allocated.
1943
250k
  if (!hasExtInfo()) {
1944
    // Save (non-extended) type source info pointer.
1945
1.79k
    auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1946
    // Allocate external info struct.
1947
1.79k
    DeclInfo = new (getASTContext()) ExtInfo;
1948
    // Restore savedTInfo into (extended) decl info.
1949
1.79k
    getExtInfo()->TInfo = savedTInfo;
1950
1.79k
  }
1951
  // Set the template parameter lists info.
1952
250k
  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1953
250k
}
1954
1955
9.05M
SourceLocation DeclaratorDecl::getOuterLocStart() const {
1956
9.05M
  return getTemplateOrInnerLocStart(this);
1957
9.05M
}
1958
1959
// Helper function: returns true if QT is or contains a type
1960
// having a postfix component.
1961
277k
static bool typeIsPostfix(QualType QT) {
1962
370k
  while (true) {
1963
370k
    const Type* T = QT.getTypePtr();
1964
370k
    switch (T->getTypeClass()) {
1965
274k
    default:
1966
274k
      return false;
1967
13.3k
    case Type::Pointer:
1968
13.3k
      QT = cast<PointerType>(T)->getPointeeType();
1969
13.3k
      break;
1970
39
    case Type::BlockPointer:
1971
39
      QT = cast<BlockPointerType>(T)->getPointeeType();
1972
39
      break;
1973
306
    case Type::MemberPointer:
1974
306
      QT = cast<MemberPointerType>(T)->getPointeeType();
1975
306
      break;
1976
55.8k
    case Type::LValueReference:
1977
75.4k
    case Type::RValueReference:
1978
75.4k
      QT = cast<ReferenceType>(T)->getPointeeType();
1979
75.4k
      break;
1980
3.56k
    case Type::PackExpansion:
1981
3.56k
      QT = cast<PackExpansionType>(T)->getPattern();
1982
3.56k
      break;
1983
1.00k
    case Type::Paren:
1984
2.22k
    case Type::ConstantArray:
1985
2.24k
    case Type::DependentSizedArray:
1986
2.62k
    case Type::IncompleteArray:
1987
2.63k
    case Type::VariableArray:
1988
2.67k
    case Type::FunctionProto:
1989
2.67k
    case Type::FunctionNoProto:
1990
2.67k
      return true;
1991
370k
    }
1992
370k
  }
1993
277k
}
1994
1995
294k
SourceRange DeclaratorDecl::getSourceRange() const {
1996
294k
  SourceLocation RangeEnd = getLocation();
1997
294k
  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1998
    // If the declaration has no name or the type extends past the name take the
1999
    // end location of the type.
2000
290k
    if (!getDeclName() || 
typeIsPostfix(TInfo->getType())270k
)
2001
21.5k
      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2002
290k
  }
2003
294k
  return SourceRange(getOuterLocStart(), RangeEnd);
2004
294k
}
2005
2006
void QualifierInfo::setTemplateParameterListsInfo(
2007
324k
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2008
  // Free previous template parameters (if any).
2009
324k
  if (NumTemplParamLists > 0) {
2010
0
    Context.Deallocate(TemplParamLists);
2011
0
    TemplParamLists = nullptr;
2012
0
    NumTemplParamLists = 0;
2013
0
  }
2014
  // Set info on matched template parameter lists (if any).
2015
324k
  if (!TPLists.empty()) {
2016
324k
    TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2017
324k
    NumTemplParamLists = TPLists.size();
2018
324k
    std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2019
324k
  }
2020
324k
}
2021
2022
//===----------------------------------------------------------------------===//
2023
// VarDecl Implementation
2024
//===----------------------------------------------------------------------===//
2025
2026
2.82k
const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
2027
2.82k
  switch (SC) {
2028
0
  case SC_None:                 break;
2029
1
  case SC_Auto:                 return "auto";
2030
962
  case SC_Extern:               return "extern";
2031
0
  case SC_PrivateExtern:        return "__private_extern__";
2032
0
  case SC_Register:             return "register";
2033
1.85k
  case SC_Static:               return "static";
2034
2.82k
  }
2035
2036
0
  llvm_unreachable("Invalid storage class");
2037
0
}
2038
2039
VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2040
                 SourceLocation StartLoc, SourceLocation IdLoc,
2041
                 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2042
                 StorageClass SC)
2043
    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2044
84.0M
      redeclarable_base(C) {
2045
84.0M
  static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2046
84.0M
                "VarDeclBitfields too large!");
2047
84.0M
  static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2048
84.0M
                "ParmVarDeclBitfields too large!");
2049
84.0M
  static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2050
84.0M
                "NonParmVarDeclBitfields too large!");
2051
84.0M
  AllBits = 0;
2052
84.0M
  VarDeclBits.SClass = SC;
2053
  // Everything else is implicitly initialized to false.
2054
84.0M
}
2055
2056
VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,
2057
                         SourceLocation IdL, const IdentifierInfo *Id,
2058
4.34M
                         QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2059
4.34M
  return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2060
4.34M
}
2061
2062
365k
VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2063
365k
  return new (C, ID)
2064
365k
      VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2065
365k
              QualType(), nullptr, SC_None);
2066
365k
}
2067
2068
71.9k
void VarDecl::setStorageClass(StorageClass SC) {
2069
71.9k
  assert(isLegalForVariable(SC));
2070
0
  VarDeclBits.SClass = SC;
2071
71.9k
}
2072
2073
7.20M
VarDecl::TLSKind VarDecl::getTLSKind() const {
2074
7.20M
  switch (VarDeclBits.TSCSpec) {
2075
7.19M
  case TSCS_unspecified:
2076
7.19M
    if (!hasAttr<ThreadAttr>() &&
2077
7.19M
        
!(7.19M
getASTContext().getLangOpts().OpenMPUseTLS7.19M
&&
2078
7.19M
          
getASTContext().getTargetInfo().isTLSSupported()2.75M
&&
2079
7.19M
          
hasAttr<OMPThreadPrivateDeclAttr>()2.67M
))
2080
7.19M
      return TLS_None;
2081
931
    return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2082
931
                LangOptions::MSVC2015)) ||
2083
931
            
hasAttr<OMPThreadPrivateDeclAttr>()906
)
2084
931
               ? 
TLS_Dynamic795
2085
931
               : 
TLS_Static136
;
2086
958
  case TSCS___thread: // Fall through.
2087
1.03k
  case TSCS__Thread_local:
2088
1.03k
    return TLS_Static;
2089
3.94k
  case TSCS_thread_local:
2090
3.94k
    return TLS_Dynamic;
2091
7.20M
  }
2092
0
  llvm_unreachable("Unknown thread storage class specifier!");
2093
0
}
2094
2095
91.9k
SourceRange VarDecl::getSourceRange() const {
2096
91.9k
  if (const Expr *Init = getInit()) {
2097
34.7k
    SourceLocation InitEnd = Init->getEndLoc();
2098
    // If Init is implicit, ignore its source range and fallback on
2099
    // DeclaratorDecl::getSourceRange() to handle postfix elements.
2100
34.7k
    if (InitEnd.isValid() && 
InitEnd != getLocation()34.7k
)
2101
33.6k
      return SourceRange(getOuterLocStart(), InitEnd);
2102
34.7k
  }
2103
58.2k
  return DeclaratorDecl::getSourceRange();
2104
91.9k
}
2105
2106
template<typename T>
2107
42.3M
static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2108
  // C++ [dcl.link]p1: All function types, function names with external linkage,
2109
  // and variable names with external linkage have a language linkage.
2110
42.3M
  if (!D.hasExternalFormalLinkage())
2111
30.2M
    return NoLanguageLinkage;
2112
2113
  // Language linkage is a C++ concept, but saying that everything else in C has
2114
  // C language linkage fits the implementation nicely.
2115
12.0M
  ASTContext &Context = D.getASTContext();
2116
12.0M
  if (!Context.getLangOpts().CPlusPlus)
2117
3.74M
    return CLanguageLinkage;
2118
2119
  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2120
  // language linkage of the names of class members and the function type of
2121
  // class member functions.
2122
8.33M
  const DeclContext *DC = D.getDeclContext();
2123
8.33M
  if (DC->isRecord())
2124
1.90M
    return CXXLanguageLinkage;
2125
2126
  // If the first decl is in an extern "C" context, any other redeclaration
2127
  // will have C language linkage. If the first one is not in an extern "C"
2128
  // context, we would have reported an error for any other decl being in one.
2129
6.43M
  if (isFirstInExternCContext(&D))
2130
3.27M
    return CLanguageLinkage;
2131
3.15M
  return CXXLanguageLinkage;
2132
6.43M
}
Decl.cpp:clang::LanguageLinkage getDeclLanguageLinkage<clang::VarDecl>(clang::VarDecl const&)
Line
Count
Source
2107
1.90M
static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2108
  // C++ [dcl.link]p1: All function types, function names with external linkage,
2109
  // and variable names with external linkage have a language linkage.
2110
1.90M
  if (!D.hasExternalFormalLinkage())
2111
746k
    return NoLanguageLinkage;
2112
2113
  // Language linkage is a C++ concept, but saying that everything else in C has
2114
  // C language linkage fits the implementation nicely.
2115
1.15M
  ASTContext &Context = D.getASTContext();
2116
1.15M
  if (!Context.getLangOpts().CPlusPlus)
2117
823k
    return CLanguageLinkage;
2118
2119
  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2120
  // language linkage of the names of class members and the function type of
2121
  // class member functions.
2122
332k
  const DeclContext *DC = D.getDeclContext();
2123
332k
  if (DC->isRecord())
2124
0
    return CXXLanguageLinkage;
2125
2126
  // If the first decl is in an extern "C" context, any other redeclaration
2127
  // will have C language linkage. If the first one is not in an extern "C"
2128
  // context, we would have reported an error for any other decl being in one.
2129
332k
  if (isFirstInExternCContext(&D))
2130
250k
    return CLanguageLinkage;
2131
82.0k
  return CXXLanguageLinkage;
2132
332k
}
Decl.cpp:clang::LanguageLinkage getDeclLanguageLinkage<clang::FunctionDecl>(clang::FunctionDecl const&)
Line
Count
Source
2107
40.4M
static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2108
  // C++ [dcl.link]p1: All function types, function names with external linkage,
2109
  // and variable names with external linkage have a language linkage.
2110
40.4M
  if (!D.hasExternalFormalLinkage())
2111
29.5M
    return NoLanguageLinkage;
2112
2113
  // Language linkage is a C++ concept, but saying that everything else in C has
2114
  // C language linkage fits the implementation nicely.
2115
10.9M
  ASTContext &Context = D.getASTContext();
2116
10.9M
  if (!Context.getLangOpts().CPlusPlus)
2117
2.92M
    return CLanguageLinkage;
2118
2119
  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2120
  // language linkage of the names of class members and the function type of
2121
  // class member functions.
2122
8.00M
  const DeclContext *DC = D.getDeclContext();
2123
8.00M
  if (DC->isRecord())
2124
1.90M
    return CXXLanguageLinkage;
2125
2126
  // If the first decl is in an extern "C" context, any other redeclaration
2127
  // will have C language linkage. If the first one is not in an extern "C"
2128
  // context, we would have reported an error for any other decl being in one.
2129
6.10M
  if (isFirstInExternCContext(&D))
2130
3.02M
    return CLanguageLinkage;
2131
3.07M
  return CXXLanguageLinkage;
2132
6.10M
}
2133
2134
template<typename T>
2135
40.2M
static bool isDeclExternC(const T &D) {
2136
  // Since the context is ignored for class members, they can only have C++
2137
  // language linkage or no language linkage.
2138
40.2M
  const DeclContext *DC = D.getDeclContext();
2139
40.2M
  if (DC->isRecord()) {
2140
3.85M
    assert(D.getASTContext().getLangOpts().CPlusPlus);
2141
0
    return false;
2142
3.85M
  }
2143
2144
36.3M
  return D.getLanguageLinkage() == CLanguageLinkage;
2145
40.2M
}
Decl.cpp:bool isDeclExternC<clang::VarDecl>(clang::VarDecl const&)
Line
Count
Source
2135
2.01M
static bool isDeclExternC(const T &D) {
2136
  // Since the context is ignored for class members, they can only have C++
2137
  // language linkage or no language linkage.
2138
2.01M
  const DeclContext *DC = D.getDeclContext();
2139
2.01M
  if (DC->isRecord()) {
2140
117k
    assert(D.getASTContext().getLangOpts().CPlusPlus);
2141
0
    return false;
2142
117k
  }
2143
2144
1.89M
  return D.getLanguageLinkage() == CLanguageLinkage;
2145
2.01M
}
Decl.cpp:bool isDeclExternC<clang::FunctionDecl>(clang::FunctionDecl const&)
Line
Count
Source
2135
38.2M
static bool isDeclExternC(const T &D) {
2136
  // Since the context is ignored for class members, they can only have C++
2137
  // language linkage or no language linkage.
2138
38.2M
  const DeclContext *DC = D.getDeclContext();
2139
38.2M
  if (DC->isRecord()) {
2140
3.73M
    assert(D.getASTContext().getLangOpts().CPlusPlus);
2141
0
    return false;
2142
3.73M
  }
2143
2144
34.4M
  return D.getLanguageLinkage() == CLanguageLinkage;
2145
38.2M
}
2146
2147
1.90M
LanguageLinkage VarDecl::getLanguageLinkage() const {
2148
1.90M
  return getDeclLanguageLinkage(*this);
2149
1.90M
}
2150
2151
2.01M
bool VarDecl::isExternC() const {
2152
2.01M
  return isDeclExternC(*this);
2153
2.01M
}
2154
2155
3.63M
bool VarDecl::isInExternCContext() const {
2156
3.63M
  return getLexicalDeclContext()->isExternCContext();
2157
3.63M
}
2158
2159
1.43k
bool VarDecl::isInExternCXXContext() const {
2160
1.43k
  return getLexicalDeclContext()->isExternCXXContext();
2161
1.43k
}
2162
2163
223M
VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2164
2165
VarDecl::DefinitionKind
2166
58.5M
VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2167
58.5M
  if (isThisDeclarationADemotedDefinition())
2168
157
    return DeclarationOnly;
2169
2170
  // C++ [basic.def]p2:
2171
  //   A declaration is a definition unless [...] it contains the 'extern'
2172
  //   specifier or a linkage-specification and neither an initializer [...],
2173
  //   it declares a non-inline static data member in a class declaration [...],
2174
  //   it declares a static data member outside a class definition and the variable
2175
  //   was defined within the class with the constexpr specifier [...],
2176
  // C++1y [temp.expl.spec]p15:
2177
  //   An explicit specialization of a static data member or an explicit
2178
  //   specialization of a static data member template is a definition if the
2179
  //   declaration includes an initializer; otherwise, it is a declaration.
2180
  //
2181
  // FIXME: How do you declare (but not define) a partial specialization of
2182
  // a static data member template outside the containing class?
2183
58.5M
  if (isStaticDataMember()) {
2184
23.3M
    if (isOutOfLine() &&
2185
23.3M
        
!(10.2M
getCanonicalDecl()->isInline()10.2M
&&
2186
10.2M
          
getCanonicalDecl()->isConstexpr()6.87k
) &&
2187
23.3M
        
(10.2M
hasInit()10.2M
||
2188
         // If the first declaration is out-of-line, this may be an
2189
         // instantiation of an out-of-line partial specialization of a variable
2190
         // template for which we have not yet instantiated the initializer.
2191
10.2M
         
(10.1M
getFirstDecl()->isOutOfLine()10.1M
2192
10.1M
              ? 
getTemplateSpecializationKind() == TSK_Undeclared61.5k
2193
10.1M
              : getTemplateSpecializationKind() !=
2194
10.0M
                    TSK_ExplicitSpecialization) ||
2195
10.2M
         
isa<VarTemplatePartialSpecializationDecl>(this)1.31k
))
2196
10.2M
      return Definition;
2197
13.0M
    if (!isOutOfLine() && 
isInline()13.0M
)
2198
694k
      return Definition;
2199
12.3M
    return DeclarationOnly;
2200
13.0M
  }
2201
  // C99 6.7p5:
2202
  //   A definition of an identifier is a declaration for that identifier that
2203
  //   [...] causes storage to be reserved for that object.
2204
  // Note: that applies for all non-file-scope objects.
2205
  // C99 6.9.2p1:
2206
  //   If the declaration of an identifier for an object has file scope and an
2207
  //   initializer, the declaration is an external definition for the identifier
2208
35.2M
  if (hasInit())
2209
16.9M
    return Definition;
2210
2211
18.2M
  if (hasDefiningAttr())
2212
487
    return Definition;
2213
2214
18.2M
  if (const auto *SAA = getAttr<SelectAnyAttr>())
2215
169
    if (!SAA->isInherited())
2216
154
      return Definition;
2217
2218
  // A variable template specialization (other than a static data member
2219
  // template or an explicit specialization) is a declaration until we
2220
  // instantiate its initializer.
2221
18.2M
  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2222
15.9k
    if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2223
15.9k
        
!isa<VarTemplatePartialSpecializationDecl>(VTSD)14.1k
&&
2224
15.9k
        
!VTSD->IsCompleteDefinition14.1k
)
2225
10.8k
      return DeclarationOnly;
2226
15.9k
  }
2227
2228
18.2M
  if (hasExternalStorage())
2229
2.82M
    return DeclarationOnly;
2230
2231
  // [dcl.link] p7:
2232
  //   A declaration directly contained in a linkage-specification is treated
2233
  //   as if it contains the extern specifier for the purpose of determining
2234
  //   the linkage of the declared name and whether it is a definition.
2235
15.4M
  if (isSingleLineLanguageLinkage(*this))
2236
124k
    return DeclarationOnly;
2237
2238
  // C99 6.9.2p2:
2239
  //   A declaration of an object that has file scope without an initializer,
2240
  //   and without a storage class specifier or the scs 'static', constitutes
2241
  //   a tentative definition.
2242
  // No such thing in C++.
2243
15.3M
  if (!C.getLangOpts().CPlusPlus && 
isFileVarDecl()6.90M
)
2244
130k
    return TentativeDefinition;
2245
2246
  // What's left is (in C, block-scope) declarations without initializers or
2247
  // external storage. These are definitions.
2248
15.1M
  return Definition;
2249
15.3M
}
2250
2251
11.4k
VarDecl *VarDecl::getActingDefinition() {
2252
11.4k
  DefinitionKind Kind = isThisDeclarationADefinition();
2253
11.4k
  if (Kind != TentativeDefinition)
2254
1.09k
    return nullptr;
2255
2256
10.3k
  VarDecl *LastTentative = nullptr;
2257
2258
  // Loop through the declaration chain, starting with the most recent.
2259
21.8k
  for (VarDecl *Decl = getMostRecentDecl(); Decl;
2260
11.4k
       
Decl = Decl->getPreviousDecl()11.4k
) {
2261
11.4k
    Kind = Decl->isThisDeclarationADefinition();
2262
11.4k
    if (Kind == Definition)
2263
43
      return nullptr;
2264
    // Record the first (most recent) TentativeDefinition that is encountered.
2265
11.4k
    if (Kind == TentativeDefinition && 
!LastTentative11.2k
)
2266
10.3k
      LastTentative = Decl;
2267
11.4k
  }
2268
2269
10.3k
  return LastTentative;
2270
10.3k
}
2271
2272
13.4M
VarDecl *VarDecl::getDefinition(ASTContext &C) {
2273
13.4M
  VarDecl *First = getFirstDecl();
2274
17.5M
  for (auto I : First->redecls()) {
2275
17.5M
    if (I->isThisDeclarationADefinition(C) == Definition)
2276
11.7M
      return I;
2277
17.5M
  }
2278
1.62M
  return nullptr;
2279
13.4M
}
2280
2281
9.07M
VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2282
9.07M
  DefinitionKind Kind = DeclarationOnly;
2283
2284
9.07M
  const VarDecl *First = getFirstDecl();
2285
9.16M
  for (auto I : First->redecls()) {
2286
9.16M
    Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2287
9.16M
    if (Kind == Definition)
2288
9.00M
      break;
2289
9.16M
  }
2290
2291
9.07M
  return Kind;
2292
9.07M
}
2293
2294
32.5M
const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2295
37.1M
  for (auto I : redecls()) {
2296
37.1M
    if (auto Expr = I->getInit()) {
2297
11.3M
      D = I;
2298
11.3M
      return Expr;
2299
11.3M
    }
2300
37.1M
  }
2301
21.1M
  return nullptr;
2302
32.5M
}
2303
2304
104M
bool VarDecl::hasInit() const {
2305
104M
  if (auto *P = dyn_cast<ParmVarDecl>(this))
2306
30.6M
    if (P->hasUnparsedDefaultArg() || 
P->hasUninstantiatedDefaultArg()30.6M
)
2307
28.4k
      return false;
2308
2309
104M
  return !Init.isNull();
2310
104M
}
2311
2312
51.6M
Expr *VarDecl::getInit() {
2313
51.6M
  if (!hasInit())
2314
32.2M
    return nullptr;
2315
2316
19.4M
  if (auto *S = Init.dyn_cast<Stmt *>())
2317
10.9M
    return cast<Expr>(S);
2318
2319
8.48M
  return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2320
19.4M
}
2321
2322
247k
Stmt **VarDecl::getInitAddress() {
2323
247k
  if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2324
7.22k
    return &ES->Value;
2325
2326
240k
  return Init.getAddrOfPtr1();
2327
247k
}
2328
2329
520
VarDecl *VarDecl::getInitializingDeclaration() {
2330
520
  VarDecl *Def = nullptr;
2331
520
  for (auto I : redecls()) {
2332
520
    if (I->hasInit())
2333
287
      return I;
2334
2335
233
    if (I->isThisDeclarationADefinition()) {
2336
30
      if (isStaticDataMember())
2337
0
        return I;
2338
30
      Def = I;
2339
30
    }
2340
233
  }
2341
233
  return Def;
2342
520
}
2343
2344
79.5M
bool VarDecl::isOutOfLine() const {
2345
79.5M
  if (Decl::isOutOfLine())
2346
10.4M
    return true;
2347
2348
69.0M
  if (!isStaticDataMember())
2349
5.63M
    return false;
2350
2351
  // If this static data member was instantiated from a static data member of
2352
  // a class template, check whether that static data member was defined
2353
  // out-of-line.
2354
63.4M
  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2355
26.5M
    return VD->isOutOfLine();
2356
2357
36.9M
  return false;
2358
63.4M
}
2359
2360
2.75M
void VarDecl::setInit(Expr *I) {
2361
2.75M
  if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2362
0
    Eval->~EvaluatedStmt();
2363
0
    getASTContext().Deallocate(Eval);
2364
0
  }
2365
2366
2.75M
  Init = I;
2367
2.75M
}
2368
2369
37.8M
bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2370
37.8M
  const LangOptions &Lang = C.getLangOpts();
2371
2372
  // OpenCL permits const integral variables to be used in constant
2373
  // expressions, like in C++98.
2374
37.8M
  if (!Lang.CPlusPlus && 
!Lang.OpenCL10.9M
)
2375
10.8M
    return false;
2376
2377
  // Function parameters are never usable in constant expressions.
2378
27.0M
  if (isa<ParmVarDecl>(this))
2379
7.83M
    return false;
2380
2381
  // The values of weak variables are never usable in constant expressions.
2382
19.1M
  if (isWeak())
2383
159
    return false;
2384
2385
  // In C++11, any variable of reference type can be used in a constant
2386
  // expression if it is initialized by a constant expression.
2387
19.1M
  if (Lang.CPlusPlus11 && 
getType()->isReferenceType()18.0M
)
2388
242k
    return true;
2389
2390
  // Only const objects can be used in constant expressions in C++. C++98 does
2391
  // not require the variable to be non-volatile, but we consider this to be a
2392
  // defect.
2393
18.9M
  if (!getType().isConstant(C) || 
getType().isVolatileQualified()7.49M
)
2394
11.4M
    return false;
2395
2396
  // In C++, const, non-volatile variables of integral or enumeration types
2397
  // can be used in constant expressions.
2398
7.49M
  if (getType()->isIntegralOrEnumerationType())
2399
7.24M
    return true;
2400
2401
  // Additionally, in C++11, non-volatile constexpr variables can be used in
2402
  // constant expressions.
2403
248k
  return Lang.CPlusPlus11 && 
isConstexpr()232k
;
2404
7.49M
}
2405
2406
26.4M
bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2407
  // C++2a [expr.const]p3:
2408
  //   A variable is usable in constant expressions after its initializing
2409
  //   declaration is encountered...
2410
26.4M
  const VarDecl *DefVD = nullptr;
2411
26.4M
  const Expr *Init = getAnyInitializer(DefVD);
2412
26.4M
  if (!Init || 
Init->isValueDependent()5.74M
||
getType()->isDependentType()5.60M
)
2413
20.8M
    return false;
2414
  //   ... if it is a constexpr variable, or it is of reference type or of
2415
  //   const-qualified integral or enumeration type, ...
2416
5.59M
  if (!DefVD->mightBeUsableInConstantExpressions(Context))
2417
3.36M
    return false;
2418
  //   ... and its initializer is a constant initializer.
2419
2.22M
  if (Context.getLangOpts().CPlusPlus && 
!DefVD->hasConstantInitialization()2.22M
)
2420
153k
    return false;
2421
  // C++98 [expr.const]p1:
2422
  //   An integral constant-expression can involve only [...] const variables
2423
  //   or static data members of integral or enumeration types initialized with
2424
  //   [integer] constant expressions (dcl.init)
2425
2.07M
  if ((Context.getLangOpts().CPlusPlus || 
Context.getLangOpts().OpenCL123
) &&
2426
2.07M
      !Context.getLangOpts().CPlusPlus11 && 
!DefVD->hasICEInitializer(Context)1.74k
)
2427
6
    return false;
2428
2.07M
  return true;
2429
2.07M
}
2430
2431
/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2432
/// form, which contains extra information on the evaluated value of the
2433
/// initializer.
2434
2.89M
EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2435
2.89M
  auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2436
2.89M
  if (!Eval) {
2437
    // Note: EvaluatedStmt contains an APValue, which usually holds
2438
    // resources not allocated from the ASTContext.  We need to do some
2439
    // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2440
    // where we can detect whether there's anything to clean up or not.
2441
539k
    Eval = new (getASTContext()) EvaluatedStmt;
2442
539k
    Eval->Value = Init.get<Stmt *>();
2443
539k
    Init = Eval;
2444
539k
  }
2445
2.89M
  return Eval;
2446
2.89M
}
2447
2448
9.82M
EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2449
9.82M
  return Init.dyn_cast<EvaluatedStmt *>();
2450
9.82M
}
2451
2452
1.93M
APValue *VarDecl::evaluateValue() const {
2453
1.93M
  SmallVector<PartialDiagnosticAt, 8> Notes;
2454
1.93M
  return evaluateValueImpl(Notes, hasConstantInitialization());
2455
1.93M
}
2456
2457
APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2458
2.36M
                                    bool IsConstantInitialization) const {
2459
2.36M
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2460
2461
2.36M
  const auto *Init = cast<Expr>(Eval->Value);
2462
2.36M
  assert(!Init->isValueDependent());
2463
2464
  // We only produce notes indicating why an initializer is non-constant the
2465
  // first time it is evaluated. FIXME: The notes won't always be emitted the
2466
  // first time we try evaluation, so might not be produced at all.
2467
2.36M
  if (Eval->WasEvaluated)
2468
1.87M
    return Eval->Evaluated.isAbsent() ? 
nullptr131k
:
&Eval->Evaluated1.74M
;
2469
2470
493k
  if (Eval->IsEvaluating) {
2471
    // FIXME: Produce a diagnostic for self-initialization.
2472
4
    return nullptr;
2473
4
  }
2474
2475
493k
  Eval->IsEvaluating = true;
2476
2477
493k
  ASTContext &Ctx = getASTContext();
2478
493k
  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2479
493k
                                            IsConstantInitialization);
2480
2481
  // In C++11, this isn't a constant initializer if we produced notes. In that
2482
  // case, we can't keep the result, because it may only be correct under the
2483
  // assumption that the initializer is a constant context.
2484
493k
  if (IsConstantInitialization && 
Ctx.getLangOpts().CPlusPlus11438k
&&
2485
493k
      
!Notes.empty()432k
)
2486
65.9k
    Result = false;
2487
2488
  // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2489
  // or that it's empty (so that there's nothing to clean up) if evaluation
2490
  // failed.
2491
493k
  if (!Result)
2492
118k
    Eval->Evaluated = APValue();
2493
374k
  else if (Eval->Evaluated.needsCleanup())
2494
22.6k
    Ctx.addDestruction(&Eval->Evaluated);
2495
2496
493k
  Eval->IsEvaluating = false;
2497
493k
  Eval->WasEvaluated = true;
2498
2499
493k
  return Result ? 
&Eval->Evaluated374k
:
nullptr118k
;
2500
493k
}
2501
2502
1.70M
APValue *VarDecl::getEvaluatedValue() const {
2503
1.70M
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2504
1.70M
    if (Eval->WasEvaluated)
2505
1.70M
      return &Eval->Evaluated;
2506
2507
8
  return nullptr;
2508
1.70M
}
2509
2510
2.29k
bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2511
2.29k
  const Expr *Init = getInit();
2512
2.29k
  assert(Init && "no initializer");
2513
2514
0
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2515
2.29k
  if (!Eval->CheckedForICEInit) {
2516
572
    Eval->CheckedForICEInit = true;
2517
572
    Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2518
572
  }
2519
2.29k
  return Eval->HasICEInit;
2520
2.29k
}
2521
2522
5.91M
bool VarDecl::hasConstantInitialization() const {
2523
  // In C, all globals (and only globals) have constant initialization.
2524
5.91M
  if (hasGlobalStorage() && 
!getASTContext().getLangOpts().CPlusPlus5.51M
)
2525
7.52k
    return true;
2526
2527
  // In C++, it depends on whether the evaluation at the point of definition
2528
  // was evaluatable as a constant initializer.
2529
5.90M
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2530
5.88M
    return Eval->HasConstantInitialization;
2531
2532
20.4k
  return false;
2533
5.90M
}
2534
2535
bool VarDecl::checkForConstantInitialization(
2536
429k
    SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2537
429k
  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2538
  // If we ask for the value before we know whether we have a constant
2539
  // initializer, we can compute the wrong value (for example, due to
2540
  // std::is_constant_evaluated()).
2541
429k
  assert(!Eval->WasEvaluated &&
2542
429k
         "already evaluated var value before checking for constant init");
2543
0
  assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2544
2545
0
  assert(!cast<Expr>(Eval->Value)->isValueDependent());
2546
2547
  // Evaluate the initializer to check whether it's a constant expression.
2548
0
  Eval->HasConstantInitialization =
2549
429k
      evaluateValueImpl(Notes, true) && 
Notes.empty()362k
;
2550
2551
  // If evaluation as a constant initializer failed, allow re-evaluation as a
2552
  // non-constant initializer if we later find we want the value.
2553
429k
  if (!Eval->HasConstantInitialization)
2554
67.3k
    Eval->WasEvaluated = false;
2555
2556
429k
  return Eval->HasConstantInitialization;
2557
429k
}
2558
2559
241M
bool VarDecl::isParameterPack() const {
2560
241M
  return isa<PackExpansionType>(getType());
2561
241M
}
2562
2563
template<typename DeclT>
2564
4.06M
static DeclT *getDefinitionOrSelf(DeclT *D) {
2565
4.06M
  assert(D);
2566
4.06M
  if (auto *Def = D->getDefinition())
2567
3.51M
    return Def;
2568
548k
  return D;
2569
4.06M
}
Decl.cpp:clang::VarDecl* getDefinitionOrSelf<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
2564
1.08M
static DeclT *getDefinitionOrSelf(DeclT *D) {
2565
1.08M
  assert(D);
2566
1.08M
  if (auto *Def = D->getDefinition())
2567
805k
    return Def;
2568
278k
  return D;
2569
1.08M
}
Decl.cpp:clang::FunctionDecl* getDefinitionOrSelf<clang::FunctionDecl>(clang::FunctionDecl*)
Line
Count
Source
2564
2.90M
static DeclT *getDefinitionOrSelf(DeclT *D) {
2565
2.90M
  assert(D);
2566
2.90M
  if (auto *Def = D->getDefinition())
2567
2.63M
    return Def;
2568
270k
  return D;
2569
2.90M
}
Decl.cpp:clang::EnumDecl* getDefinitionOrSelf<clang::EnumDecl>(clang::EnumDecl*)
Line
Count
Source
2564
73.1k
static DeclT *getDefinitionOrSelf(DeclT *D) {
2565
73.1k
  assert(D);
2566
73.1k
  if (auto *Def = D->getDefinition())
2567
73.1k
    return Def;
2568
5
  return D;
2569
73.1k
}
2570
2571
2.19M
bool VarDecl::isEscapingByref() const {
2572
2.19M
  return hasAttr<BlocksAttr>() && 
NonParmVarDeclBits.EscapingByref2.71k
;
2573
2.19M
}
2574
2575
7.53k
bool VarDecl::isNonEscapingByref() const {
2576
7.53k
  return hasAttr<BlocksAttr>() && 
!NonParmVarDeclBits.EscapingByref594
;
2577
7.53k
}
2578
2579
554k
bool VarDecl::hasDependentAlignment() const {
2580
554k
  QualType T = getType();
2581
554k
  return T->isDependentType() || 
T->isUndeducedAutoType()459k
||
2582
554k
         
llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) 459k
{
2583
36
           return AA->isAlignmentDependent();
2584
36
         });
2585
554k
}
2586
2587
1.20M
VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2588
1.20M
  const VarDecl *VD = this;
2589
2590
  // If this is an instantiated member, walk back to the template from which
2591
  // it was instantiated.
2592
1.20M
  if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2593
1.07M
    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2594
1.07M
      VD = VD->getInstantiatedFromStaticDataMember();
2595
1.07M
      while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2596
0
        VD = NewVD;
2597
1.07M
    }
2598
1.07M
  }
2599
2600
  // If it's an instantiated variable template specialization, find the
2601
  // template or partial specialization from which it was instantiated.
2602
1.20M
  if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2603
5.84k
    if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2604
5.59k
      auto From = VDTemplSpec->getInstantiatedFrom();
2605
5.59k
      if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2606
5.38k
        while (!VTD->isMemberSpecialization()) {
2607
5.36k
          auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2608
5.36k
          if (!NewVTD)
2609
5.01k
            break;
2610
353
          VTD = NewVTD;
2611
353
        }
2612
5.02k
        return getDefinitionOrSelf(VTD->getTemplatedDecl());
2613
5.02k
      }
2614
570
      if (auto *VTPSD =
2615
570
              From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2616
596
        while (!VTPSD->isMemberSpecialization()) {
2617
593
          auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2618
593
          if (!NewVTPSD)
2619
567
            break;
2620
26
          VTPSD = NewVTPSD;
2621
26
        }
2622
570
        return getDefinitionOrSelf<VarDecl>(VTPSD);
2623
570
      }
2624
570
    }
2625
5.84k
  }
2626
2627
  // If this is the pattern of a variable template, find where it was
2628
  // instantiated from. FIXME: Is this necessary?
2629
1.19M
  if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2630
3.68k
    while (!VarTemplate->isMemberSpecialization()) {
2631
3.67k
      auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2632
3.67k
      if (!NewVT)
2633
3.67k
        break;
2634
0
      VarTemplate = NewVT;
2635
0
    }
2636
2637
3.68k
    return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2638
3.68k
  }
2639
2640
1.19M
  if (VD == this)
2641
121k
    return nullptr;
2642
1.07M
  return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2643
1.19M
}
2644
2645
65.7M
VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2646
65.7M
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2647
27.7M
    return cast<VarDecl>(MSI->getInstantiatedFrom());
2648
2649
38.0M
  return nullptr;
2650
65.7M
}
2651
2652
31.6M
TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2653
31.6M
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2654
69.2k
    return Spec->getSpecializationKind();
2655
2656
31.6M
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2657
11.4M
    return MSI->getTemplateSpecializationKind();
2658
2659
20.1M
  return TSK_Undeclared;
2660
31.6M
}
2661
2662
TemplateSpecializationKind
2663
1.08M
VarDecl::getTemplateSpecializationKindForInstantiation() const {
2664
1.08M
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2665
1.07M
    return MSI->getTemplateSpecializationKind();
2666
2667
5.97k
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2668
5.97k
    return Spec->getSpecializationKind();
2669
2670
0
  return TSK_Undeclared;
2671
5.97k
}
2672
2673
23.0k
SourceLocation VarDecl::getPointOfInstantiation() const {
2674
23.0k
  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2675
8.89k
    return Spec->getPointOfInstantiation();
2676
2677
14.1k
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2678
14.1k
    return MSI->getPointOfInstantiation();
2679
2680
0
  return SourceLocation();
2681
14.1k
}
2682
2683
7.32M
VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2684
7.32M
  return getASTContext().getTemplateOrSpecializationInfo(this)
2685
7.32M
      .dyn_cast<VarTemplateDecl *>();
2686
7.32M
}
2687
2688
5.19k
void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2689
5.19k
  getASTContext().setTemplateOrSpecializationInfo(this, Template);
2690
5.19k
}
2691
2692
19
bool VarDecl::isKnownToBeDefined() const {
2693
19
  const auto &LangOpts = getASTContext().getLangOpts();
2694
  // In CUDA mode without relocatable device code, variables of form 'extern
2695
  // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2696
  // memory pool.  These are never undefined variables, even if they appear
2697
  // inside of an anon namespace or static function.
2698
  //
2699
  // With CUDA relocatable device code enabled, these variables don't get
2700
  // special handling; they're treated like regular extern variables.
2701
19
  if (LangOpts.CUDA && 
!LangOpts.GPURelocatableDeviceCode4
&&
2702
19
      
hasExternalStorage()0
&&
hasAttr<CUDASharedAttr>()0
&&
2703
19
      
isa<IncompleteArrayType>(getType())0
)
2704
0
    return true;
2705
2706
19
  return hasDefinition();
2707
19
}
2708
2709
1.86M
bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2710
1.86M
  return hasGlobalStorage() && 
(1.58M
hasAttr<NoDestroyAttr>()1.58M
||
2711
1.58M
                                
(1.58M
!Ctx.getLangOpts().RegisterStaticDestructors1.58M
&&
2712
1.58M
                                 
!hasAttr<AlwaysDestroyAttr>()44
));
2713
1.86M
}
2714
2715
QualType::DestructionKind
2716
1.83M
VarDecl::needsDestruction(const ASTContext &Ctx) const {
2717
1.83M
  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2718
163k
    if (Eval->HasConstantDestruction)
2719
64
      return QualType::DK_none;
2720
2721
1.83M
  if (isNoDestroy(Ctx))
2722
32
    return QualType::DK_none;
2723
2724
1.83M
  return getType().isDestructedType();
2725
1.83M
}
2726
2727
14.4k
bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
2728
14.4k
  assert(hasInit() && "Expect initializer to check for flexible array init");
2729
0
  auto *Ty = getType()->getAs<RecordType>();
2730
14.4k
  if (!Ty || 
!Ty->getDecl()->hasFlexibleArrayMember()4.64k
)
2731
14.4k
    return false;
2732
18
  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2733
18
  if (!List)
2734
15
    return false;
2735
3
  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2736
3
  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2737
3
  if (!InitTy)
2738
0
    return false;
2739
3
  return InitTy->getSize() != 0;
2740
3
}
2741
2742
12.5k
CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
2743
12.5k
  assert(hasInit() && "Expect initializer to check for flexible array init");
2744
0
  auto *Ty = getType()->getAs<RecordType>();
2745
12.5k
  if (!Ty || 
!Ty->getDecl()->hasFlexibleArrayMember()2.29k
)
2746
12.5k
    return CharUnits::Zero();
2747
23
  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2748
23
  if (!List)
2749
2
    return CharUnits::Zero();
2750
21
  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2751
21
  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2752
21
  if (!InitTy)
2753
0
    return CharUnits::Zero();
2754
21
  CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2755
21
  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2756
21
  CharUnits FlexibleArrayOffset =
2757
21
      Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));
2758
21
  if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2759
2
    return CharUnits::Zero();
2760
19
  return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2761
21
}
2762
2763
118M
MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2764
118M
  if (isStaticDataMember())
2765
    // FIXME: Remove ?
2766
    // return getASTContext().getInstantiatedFromStaticDataMember(this);
2767
84.6M
    return getASTContext().getTemplateOrSpecializationInfo(this)
2768
84.6M
        .dyn_cast<MemberSpecializationInfo *>();
2769
33.7M
  return nullptr;
2770
118M
}
2771
2772
void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2773
809k
                                         SourceLocation PointOfInstantiation) {
2774
809k
  assert((isa<VarTemplateSpecializationDecl>(this) ||
2775
809k
          getMemberSpecializationInfo()) &&
2776
809k
         "not a variable or static data member template specialization");
2777
2778
809k
  if (VarTemplateSpecializationDecl *Spec =
2779
809k
          dyn_cast<VarTemplateSpecializationDecl>(this)) {
2780
9.60k
    Spec->setSpecializationKind(TSK);
2781
9.60k
    if (TSK != TSK_ExplicitSpecialization &&
2782
9.60k
        
PointOfInstantiation.isValid()9.59k
&&
2783
9.60k
        
Spec->getPointOfInstantiation().isInvalid()9.59k
) {
2784
4.35k
      Spec->setPointOfInstantiation(PointOfInstantiation);
2785
4.35k
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2786
488
        L->InstantiationRequested(this);
2787
4.35k
    }
2788
799k
  } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2789
799k
    MSI->setTemplateSpecializationKind(TSK);
2790
799k
    if (TSK != TSK_ExplicitSpecialization && 
PointOfInstantiation.isValid()799k
&&
2791
799k
        
MSI->getPointOfInstantiation().isInvalid()799k
) {
2792
14.0k
      MSI->setPointOfInstantiation(PointOfInstantiation);
2793
14.0k
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2794
542
        L->InstantiationRequested(this);
2795
14.0k
    }
2796
799k
  }
2797
809k
}
2798
2799
void
2800
VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2801
239k
                                            TemplateSpecializationKind TSK) {
2802
239k
  assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2803
239k
         "Previous template or instantiation?");
2804
0
  getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2805
239k
}
2806
2807
//===----------------------------------------------------------------------===//
2808
// ParmVarDecl Implementation
2809
//===----------------------------------------------------------------------===//
2810
2811
ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2812
                                 SourceLocation StartLoc,
2813
                                 SourceLocation IdLoc, IdentifierInfo *Id,
2814
                                 QualType T, TypeSourceInfo *TInfo,
2815
72.2M
                                 StorageClass S, Expr *DefArg) {
2816
72.2M
  return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2817
72.2M
                                 S, DefArg);
2818
72.2M
}
2819
2820
11.8M
QualType ParmVarDecl::getOriginalType() const {
2821
11.8M
  TypeSourceInfo *TSI = getTypeSourceInfo();
2822
11.8M
  QualType T = TSI ? 
TSI->getType()8.72M
:
getType()3.16M
;
2823
11.8M
  if (const auto *DT = dyn_cast<DecayedType>(T))
2824
0
    return DT->getOriginalType();
2825
11.8M
  return T;
2826
11.8M
}
2827
2828
2.02M
ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2829
2.02M
  return new (C, ID)
2830
2.02M
      ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2831
2.02M
                  nullptr, QualType(), nullptr, SC_None, nullptr);
2832
2.02M
}
2833
2834
236k
SourceRange ParmVarDecl::getSourceRange() const {
2835
236k
  if (!hasInheritedDefaultArg()) {
2836
235k
    SourceRange ArgRange = getDefaultArgRange();
2837
235k
    if (ArgRange.isValid())
2838
3.70k
      return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2839
235k
  }
2840
2841
  // DeclaratorDecl considers the range of postfix types as overlapping with the
2842
  // declaration name, but this is not the case with parameters in ObjC methods.
2843
232k
  if (isa<ObjCMethodDecl>(getDeclContext()))
2844
647
    return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2845
2846
231k
  return DeclaratorDecl::getSourceRange();
2847
232k
}
2848
2849
10.7k
bool ParmVarDecl::isDestroyedInCallee() const {
2850
  // ns_consumed only affects code generation in ARC
2851
10.7k
  if (hasAttr<NSConsumedAttr>())
2852
13
    return getASTContext().getLangOpts().ObjCAutoRefCount;
2853
2854
  // FIXME: isParamDestroyedInCallee() should probably imply
2855
  // isDestructedType()
2856
10.7k
  auto *RT = getType()->getAs<RecordType>();
2857
10.7k
  if (RT && 
RT->getDecl()->isParamDestroyedInCallee()122
&&
2858
10.7k
      
getType().isDestructedType()17
)
2859
16
    return true;
2860
2861
10.7k
  return false;
2862
10.7k
}
2863
2864
2.27M
Expr *ParmVarDecl::getDefaultArg() {
2865
2.27M
  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2866
0
  assert(!hasUninstantiatedDefaultArg() &&
2867
2.27M
         "Default argument is not yet instantiated!");
2868
2869
0
  Expr *Arg = getInit();
2870
2.27M
  if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2871
18.8k
    if (!isa<ConstantExpr>(E))
2872
18.8k
      return E->getSubExpr();
2873
2874
2.25M
  return Arg;
2875
2.27M
}
2876
2877
74.4M
void ParmVarDecl::setDefaultArg(Expr *defarg) {
2878
74.4M
  ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2879
74.4M
  Init = defarg;
2880
74.4M
}
2881
2882
236k
SourceRange ParmVarDecl::getDefaultArgRange() const {
2883
236k
  switch (ParmVarDeclBits.DefaultArgKind) {
2884
0
  case DAK_None:
2885
9
  case DAK_Unparsed:
2886
    // Nothing we can do here.
2887
9
    return SourceRange();
2888
2889
1
  case DAK_Uninstantiated:
2890
1
    return getUninstantiatedDefaultArg()->getSourceRange();
2891
2892
236k
  case DAK_Normal:
2893
236k
    if (const Expr *E = getInit())
2894
3.85k
      return E->getSourceRange();
2895
2896
    // Missing an actual expression, may be invalid.
2897
232k
    return SourceRange();
2898
236k
  }
2899
0
  llvm_unreachable("Invalid default argument kind.");
2900
0
}
2901
2902
151k
void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2903
151k
  ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2904
151k
  Init = arg;
2905
151k
}
2906
2907
53.8k
Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2908
53.8k
  assert(hasUninstantiatedDefaultArg() &&
2909
53.8k
         "Wrong kind of initialization expression!");
2910
0
  return cast_or_null<Expr>(Init.get<Stmt *>());
2911
53.8k
}
2912
2913
178M
bool ParmVarDecl::hasDefaultArg() const {
2914
  // FIXME: We should just return false for DAK_None here once callers are
2915
  // prepared for the case that we encountered an invalid default argument and
2916
  // were unable to even build an invalid expression.
2917
178M
  return hasUnparsedDefaultArg() || 
hasUninstantiatedDefaultArg()178M
||
2918
178M
         
!Init.isNull()177M
;
2919
178M
}
2920
2921
47
void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2922
47
  getASTContext().setParameterIndex(this, parameterIndex);
2923
47
  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2924
47
}
2925
2926
0
unsigned ParmVarDecl::getParameterIndexLarge() const {
2927
0
  return getASTContext().getParameterIndex(this);
2928
0
}
2929
2930
//===----------------------------------------------------------------------===//
2931
// FunctionDecl Implementation
2932
//===----------------------------------------------------------------------===//
2933
2934
FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2935
                           SourceLocation StartLoc,
2936
                           const DeclarationNameInfo &NameInfo, QualType T,
2937
                           TypeSourceInfo *TInfo, StorageClass S,
2938
                           bool UsesFPIntrin, bool isInlineSpecified,
2939
                           ConstexprSpecKind ConstexprKind,
2940
                           Expr *TrailingRequiresClause)
2941
    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2942
                     StartLoc),
2943
      DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2944
30.5M
      EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2945
30.5M
  assert(T.isNull() || T->isFunctionType());
2946
0
  FunctionDeclBits.SClass = S;
2947
30.5M
  FunctionDeclBits.IsInline = isInlineSpecified;
2948
30.5M
  FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2949
30.5M
  FunctionDeclBits.IsVirtualAsWritten = false;
2950
30.5M
  FunctionDeclBits.IsPure = false;
2951
30.5M
  FunctionDeclBits.HasInheritedPrototype = false;
2952
30.5M
  FunctionDeclBits.HasWrittenPrototype = true;
2953
30.5M
  FunctionDeclBits.IsDeleted = false;
2954
30.5M
  FunctionDeclBits.IsTrivial = false;
2955
30.5M
  FunctionDeclBits.IsTrivialForCall = false;
2956
30.5M
  FunctionDeclBits.IsDefaulted = false;
2957
30.5M
  FunctionDeclBits.IsExplicitlyDefaulted = false;
2958
30.5M
  FunctionDeclBits.HasDefaultedFunctionInfo = false;
2959
30.5M
  FunctionDeclBits.IsIneligibleOrNotSelected = false;
2960
30.5M
  FunctionDeclBits.HasImplicitReturnZero = false;
2961
30.5M
  FunctionDeclBits.IsLateTemplateParsed = false;
2962
30.5M
  FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
2963
30.5M
  FunctionDeclBits.InstantiationIsPending = false;
2964
30.5M
  FunctionDeclBits.UsesSEHTry = false;
2965
30.5M
  FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
2966
30.5M
  FunctionDeclBits.HasSkippedBody = false;
2967
30.5M
  FunctionDeclBits.WillHaveBody = false;
2968
30.5M
  FunctionDeclBits.IsMultiVersion = false;
2969
30.5M
  FunctionDeclBits.IsCopyDeductionCandidate = false;
2970
30.5M
  FunctionDeclBits.HasODRHash = false;
2971
30.5M
  if (TrailingRequiresClause)
2972
882
    setTrailingRequiresClause(TrailingRequiresClause);
2973
30.5M
}
2974
2975
void FunctionDecl::getNameForDiagnostic(
2976
750k
    raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2977
750k
  NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2978
750k
  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2979
750k
  if (TemplateArgs)
2980
41.7k
    printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2981
750k
}
2982
2983
1.36M
bool FunctionDecl::isVariadic() const {
2984
1.36M
  if (const auto *FT = getType()->getAs<FunctionProtoType>())
2985
1.18M
    return FT->isVariadic();
2986
176k
  return false;
2987
1.36M
}
2988
2989
FunctionDecl::DefaultedFunctionInfo *
2990
FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2991
531
                                            ArrayRef<DeclAccessPair> Lookups) {
2992
531
  DefaultedFunctionInfo *Info = new (Context.Allocate(
2993
531
      totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2994
531
      std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2995
531
      DefaultedFunctionInfo;
2996
531
  Info->NumLookups = Lookups.size();
2997
531
  std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2998
531
                          Info->getTrailingObjects<DeclAccessPair>());
2999
531
  return Info;
3000
531
}
3001
3002
654
void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
3003
654
  assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
3004
0
  assert(!Body && "can't replace function body with defaulted function info");
3005
3006
0
  FunctionDeclBits.HasDefaultedFunctionInfo = true;
3007
654
  DefaultedInfo = Info;
3008
654
}
3009
3010
FunctionDecl::DefaultedFunctionInfo *
3011
47.9k
FunctionDecl::getDefaultedFunctionInfo() const {
3012
47.9k
  return FunctionDeclBits.HasDefaultedFunctionInfo ? 
DefaultedInfo1.08k
:
nullptr46.8k
;
3013
47.9k
}
3014
3015
18.1M
bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3016
18.5M
  for (auto I : redecls()) {
3017
18.5M
    if (I->doesThisDeclarationHaveABody()) {
3018
13.8M
      Definition = I;
3019
13.8M
      return true;
3020
13.8M
    }
3021
18.5M
  }
3022
3023
4.34M
  return false;
3024
18.1M
}
3025
3026
2.52k
bool FunctionDecl::hasTrivialBody() const {
3027
2.52k
  Stmt *S = getBody();
3028
2.52k
  if (!S) {
3029
    // Since we don't have a body for this function, we don't know if it's
3030
    // trivial or not.
3031
1.15k
    return false;
3032
1.15k
  }
3033
3034
1.37k
  if (isa<CompoundStmt>(S) && 
cast<CompoundStmt>(S)->body_empty()1.36k
)
3035
1.08k
    return true;
3036
287
  return false;
3037
1.37k
}
3038
3039
11.6M
bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
3040
11.6M
  if (!getFriendObjectKind())
3041
11.6M
    return false;
3042
3043
  // Check for a friend function instantiated from a friend function
3044
  // definition in a templated class.
3045
44.8k
  if (const FunctionDecl *InstantiatedFrom =
3046
44.8k
          getInstantiatedFromMemberFunction())
3047
1.41k
    return InstantiatedFrom->getFriendObjectKind() &&
3048
1.41k
           
InstantiatedFrom->isThisDeclarationADefinition()1.37k
;
3049
3050
  // Check for a friend function template instantiated from a friend
3051
  // function template definition in a templated class.
3052
43.4k
  if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3053
12.4k
    if (const FunctionTemplateDecl *InstantiatedFrom =
3054
12.4k
            Template->getInstantiatedFromMemberTemplate())
3055
11
      return InstantiatedFrom->getFriendObjectKind() &&
3056
11
             InstantiatedFrom->isThisDeclarationADefinition();
3057
12.4k
  }
3058
3059
43.4k
  return false;
3060
43.4k
}
3061
3062
bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3063
18.4M
                             bool CheckForPendingFriendDefinition) const {
3064
19.2M
  for (const FunctionDecl *FD : redecls()) {
3065
19.2M
    if (FD->isThisDeclarationADefinition()) {
3066
8.52M
      Definition = FD;
3067
8.52M
      return true;
3068
8.52M
    }
3069
3070
    // If this is a friend function defined in a class template, it does not
3071
    // have a body until it is used, nevertheless it is a definition, see
3072
    // [temp.inst]p2:
3073
    //
3074
    // ... for the purpose of determining whether an instantiated redeclaration
3075
    // is valid according to [basic.def.odr] and [class.mem], a declaration that
3076
    // corresponds to a definition in the template is considered to be a
3077
    // definition.
3078
    //
3079
    // The following code must produce redefinition error:
3080
    //
3081
    //     template<typename T> struct C20 { friend void func_20() {} };
3082
    //     C20<int> c20i;
3083
    //     void func_20() {}
3084
    //
3085
10.7M
    if (CheckForPendingFriendDefinition &&
3086
10.7M
        
FD->isThisDeclarationInstantiatedFromAFriendDefinition()8.17M
) {
3087
691
      Definition = FD;
3088
691
      return true;
3089
691
    }
3090
10.7M
  }
3091
3092
9.96M
  return false;
3093
18.4M
}
3094
3095
14.5M
Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3096
14.5M
  if (!hasBody(Definition))
3097
3.02M
    return nullptr;
3098
3099
11.4M
  assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3100
11.4M
         "definition should not have a body");
3101
11.4M
  if (Definition->Body)
3102
11.4M
    return Definition->Body.get(getASTContext().getExternalSource());
3103
3104
742
  return nullptr;
3105
11.4M
}
3106
3107
4.54M
void FunctionDecl::setBody(Stmt *B) {
3108
4.54M
  FunctionDeclBits.HasDefaultedFunctionInfo = false;
3109
4.54M
  Body = LazyDeclStmtPtr(B);
3110
4.54M
  if (B)
3111
4.54M
    EndRangeLoc = B->getEndLoc();
3112
4.54M
}
3113
3114
2.50M
void FunctionDecl::setPure(bool P) {
3115
2.50M
  FunctionDeclBits.IsPure = P;
3116
2.50M
  if (P)
3117
6.04k
    if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3118
6.04k
      Parent->markedVirtualFunctionPure();
3119
2.50M
}
3120
3121
template<std::size_t Len>
3122
97.2M
static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3123
97.2M
  IdentifierInfo *II = ND->getIdentifier();
3124
97.2M
  return II && 
II->isStr(Str)97.1M
;
3125
97.2M
}
3126
3127
122M
bool FunctionDecl::isMain() const {
3128
122M
  const TranslationUnitDecl *tunit =
3129
122M
    dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3130
122M
  return tunit &&
3131
122M
         
!tunit->getASTContext().getLangOpts().Freestanding102M
&&
3132
122M
         
isNamed(this, "main")97.2M
;
3133
122M
}
3134
3135
89.4M
bool FunctionDecl::isMSVCRTEntryPoint() const {
3136
89.4M
  const TranslationUnitDecl *TUnit =
3137
89.4M
      dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3138
89.4M
  if (!TUnit)
3139
13.0M
    return false;
3140
3141
  // Even though we aren't really targeting MSVCRT if we are freestanding,
3142
  // semantic analysis for these functions remains the same.
3143
3144
  // MSVCRT entry points only exist on MSVCRT targets.
3145
76.4M
  if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3146
76.2M
    return false;
3147
3148
  // Nameless functions like constructors cannot be entry points.
3149
214k
  if (!getIdentifier())
3150
1.00k
    return false;
3151
3152
213k
  return llvm::StringSwitch<bool>(getName())
3153
213k
      .Cases("main",     // an ANSI console app
3154
213k
             "wmain",    // a Unicode console App
3155
213k
             "WinMain",  // an ANSI GUI app
3156
213k
             "wWinMain", // a Unicode GUI app
3157
213k
             "DllMain",  // a DLL
3158
213k
             true)
3159
213k
      .Default(false);
3160
214k
}
3161
3162
8.02k
bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3163
8.02k
  assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
3164
0
  assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
3165
8.02k
         getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3166
8.02k
         getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
3167
8.02k
         getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
3168
3169
8.02k
  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3170
326
    return false;
3171
3172
7.69k
  const auto *proto = getType()->castAs<FunctionProtoType>();
3173
7.69k
  if (proto->getNumParams() != 2 || 
proto->isVariadic()3.19k
)
3174
4.50k
    return false;
3175
3176
3.19k
  ASTContext &Context =
3177
3.19k
    cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3178
3.19k
      ->getASTContext();
3179
3180
  // The result type and first argument type are constant across all
3181
  // these operators.  The second argument must be exactly void*.
3182
3.19k
  return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3183
7.69k
}
3184
3185
bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3186
9.54M
    Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3187
9.54M
  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3188
9.39M
    return false;
3189
156k
  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3190
156k
      
getDeclName().getCXXOverloadedOperator() != OO_Delete141k
&&
3191
156k
      
getDeclName().getCXXOverloadedOperator() != OO_Array_New134k
&&
3192
156k
      
getDeclName().getCXXOverloadedOperator() != OO_Array_Delete125k
)
3193
123k
    return false;
3194
3195
32.3k
  if (isa<CXXRecordDecl>(getDeclContext()))
3196
1.51k
    return false;
3197
3198
  // This can only fail for an invalid 'operator new' declaration.
3199
30.8k
  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3200
4
    return false;
3201
3202
30.8k
  const auto *FPT = getType()->castAs<FunctionProtoType>();
3203
30.8k
  if (FPT->getNumParams() == 0 || 
FPT->getNumParams() > 330.8k
||
FPT->isVariadic()30.8k
)
3204
11
    return false;
3205
3206
  // If this is a single-parameter function, it must be a replaceable global
3207
  // allocation or deallocation function.
3208
30.8k
  if (FPT->getNumParams() == 1)
3209
21.4k
    return true;
3210
3211
9.41k
  unsigned Params = 1;
3212
9.41k
  QualType Ty = FPT->getParamType(Params);
3213
9.41k
  ASTContext &Ctx = getASTContext();
3214
3215
9.41k
  auto Consume = [&] {
3216
2.94k
    ++Params;
3217
2.94k
    Ty = Params < FPT->getNumParams() ? 
FPT->getParamType(Params)216
:
QualType()2.73k
;
3218
2.94k
  };
3219
3220
  // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3221
9.41k
  bool IsSizedDelete = false;
3222
9.41k
  if (Ctx.getLangOpts().SizedDeallocation &&
3223
9.41k
      
(316
getDeclName().getCXXOverloadedOperator() == OO_Delete316
||
3224
316
       
getDeclName().getCXXOverloadedOperator() == OO_Array_Delete219
) &&
3225
9.41k
      
Ctx.hasSameType(Ty, Ctx.getSizeType())139
) {
3226
81
    IsSizedDelete = true;
3227
81
    Consume();
3228
81
  }
3229
3230
  // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3231
  // new/delete.
3232
9.41k
  if (Ctx.getLangOpts().AlignedAllocation && 
!Ty.isNull()1.81k
&&
Ty->isAlignValT()1.80k
) {
3233
1.37k
    Consume();
3234
1.37k
    if (AlignmentParam)
3235
1.02k
      *AlignmentParam = Params;
3236
1.37k
  }
3237
3238
  // Finally, if this is not a sized delete, the final parameter can
3239
  // be a 'const std::nothrow_t&'.
3240
9.41k
  if (!IsSizedDelete && 
!Ty.isNull()9.32k
&&
Ty->isReferenceType()8.16k
) {
3241
1.55k
    Ty = Ty->getPointeeType();
3242
1.55k
    if (Ty.getCVRQualifiers() != Qualifiers::Const)
3243
6
      return false;
3244
1.55k
    if (Ty->isNothrowT()) {
3245
1.48k
      if (IsNothrow)
3246
1.32k
        *IsNothrow = true;
3247
1.48k
      Consume();
3248
1.48k
    }
3249
1.55k
  }
3250
3251
9.40k
  return Params == FPT->getNumParams();
3252
9.41k
}
3253
3254
679k
bool FunctionDecl::isInlineBuiltinDeclaration() const {
3255
679k
  if (!getBuiltinID())
3256
577k
    return false;
3257
3258
101k
  const FunctionDecl *Definition;
3259
101k
  return hasBody(Definition) && 
Definition->isInlineSpecified()175
&&
3260
101k
         
Definition->hasAttr<AlwaysInlineAttr>()139
&&
3261
101k
         
Definition->hasAttr<GNUInlineAttr>()111
;
3262
679k
}
3263
3264
30.5k
bool FunctionDecl::isDestroyingOperatorDelete() const {
3265
  // C++ P0722:
3266
  //   Within a class C, a single object deallocation function with signature
3267
  //     (T, std::destroying_delete_t, <more params>)
3268
  //   is a destroying operator delete.
3269
30.5k
  if (!isa<CXXMethodDecl>(this) || 
getOverloadedOperator() != OO_Delete4.20k
||
3270
30.5k
      
getNumParams() < 23.58k
)
3271
28.3k
    return false;
3272
3273
2.24k
  auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3274
2.24k
  return RD && 
RD->isInStdNamespace()799
&&
RD->getIdentifier()779
&&
3275
2.24k
         
RD->getIdentifier()->isStr("destroying_delete_t")779
;
3276
30.5k
}
3277
3278
40.4M
LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3279
40.4M
  return getDeclLanguageLinkage(*this);
3280
40.4M
}
3281
3282
38.2M
bool FunctionDecl::isExternC() const {
3283
38.2M
  return isDeclExternC(*this);
3284
38.2M
}
3285
3286
31.7M
bool FunctionDecl::isInExternCContext() const {
3287
31.7M
  if (hasAttr<OpenCLKernelAttr>())
3288
1.50k
    return true;
3289
31.7M
  return getLexicalDeclContext()->isExternCContext();
3290
31.7M
}
3291
3292
20.6k
bool FunctionDecl::isInExternCXXContext() const {
3293
20.6k
  return getLexicalDeclContext()->isExternCXXContext();
3294
20.6k
}
3295
3296
4.10M
bool FunctionDecl::isGlobal() const {
3297
4.10M
  if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3298
1.21M
    return Method->isStatic();
3299
3300
2.88M
  if (getCanonicalDecl()->getStorageClass() == SC_Static)
3301
1.96M
    return false;
3302
3303
918k
  for (const DeclContext *DC = getDeclContext();
3304
1.91M
       DC->isNamespace();
3305
993k
       
DC = DC->getParent()993k
) {
3306
993k
    if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3307
993k
      if (!Namespace->getDeclName())
3308
306
        return false;
3309
993k
    }
3310
993k
  }
3311
3312
917k
  return true;
3313
918k
}
3314
3315
5.68M
bool FunctionDecl::isNoReturn() const {
3316
5.68M
  if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3317
5.68M
      
hasAttr<C11NoReturnAttr>()5.67M
)
3318
4.91k
    return true;
3319
3320
5.67M
  if (auto *FnTy = getType()->getAs<FunctionType>())
3321
5.67M
    return FnTy->getNoReturnAttr();
3322
3323
0
  return false;
3324
5.67M
}
3325
3326
3327
26.7M
MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3328
26.7M
  if (hasAttr<TargetAttr>())
3329
1.25M
    return MultiVersionKind::Target;
3330
25.4M
  if (hasAttr<CPUDispatchAttr>())
3331
202
    return MultiVersionKind::CPUDispatch;
3332
25.4M
  if (hasAttr<CPUSpecificAttr>())
3333
246
    return MultiVersionKind::CPUSpecific;
3334
25.4M
  if (hasAttr<TargetClonesAttr>())
3335
121
    return MultiVersionKind::TargetClones;
3336
25.4M
  return MultiVersionKind::None;
3337
25.4M
}
3338
3339
3.12M
bool FunctionDecl::isCPUDispatchMultiVersion() const {
3340
3.12M
  return isMultiVersion() && 
hasAttr<CPUDispatchAttr>()306
;
3341
3.12M
}
3342
3343
2.98M
bool FunctionDecl::isCPUSpecificMultiVersion() const {
3344
2.98M
  return isMultiVersion() && 
hasAttr<CPUSpecificAttr>()277
;
3345
2.98M
}
3346
3347
324
bool FunctionDecl::isTargetMultiVersion() const {
3348
324
  return isMultiVersion() && hasAttr<TargetAttr>();
3349
324
}
3350
3351
181
bool FunctionDecl::isTargetClonesMultiVersion() const {
3352
181
  return isMultiVersion() && hasAttr<TargetClonesAttr>();
3353
181
}
3354
3355
void
3356
367k
FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3357
367k
  redeclarable_base::setPreviousDecl(PrevDecl);
3358
3359
367k
  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3360
65.9k
    FunctionTemplateDecl *PrevFunTmpl
3361
65.9k
      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 
nullptr0
;
3362
65.9k
    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3363
0
    FunTmpl->setPreviousDecl(PrevFunTmpl);
3364
65.9k
  }
3365
3366
367k
  if (PrevDecl && PrevDecl->isInlined())
3367
51.7k
    setImplicitlyInline(true);
3368
367k
}
3369
3370
622M
FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3371
3372
/// Returns a value indicating whether this function corresponds to a builtin
3373
/// function.
3374
///
3375
/// The function corresponds to a built-in function if it is declared at
3376
/// translation scope or within an extern "C" block and its name matches with
3377
/// the name of a builtin. The returned value will be 0 for functions that do
3378
/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3379
/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3380
/// value.
3381
///
3382
/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3383
/// functions as their wrapped builtins. This shouldn't be done in general, but
3384
/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3385
125M
unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3386
125M
  unsigned BuiltinID = 0;
3387
3388
125M
  if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3389
64.7M
    BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3390
64.7M
  } else 
if (const auto *61.0M
BAA61.0M
= getAttr<BuiltinAliasAttr>()) {
3391
19
    BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3392
61.0M
  } else if (const auto *A = getAttr<BuiltinAttr>()) {
3393
19.1M
    BuiltinID = A->getID();
3394
19.1M
  }
3395
3396
125M
  if (!BuiltinID)
3397
41.8M
    return 0;
3398
3399
  // If the function is marked "overloadable", it has a different mangled name
3400
  // and is not the C library function.
3401
83.9M
  if (!ConsiderWrapperFunctions && 
hasAttr<OverloadableAttr>()82.2M
&&
3402
83.9M
      
(55.0M
!hasAttr<ArmBuiltinAliasAttr>()55.0M
&&
!hasAttr<BuiltinAliasAttr>()10.1k
))
3403
10.1k
    return 0;
3404
3405
83.9M
  ASTContext &Context = getASTContext();
3406
83.9M
  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3407
81.9M
    return BuiltinID;
3408
3409
  // This function has the name of a known C library
3410
  // function. Determine whether it actually refers to the C library
3411
  // function or whether it just has the same name.
3412
3413
  // If this is a static function, it's not a builtin.
3414
2.01M
  if (!ConsiderWrapperFunctions && 
getStorageClass() == SC_Static1.89M
)
3415
0
    return 0;
3416
3417
  // OpenCL v1.2 s6.9.f - The library functions defined in
3418
  // the C99 standard headers are not available.
3419
2.01M
  if (Context.getLangOpts().OpenCL &&
3420
2.01M
      
Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)45
)
3421
45
    return 0;
3422
3423
  // CUDA does not have device-side standard library. printf and malloc are the
3424
  // only special cases that are supported by device-side runtime.
3425
2.01M
  if (Context.getLangOpts().CUDA && 
hasAttr<CUDADeviceAttr>()436
&&
3426
2.01M
      
!hasAttr<CUDAHostAttr>()417
&&
3427
2.01M
      
!(417
BuiltinID == Builtin::BIprintf417
||
BuiltinID == Builtin::BImalloc190
))
3428
80
    return 0;
3429
3430
  // As AMDGCN implementation of OpenMP does not have a device-side standard
3431
  // library, none of the predefined library functions except printf and malloc
3432
  // should be treated as a builtin i.e. 0 should be returned for them.
3433
2.01M
  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3434
2.01M
      
Context.getLangOpts().OpenMPIsDevice1.27k
&&
3435
2.01M
      
Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)1.02k
&&
3436
2.01M
      
!(1.02k
BuiltinID == Builtin::BIprintf1.02k
||
BuiltinID == Builtin::BImalloc1.02k
))
3437
1.01k
    return 0;
3438
3439
2.01M
  return BuiltinID;
3440
2.01M
}
3441
3442
/// getNumParams - Return the number of parameters this function must have
3443
/// based on its FunctionType.  This is the length of the ParamInfo array
3444
/// after it has been created.
3445
256M
unsigned FunctionDecl::getNumParams() const {
3446
256M
  const auto *FPT = getType()->getAs<FunctionProtoType>();
3447
256M
  return FPT ? 
FPT->getNumParams()256M
:
0297k
;
3448
256M
}
3449
3450
void FunctionDecl::setParams(ASTContext &C,
3451
30.3M
                             ArrayRef<ParmVarDecl *> NewParamInfo) {
3452
30.3M
  assert(!ParamInfo && "Already has param info!");
3453
0
  assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3454
3455
  // Zero params -> null pointer.
3456
30.3M
  if (!NewParamInfo.empty()) {
3457
28.3M
    ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3458
28.3M
    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3459
28.3M
  }
3460
30.3M
}
3461
3462
/// getMinRequiredArguments - Returns the minimum number of arguments
3463
/// needed to call this function. This may be fewer than the number of
3464
/// function parameters, if some of the parameters have default
3465
/// arguments (in C++) or are parameter packs (C++11).
3466
65.0M
unsigned FunctionDecl::getMinRequiredArguments() const {
3467
65.0M
  if (!getASTContext().getLangOpts().CPlusPlus)
3468
5.03M
    return getNumParams();
3469
3470
  // Note that it is possible for a parameter with no default argument to
3471
  // follow a parameter with a default argument.
3472
60.0M
  unsigned NumRequiredArgs = 0;
3473
60.0M
  unsigned MinParamsSoFar = 0;
3474
145M
  for (auto *Param : parameters()) {
3475
145M
    if (!Param->isParameterPack()) {
3476
145M
      ++MinParamsSoFar;
3477
145M
      if (!Param->hasDefaultArg())
3478
145M
        NumRequiredArgs = MinParamsSoFar;
3479
145M
    }
3480
145M
  }
3481
60.0M
  return NumRequiredArgs;
3482
65.0M
}
3483
3484
7.48M
bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3485
7.48M
  return getNumParams() == 1 ||
3486
7.48M
         
(2.91M
getNumParams() > 12.91M
&&
3487
2.91M
          std::all_of(param_begin() + 1, param_end(),
3488
1.48M
                      [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3489
7.48M
}
3490
3491
/// The combination of the extern and inline keywords under MSVC forces
3492
/// the function to be required.
3493
///
3494
/// Note: This function assumes that we will only get called when isInlined()
3495
/// would return true for this FunctionDecl.
3496
1.54M
bool FunctionDecl::isMSExternInline() const {
3497
1.54M
  assert(isInlined() && "expected to get called on an inlined function!");
3498
3499
0
  const ASTContext &Context = getASTContext();
3500
1.54M
  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3501
1.54M
      
!hasAttr<DLLExportAttr>()1.53M
)
3502
1.53M
    return false;
3503
3504
18.7k
  
for (const FunctionDecl *FD = getMostRecentDecl(); 8.55k
FD;
3505
10.2k
       FD = FD->getPreviousDecl())
3506
10.3k
    if (!FD->isImplicit() && 
FD->getStorageClass() == SC_Extern10.2k
)
3507
76
      return true;
3508
3509
8.47k
  return false;
3510
8.55k
}
3511
3512
28
static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3513
28
  if (Redecl->getStorageClass() != SC_Extern)
3514
27
    return false;
3515
3516
2
  
for (const FunctionDecl *FD = Redecl->getPreviousDecl(); 1
FD;
3517
1
       FD = FD->getPreviousDecl())
3518
1
    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3519
0
      return false;
3520
3521
1
  return true;
3522
1
}
3523
3524
106k
static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3525
  // Only consider file-scope declarations in this test.
3526
106k
  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3527
0
    return false;
3528
3529
  // Only consider explicit declarations; the presence of a builtin for a
3530
  // libcall shouldn't affect whether a definition is externally visible.
3531
106k
  if (Redecl->isImplicit())
3532
73.5k
    return false;
3533
3534
33.3k
  if (!Redecl->isInlineSpecified() || 
Redecl->getStorageClass() == SC_Extern30.6k
)
3535
2.69k
    return true; // Not an inline definition
3536
3537
30.6k
  return false;
3538
33.3k
}
3539
3540
/// For a function declaration in C or C++, determine whether this
3541
/// declaration causes the definition to be externally visible.
3542
///
3543
/// For instance, this determines if adding the current declaration to the set
3544
/// of redeclarations of the given functions causes
3545
/// isInlineDefinitionExternallyVisible to change from false to true.
3546
20.1M
bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3547
20.1M
  assert(!doesThisDeclarationHaveABody() &&
3548
20.1M
         "Must have a declaration without a body.");
3549
3550
0
  ASTContext &Context = getASTContext();
3551
3552
20.1M
  if (Context.getLangOpts().MSVCCompat) {
3553
2.87k
    const FunctionDecl *Definition;
3554
2.87k
    if (hasBody(Definition) && 
Definition->isInlined()29
&&
3555
2.87k
        
redeclForcesDefMSVC(this)28
)
3556
1
      return true;
3557
2.87k
  }
3558
3559
20.1M
  if (Context.getLangOpts().CPlusPlus)
3560
8.22M
    return false;
3561
3562
11.9M
  if (Context.getLangOpts().GNUInline || 
hasAttr<GNUInlineAttr>()11.9M
) {
3563
    // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3564
    // an externally visible definition.
3565
    //
3566
    // FIXME: What happens if gnu_inline gets added on after the first
3567
    // declaration?
3568
35
    if (!isInlineSpecified() || 
getStorageClass() == SC_Extern14
)
3569
31
      return false;
3570
3571
4
    const FunctionDecl *Prev = this;
3572
4
    bool FoundBody = false;
3573
5
    while ((Prev = Prev->getPreviousDecl())) {
3574
2
      FoundBody |= Prev->doesThisDeclarationHaveABody();
3575
3576
2
      if (Prev->doesThisDeclarationHaveABody()) {
3577
        // If it's not the case that both 'inline' and 'extern' are
3578
        // specified on the definition, then it is always externally visible.
3579
2
        if (!Prev->isInlineSpecified() ||
3580
2
            Prev->getStorageClass() != SC_Extern)
3581
1
          return false;
3582
2
      } else 
if (0
Prev->isInlineSpecified()0
&&
3583
0
                 Prev->getStorageClass() != SC_Extern) {
3584
0
        return false;
3585
0
      }
3586
2
    }
3587
3
    return FoundBody;
3588
4
  }
3589
3590
  // C99 6.7.4p6:
3591
  //   [...] If all of the file scope declarations for a function in a
3592
  //   translation unit include the inline function specifier without extern,
3593
  //   then the definition in that translation unit is an inline definition.
3594
11.9M
  if (isInlineSpecified() && 
getStorageClass() != SC_Extern10.4M
)
3595
10.4M
    return false;
3596
1.48M
  const FunctionDecl *Prev = this;
3597
1.48M
  bool FoundBody = false;
3598
1.55M
  while ((Prev = Prev->getPreviousDecl())) {
3599
70.6k
    FoundBody |= Prev->doesThisDeclarationHaveABody();
3600
70.6k
    if (RedeclForcesDefC99(Prev))
3601
2.53k
      return false;
3602
70.6k
  }
3603
1.48M
  return FoundBody;
3604
1.48M
}
3605
3606
641
FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3607
641
  const TypeSourceInfo *TSI = getTypeSourceInfo();
3608
641
  return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3609
641
             : 
FunctionTypeLoc()0
;
3610
641
}
3611
3612
582
SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3613
582
  FunctionTypeLoc FTL = getFunctionTypeLoc();
3614
582
  if (!FTL)
3615
1
    return SourceRange();
3616
3617
  // Skip self-referential return types.
3618
581
  const SourceManager &SM = getASTContext().getSourceManager();
3619
581
  SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3620
581
  SourceLocation Boundary = getNameInfo().getBeginLoc();
3621
581
  if (RTRange.isInvalid() || Boundary.isInvalid() ||
3622
581
      !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3623
7
    return SourceRange();
3624
3625
574
  return RTRange;
3626
581
}
3627
3628
14
SourceRange FunctionDecl::getParametersSourceRange() const {
3629
14
  unsigned NP = getNumParams();
3630
14
  SourceLocation EllipsisLoc = getEllipsisLoc();
3631
3632
14
  if (NP == 0 && 
EllipsisLoc.isInvalid()1
)
3633
0
    return SourceRange();
3634
3635
14
  SourceLocation Begin =
3636
14
      NP > 0 ? 
ParamInfo[0]->getSourceRange().getBegin()13
:
EllipsisLoc1
;
3637
14
  SourceLocation End = EllipsisLoc.isValid()
3638
14
                           ? 
EllipsisLoc4
3639
14
                           : 
ParamInfo[NP - 1]->getSourceRange().getEnd()10
;
3640
3641
14
  return SourceRange(Begin, End);
3642
14
}
3643
3644
46
SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3645
46
  FunctionTypeLoc FTL = getFunctionTypeLoc();
3646
46
  return FTL ? FTL.getExceptionSpecRange() : 
SourceRange()0
;
3647
46
}
3648
3649
/// For an inline function definition in C, or for a gnu_inline function
3650
/// in C++, determine whether the definition will be externally visible.
3651
///
3652
/// Inline function definitions are always available for inlining optimizations.
3653
/// However, depending on the language dialect, declaration specifiers, and
3654
/// attributes, the definition of an inline function may or may not be
3655
/// "externally" visible to other translation units in the program.
3656
///
3657
/// In C99, inline definitions are not externally visible by default. However,
3658
/// if even one of the global-scope declarations is marked "extern inline", the
3659
/// inline definition becomes externally visible (C99 6.7.4p6).
3660
///
3661
/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3662
/// definition, we use the GNU semantics for inline, which are nearly the
3663
/// opposite of C99 semantics. In particular, "inline" by itself will create
3664
/// an externally visible symbol, but "extern inline" will not create an
3665
/// externally visible symbol.
3666
23.6k
bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3667
23.6k
  assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3668
23.6k
          hasAttr<AliasAttr>()) &&
3669
23.6k
         "Must be a function definition");
3670
0
  assert(isInlined() && "Function must be inline");
3671
0
  ASTContext &Context = getASTContext();
3672
3673
23.6k
  if (Context.getLangOpts().GNUInline || 
hasAttr<GNUInlineAttr>()23.4k
) {
3674
    // Note: If you change the logic here, please change
3675
    // doesDeclarationForceExternallyVisibleDefinition as well.
3676
    //
3677
    // If it's not the case that both 'inline' and 'extern' are
3678
    // specified on the definition, then this inline definition is
3679
    // externally visible.
3680
498
    if (Context.getLangOpts().CPlusPlus)
3681
80
      return false;
3682
418
    if (!(isInlineSpecified() && 
getStorageClass() == SC_Extern372
))
3683
165
      return true;
3684
3685
    // If any declaration is 'inline' but not 'extern', then this definition
3686
    // is externally visible.
3687
472
    
for (auto Redecl : redecls())253
{
3688
472
      if (Redecl->isInlineSpecified() &&
3689
472
          
Redecl->getStorageClass() != SC_Extern284
)
3690
8
        return true;
3691
472
    }
3692
3693
245
    return false;
3694
253
  }
3695
3696
  // The rest of this function is C-only.
3697
23.1k
  assert(!Context.getLangOpts().CPlusPlus &&
3698
23.1k
         "should not use C inline rules in C++");
3699
3700
  // C99 6.7.4p6:
3701
  //   [...] If all of the file scope declarations for a function in a
3702
  //   translation unit include the inline function specifier without extern,
3703
  //   then the definition in that translation unit is an inline definition.
3704
36.2k
  for (auto Redecl : redecls()) {
3705
36.2k
    if (RedeclForcesDefC99(Redecl))
3706
161
      return true;
3707
36.2k
  }
3708
3709
  // C99 6.7.4p6:
3710
  //   An inline definition does not provide an external definition for the
3711
  //   function, and does not forbid an external definition in another
3712
  //   translation unit.
3713
22.9k
  return false;
3714
23.1k
}
3715
3716
/// getOverloadedOperator - Which C++ overloaded operator this
3717
/// function represents, if any.
3718
69.0M
OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3719
69.0M
  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3720
9.74M
    return getDeclName().getCXXOverloadedOperator();
3721
59.2M
  return OO_None;
3722
69.0M
}
3723
3724
/// getLiteralIdentifier - The literal suffix identifier this function
3725
/// represents, if any.
3726
12.8M
const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3727
12.8M
  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3728
1.10k
    return getDeclName().getCXXLiteralIdentifier();
3729
12.8M
  return nullptr;
3730
12.8M
}
3731
3732
10.3M
FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3733
10.3M
  if (TemplateOrSpecialization.isNull())
3734
7.87M
    return TK_NonTemplate;
3735
2.46M
  if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3736
579k
    return TK_FunctionTemplate;
3737
1.88M
  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3738
1.44M
    return TK_MemberSpecialization;
3739
449k
  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3740
448k
    return TK_FunctionTemplateSpecialization;
3741
807
  if (TemplateOrSpecialization.is
3742
807
                               <DependentFunctionTemplateSpecializationInfo*>())
3743
807
    return TK_DependentFunctionTemplateSpecialization;
3744
3745
0
  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3746
0
}
3747
3748
16.7M
FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3749
16.7M
  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3750
1.25M
    return cast<FunctionDecl>(Info->getInstantiatedFrom());
3751
3752
15.4M
  return nullptr;
3753
16.7M
}
3754
3755
30.2M
MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3756
30.2M
  if (auto *MSI =
3757
30.2M
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3758
5.24M
    return MSI;
3759
24.9M
  if (auto *FTSI = TemplateOrSpecialization
3760
24.9M
                       .dyn_cast<FunctionTemplateSpecializationInfo *>())
3761
711k
    return FTSI->getMemberSpecializationInfo();
3762
24.2M
  return nullptr;
3763
24.9M
}
3764
3765
void
3766
FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3767
                                               FunctionDecl *FD,
3768
1.10M
                                               TemplateSpecializationKind TSK) {
3769
1.10M
  assert(TemplateOrSpecialization.isNull() &&
3770
1.10M
         "Member function is already a specialization");
3771
0
  MemberSpecializationInfo *Info
3772
1.10M
    = new (C) MemberSpecializationInfo(FD, TSK);
3773
1.10M
  TemplateOrSpecialization = Info;
3774
1.10M
}
3775
3776
217M
FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3777
217M
  return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3778
217M
}
3779
3780
1.53M
void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3781
1.53M
  assert(TemplateOrSpecialization.isNull() &&
3782
1.53M
         "Member function is already a specialization");
3783
0
  TemplateOrSpecialization = Template;
3784
1.53M
}
3785
3786
4.10M
bool FunctionDecl::isImplicitlyInstantiable() const {
3787
  // If the function is invalid, it can't be implicitly instantiated.
3788
4.10M
  if (isInvalidDecl())
3789
174
    return false;
3790
3791
4.10M
  switch (getTemplateSpecializationKindForInstantiation()) {
3792
3.53M
  case TSK_Undeclared:
3793
3.53M
  case TSK_ExplicitInstantiationDefinition:
3794
3.53M
  case TSK_ExplicitSpecialization:
3795
3.53M
    return false;
3796
3797
559k
  case TSK_ImplicitInstantiation:
3798
559k
    return true;
3799
3800
6.18k
  case TSK_ExplicitInstantiationDeclaration:
3801
    // Handled below.
3802
6.18k
    break;
3803
4.10M
  }
3804
3805
  // Find the actual template from which we will instantiate.
3806
6.18k
  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3807
6.18k
  bool HasPattern = false;
3808
6.18k
  if (PatternDecl)
3809
6.18k
    HasPattern = PatternDecl->hasBody(PatternDecl);
3810
3811
  // C++0x [temp.explicit]p9:
3812
  //   Except for inline functions, other explicit instantiation declarations
3813
  //   have the effect of suppressing the implicit instantiation of the entity
3814
  //   to which they refer.
3815
6.18k
  if (!HasPattern || 
!PatternDecl6.13k
)
3816
42
    return true;
3817
3818
6.13k
  return PatternDecl->isInlined();
3819
6.18k
}
3820
3821
363k
bool FunctionDecl::isTemplateInstantiation() const {
3822
  // FIXME: Remove this, it's not clear what it means. (Which template
3823
  // specialization kind?)
3824
363k
  return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3825
363k
}
3826
3827
FunctionDecl *
3828
7.46M
FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3829
  // If this is a generic lambda call operator specialization, its
3830
  // instantiation pattern is always its primary template's pattern
3831
  // even if its primary template was instantiated from another
3832
  // member template (which happens with nested generic lambdas).
3833
  // Since a lambda's call operator's body is transformed eagerly,
3834
  // we don't have to go hunting for a prototype definition template
3835
  // (i.e. instantiated-from-member-template) to use as an instantiation
3836
  // pattern.
3837
3838
7.46M
  if (isGenericLambdaCallOperatorSpecialization(
3839
7.46M
          dyn_cast<CXXMethodDecl>(this))) {
3840
4.59k
    assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3841
0
    return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3842
4.59k
  }
3843
3844
  // Check for a declaration of this function that was instantiated from a
3845
  // friend definition.
3846
7.46M
  const FunctionDecl *FD = nullptr;
3847
7.46M
  if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3848
3.53M
    FD = this;
3849
3850
7.46M
  if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3851
2.60M
    if (ForDefinition &&
3852
2.60M
        
!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind())2.60M
)
3853
601
      return nullptr;
3854
2.60M
    return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3855
2.60M
  }
3856
3857
4.85M
  if (ForDefinition &&
3858
4.85M
      
!clang::isTemplateInstantiation(getTemplateSpecializationKind())4.85M
)
3859
4.55M
    return nullptr;
3860
3861
298k
  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3862
    // If we hit a point where the user provided a specialization of this
3863
    // template, we're done looking.
3864
492k
    while (!ForDefinition || 
!Primary->isMemberSpecialization()482k
) {
3865
492k
      auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3866
492k
      if (!NewPrimary)
3867
298k
        break;
3868
194k
      Primary = NewPrimary;
3869
194k
    }
3870
3871
298k
    return getDefinitionOrSelf(Primary->getTemplatedDecl());
3872
298k
  }
3873
3874
0
  return nullptr;
3875
298k
}
3876
3877
97.8M
FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3878
97.8M
  if (FunctionTemplateSpecializationInfo *Info
3879
97.8M
        = TemplateOrSpecialization
3880
97.8M
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3881
3.20M
    return Info->getTemplate();
3882
3.20M
  }
3883
94.6M
  return nullptr;
3884
97.8M
}
3885
3886
FunctionTemplateSpecializationInfo *
3887
8.35M
FunctionDecl::getTemplateSpecializationInfo() const {
3888
8.35M
  return TemplateOrSpecialization
3889
8.35M
      .dyn_cast<FunctionTemplateSpecializationInfo *>();
3890
8.35M
}
3891
3892
const TemplateArgumentList *
3893
2.15M
FunctionDecl::getTemplateSpecializationArgs() const {
3894
2.15M
  if (FunctionTemplateSpecializationInfo *Info
3895
2.15M
        = TemplateOrSpecialization
3896
2.15M
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3897
938k
    return Info->TemplateArguments;
3898
938k
  }
3899
1.22M
  return nullptr;
3900
2.15M
}
3901
3902
const ASTTemplateArgumentListInfo *
3903
1.26M
FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3904
1.26M
  if (FunctionTemplateSpecializationInfo *Info
3905
1.26M
        = TemplateOrSpecialization
3906
1.26M
            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3907
829
    return Info->TemplateArgumentsAsWritten;
3908
829
  }
3909
1.26M
  return nullptr;
3910
1.26M
}
3911
3912
void
3913
FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3914
                                                FunctionTemplateDecl *Template,
3915
                                     const TemplateArgumentList *TemplateArgs,
3916
                                                void *InsertPos,
3917
                                                TemplateSpecializationKind TSK,
3918
                        const TemplateArgumentListInfo *TemplateArgsAsWritten,
3919
319k
                                          SourceLocation PointOfInstantiation) {
3920
319k
  assert((TemplateOrSpecialization.isNull() ||
3921
319k
          TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3922
319k
         "Member function is already a specialization");
3923
0
  assert(TSK != TSK_Undeclared &&
3924
319k
         "Must specify the type of function template specialization");
3925
0
  assert((TemplateOrSpecialization.isNull() ||
3926
319k
          TSK == TSK_ExplicitSpecialization) &&
3927
319k
         "Member specialization must be an explicit specialization");
3928
0
  FunctionTemplateSpecializationInfo *Info =
3929
319k
      FunctionTemplateSpecializationInfo::Create(
3930
319k
          C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3931
319k
          PointOfInstantiation,
3932
319k
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3933
319k
  TemplateOrSpecialization = Info;
3934
319k
  Template->addSpecialization(Info, InsertPos);
3935
319k
}
3936
3937
void
3938
FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3939
                                    const UnresolvedSetImpl &Templates,
3940
2.29k
                             const TemplateArgumentListInfo &TemplateArgs) {
3941
2.29k
  assert(TemplateOrSpecialization.isNull());
3942
0
  DependentFunctionTemplateSpecializationInfo *Info =
3943
2.29k
      DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3944
2.29k
                                                          TemplateArgs);
3945
2.29k
  TemplateOrSpecialization = Info;
3946
2.29k
}
3947
3948
DependentFunctionTemplateSpecializationInfo *
3949
1.27M
FunctionDecl::getDependentSpecializationInfo() const {
3950
1.27M
  return TemplateOrSpecialization
3951
1.27M
      .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3952
1.27M
}
3953
3954
DependentFunctionTemplateSpecializationInfo *
3955
DependentFunctionTemplateSpecializationInfo::Create(
3956
    ASTContext &Context, const UnresolvedSetImpl &Ts,
3957
2.29k
    const TemplateArgumentListInfo &TArgs) {
3958
2.29k
  void *Buffer = Context.Allocate(
3959
2.29k
      totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3960
2.29k
          TArgs.size(), Ts.size()));
3961
2.29k
  return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3962
2.29k
}
3963
3964
DependentFunctionTemplateSpecializationInfo::
3965
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3966
                                      const TemplateArgumentListInfo &TArgs)
3967
2.29k
  : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3968
2.29k
  NumTemplates = Ts.size();
3969
2.29k
  NumArgs = TArgs.size();
3970
3971
2.29k
  FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3972
20.3k
  for (unsigned I = 0, E = Ts.size(); I != E; 
++I18.0k
)
3973
18.0k
    TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3974
3975
2.29k
  TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3976
2.30k
  for (unsigned I = 0, E = TArgs.size(); I != E; 
++I9
)
3977
9
    new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3978
2.29k
}
3979
3980
71.2M
TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3981
  // For a function template specialization, query the specialization
3982
  // information object.
3983
71.2M
  if (FunctionTemplateSpecializationInfo *FTSInfo =
3984
71.2M
          TemplateOrSpecialization
3985
71.2M
              .dyn_cast<FunctionTemplateSpecializationInfo *>())
3986
1.48M
    return FTSInfo->getTemplateSpecializationKind();
3987
3988
69.7M
  if (MemberSpecializationInfo *MSInfo =
3989
69.7M
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3990
1.27M
    return MSInfo->getTemplateSpecializationKind();
3991
3992
68.5M
  return TSK_Undeclared;
3993
69.7M
}
3994
3995
TemplateSpecializationKind
3996
4.93M
FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3997
  // This is the same as getTemplateSpecializationKind(), except that for a
3998
  // function that is both a function template specialization and a member
3999
  // specialization, we prefer the member specialization information. Eg:
4000
  //
4001
  // template<typename T> struct A {
4002
  //   template<typename U> void f() {}
4003
  //   template<> void f<int>() {}
4004
  // };
4005
  //
4006
  // For A<int>::f<int>():
4007
  // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4008
  // * getTemplateSpecializationKindForInstantiation() will return
4009
  //       TSK_ImplicitInstantiation
4010
  //
4011
  // This reflects the facts that A<int>::f<int> is an explicit specialization
4012
  // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4013
  // from A::f<int> if a definition is needed.
4014
4.93M
  if (FunctionTemplateSpecializationInfo *FTSInfo =
4015
4.93M
          TemplateOrSpecialization
4016
4.93M
              .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4017
756k
    if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4018
296
      return MSInfo->getTemplateSpecializationKind();
4019
755k
    return FTSInfo->getTemplateSpecializationKind();
4020
756k
  }
4021
4022
4.18M
  if (MemberSpecializationInfo *MSInfo =
4023
4.18M
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4024
642k
    return MSInfo->getTemplateSpecializationKind();
4025
4026
3.53M
  return TSK_Undeclared;
4027
4.18M
}
4028
4029
void
4030
FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4031
205k
                                          SourceLocation PointOfInstantiation) {
4032
205k
  if (FunctionTemplateSpecializationInfo *FTSInfo
4033
205k
        = TemplateOrSpecialization.dyn_cast<
4034
205k
                                    FunctionTemplateSpecializationInfo*>()) {
4035
137k
    FTSInfo->setTemplateSpecializationKind(TSK);
4036
137k
    if (TSK != TSK_ExplicitSpecialization &&
4037
137k
        PointOfInstantiation.isValid() &&
4038
137k
        FTSInfo->getPointOfInstantiation().isInvalid()) {
4039
137k
      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4040
137k
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4041
6.36k
        L->InstantiationRequested(this);
4042
137k
    }
4043
137k
  } else 
if (MemberSpecializationInfo *68.0k
MSInfo68.0k
4044
68.0k
             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4045
68.0k
    MSInfo->setTemplateSpecializationKind(TSK);
4046
68.0k
    if (TSK != TSK_ExplicitSpecialization &&
4047
68.0k
        
PointOfInstantiation.isValid()65.2k
&&
4048
68.0k
        
MSInfo->getPointOfInstantiation().isInvalid()65.2k
) {
4049
65.0k
      MSInfo->setPointOfInstantiation(PointOfInstantiation);
4050
65.0k
      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4051
5.04k
        L->InstantiationRequested(this);
4052
65.0k
    }
4053
68.0k
  } else
4054
0
    llvm_unreachable("Function cannot have a template specialization kind");
4055
205k
}
4056
4057
356k
SourceLocation FunctionDecl::getPointOfInstantiation() const {
4058
356k
  if (FunctionTemplateSpecializationInfo *FTSInfo
4059
356k
        = TemplateOrSpecialization.dyn_cast<
4060
356k
                                        FunctionTemplateSpecializationInfo*>())
4061
183k
    return FTSInfo->getPointOfInstantiation();
4062
172k
  if (MemberSpecializationInfo *MSInfo =
4063
172k
          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4064
172k
    return MSInfo->getPointOfInstantiation();
4065
4066
0
  return SourceLocation();
4067
172k
}
4068
4069
15.0M
bool FunctionDecl::isOutOfLine() const {
4070
15.0M
  if (Decl::isOutOfLine())
4071
498k
    return true;
4072
4073
  // If this function was instantiated from a member function of a
4074
  // class template, check whether that member function was defined out-of-line.
4075
14.5M
  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4076
433k
    const FunctionDecl *Definition;
4077
433k
    if (FD->hasBody(Definition))
4078
426k
      return Definition->isOutOfLine();
4079
433k
  }
4080
4081
  // If this function was instantiated from a function template,
4082
  // check whether that function template was defined out-of-line.
4083
14.1M
  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4084
155k
    const FunctionDecl *Definition;
4085
155k
    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4086
20.1k
      return Definition->isOutOfLine();
4087
155k
  }
4088
4089
14.0M
  return false;
4090
14.1M
}
4091
4092
6.59M
SourceRange FunctionDecl::getSourceRange() const {
4093
6.59M
  return SourceRange(getOuterLocStart(), EndRangeLoc);
4094
6.59M
}
4095
4096
3.62M
unsigned FunctionDecl::getMemoryFunctionKind() const {
4097
3.62M
  IdentifierInfo *FnInfo = getIdentifier();
4098
4099
3.62M
  if (!FnInfo)
4100
0
    return 0;
4101
4102
  // Builtin handling.
4103
3.62M
  switch (getBuiltinID()) {
4104
95
  case Builtin::BI__builtin_memset:
4105
110
  case Builtin::BI__builtin___memset_chk:
4106
323
  case Builtin::BImemset:
4107
323
    return Builtin::BImemset;
4108
4109
259
  case Builtin::BI__builtin_memcpy:
4110
296
  case Builtin::BI__builtin___memcpy_chk:
4111
1.98k
  case Builtin::BImemcpy:
4112
1.98k
    return Builtin::BImemcpy;
4113
4114
22
  case Builtin::BI__builtin_mempcpy:
4115
46
  case Builtin::BI__builtin___mempcpy_chk:
4116
70
  case Builtin::BImempcpy:
4117
70
    return Builtin::BImempcpy;
4118
4119
2.70k
  case Builtin::BI__builtin_memmove:
4120
2.71k
  case Builtin::BI__builtin___memmove_chk:
4121
2.97k
  case Builtin::BImemmove:
4122
2.97k
    return Builtin::BImemmove;
4123
4124
85
  case Builtin::BIstrlcpy:
4125
100
  case Builtin::BI__builtin___strlcpy_chk:
4126
100
    return Builtin::BIstrlcpy;
4127
4128
46
  case Builtin::BIstrlcat:
4129
49
  case Builtin::BI__builtin___strlcat_chk:
4130
49
    return Builtin::BIstrlcat;
4131
4132
747
  case Builtin::BI__builtin_memcmp:
4133
1.24k
  case Builtin::BImemcmp:
4134
1.24k
    return Builtin::BImemcmp;
4135
4136
284
  case Builtin::BI__builtin_bcmp:
4137
306
  case Builtin::BIbcmp:
4138
306
    return Builtin::BIbcmp;
4139
4140
27
  case Builtin::BI__builtin_strncpy:
4141
43
  case Builtin::BI__builtin___strncpy_chk:
4142
149
  case Builtin::BIstrncpy:
4143
149
    return Builtin::BIstrncpy;
4144
4145
142
  case Builtin::BI__builtin_strncmp:
4146
258
  case Builtin::BIstrncmp:
4147
258
    return Builtin::BIstrncmp;
4148
4149
46
  case Builtin::BI__builtin_strncasecmp:
4150
118
  case Builtin::BIstrncasecmp:
4151
118
    return Builtin::BIstrncasecmp;
4152
4153
56
  case Builtin::BI__builtin_strncat:
4154
76
  case Builtin::BI__builtin___strncat_chk:
4155
170
  case Builtin::BIstrncat:
4156
170
    return Builtin::BIstrncat;
4157
4158
2
  case Builtin::BI__builtin_strndup:
4159
19
  case Builtin::BIstrndup:
4160
19
    return Builtin::BIstrndup;
4161
4162
617
  case Builtin::BI__builtin_strlen:
4163
1.22k
  case Builtin::BIstrlen:
4164
1.22k
    return Builtin::BIstrlen;
4165
4166
17
  case Builtin::BI__builtin_bzero:
4167
43
  case Builtin::BIbzero:
4168
43
    return Builtin::BIbzero;
4169
4170
1.21k
  case Builtin::BIfree:
4171
1.21k
    return Builtin::BIfree;
4172
4173
3.61M
  default:
4174
3.61M
    if (isExternC()) {
4175
1.82M
      if (FnInfo->isStr("memset"))
4176
46
        return Builtin::BImemset;
4177
1.82M
      if (FnInfo->isStr("memcpy"))
4178
53
        return Builtin::BImemcpy;
4179
1.82M
      if (FnInfo->isStr("mempcpy"))
4180
0
        return Builtin::BImempcpy;
4181
1.82M
      if (FnInfo->isStr("memmove"))
4182
23
        return Builtin::BImemmove;
4183
1.82M
      if (FnInfo->isStr("memcmp"))
4184
7
        return Builtin::BImemcmp;
4185
1.82M
      if (FnInfo->isStr("bcmp"))
4186
2
        return Builtin::BIbcmp;
4187
1.82M
      if (FnInfo->isStr("strncpy"))
4188
4
        return Builtin::BIstrncpy;
4189
1.82M
      if (FnInfo->isStr("strncmp"))
4190
4
        return Builtin::BIstrncmp;
4191
1.82M
      if (FnInfo->isStr("strncasecmp"))
4192
1
        return Builtin::BIstrncasecmp;
4193
1.82M
      if (FnInfo->isStr("strncat"))
4194
3
        return Builtin::BIstrncat;
4195
1.82M
      if (FnInfo->isStr("strndup"))
4196
1
        return Builtin::BIstrndup;
4197
1.82M
      if (FnInfo->isStr("strlen"))
4198
24
        return Builtin::BIstrlen;
4199
1.82M
      if (FnInfo->isStr("bzero"))
4200
26
        return Builtin::BIbzero;
4201
1.82M
    } else 
if (1.79M
isInStdNamespace()1.79M
) {
4202
259k
      if (FnInfo->isStr("free"))
4203
100
        return Builtin::BIfree;
4204
259k
    }
4205
3.61M
    break;
4206
3.62M
  }
4207
3.61M
  return 0;
4208
3.62M
}
4209
4210
55.4k
unsigned FunctionDecl::getODRHash() const {
4211
55.4k
  assert(hasODRHash());
4212
0
  return ODRHash;
4213
55.4k
}
4214
4215
610k
unsigned FunctionDecl::getODRHash() {
4216
610k
  if (hasODRHash())
4217
115k
    return ODRHash;
4218
4219
494k
  if (auto *FT = getInstantiatedFromMemberFunction()) {
4220
49.3k
    setHasODRHash(true);
4221
49.3k
    ODRHash = FT->getODRHash();
4222
49.3k
    return ODRHash;
4223
49.3k
  }
4224
4225
445k
  class ODRHash Hash;
4226
445k
  Hash.AddFunctionDecl(this);
4227
445k
  setHasODRHash(true);
4228
445k
  ODRHash = Hash.CalculateHash();
4229
445k
  return ODRHash;
4230
494k
}
4231
4232
//===----------------------------------------------------------------------===//
4233
// FieldDecl Implementation
4234
//===----------------------------------------------------------------------===//
4235
4236
FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4237
                             SourceLocation StartLoc, SourceLocation IdLoc,
4238
                             IdentifierInfo *Id, QualType T,
4239
                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4240
4.17M
                             InClassInitStyle InitStyle) {
4241
4.17M
  return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4242
4.17M
                               BW, Mutable, InitStyle);
4243
4.17M
}
4244
4245
100k
FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4246
100k
  return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4247
100k
                               SourceLocation(), nullptr, QualType(), nullptr,
4248
100k
                               nullptr, false, ICIS_NoInit);
4249
100k
}
4250
4251
6.33M
bool FieldDecl::isAnonymousStructOrUnion() const {
4252
6.33M
  if (!isImplicit() || 
getDeclName()460k
)
4253
5.87M
    return false;
4254
4255
460k
  if (const auto *Record = getType()->getAs<RecordType>())
4256
51.7k
    return Record->getDecl()->isAnonymousStructOrUnion();
4257
4258
409k
  return false;
4259
460k
}
4260
4261
59.0k
unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4262
59.0k
  assert(isBitField() && "not a bitfield");
4263
0
  return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4264
59.0k
}
4265
4266
2.98M
bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4267
2.98M
  return isUnnamedBitfield() && 
!getBitWidth()->isValueDependent()2.70k
&&
4268
2.98M
         
getBitWidthValue(Ctx) == 02.70k
;
4269
2.98M
}
4270
4271
2.92M
bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4272
2.92M
  if (isZeroLengthBitField(Ctx))
4273
342
    return true;
4274
4275
  // C++2a [intro.object]p7:
4276
  //   An object has nonzero size if it
4277
  //     -- is not a potentially-overlapping subobject, or
4278
2.92M
  if (!hasAttr<NoUniqueAddressAttr>())
4279
2.92M
    return false;
4280
4281
  //     -- is not of class type, or
4282
614
  const auto *RT = getType()->getAs<RecordType>();
4283
614
  if (!RT)
4284
169
    return false;
4285
445
  const RecordDecl *RD = RT->getDecl()->getDefinition();
4286
445
  if (!RD) {
4287
0
    assert(isInvalidDecl() && "valid field has incomplete type");
4288
0
    return false;
4289
0
  }
4290
4291
  //     -- [has] virtual member functions or virtual base classes, or
4292
  //     -- has subobjects of nonzero size or bit-fields of nonzero length
4293
445
  const auto *CXXRD = cast<CXXRecordDecl>(RD);
4294
445
  if (!CXXRD->isEmpty())
4295
67
    return false;
4296
4297
  // Otherwise, [...] the circumstances under which the object has zero size
4298
  // are implementation-defined.
4299
  // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4300
  // ABI will do.
4301
378
  return true;
4302
445
}
4303
4304
581k
unsigned FieldDecl::getFieldIndex() const {
4305
581k
  const FieldDecl *Canonical = getCanonicalDecl();
4306
581k
  if (Canonical != this)
4307
186
    return Canonical->getFieldIndex();
4308
4309
581k
  if (CachedFieldIndex) 
return CachedFieldIndex - 1462k
;
4310
4311
118k
  unsigned Index = 0;
4312
118k
  const RecordDecl *RD = getParent()->getDefinition();
4313
118k
  assert(RD && "requested index for field of struct with no definition");
4314
4315
297k
  for (auto *Field : RD->fields()) {
4316
297k
    Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4317
297k
    ++Index;
4318
297k
  }
4319
4320
118k
  assert(CachedFieldIndex && "failed to find field in parent");
4321
0
  return CachedFieldIndex - 1;
4322
581k
}
4323
4324
4.25k
SourceRange FieldDecl::getSourceRange() const {
4325
4.25k
  const Expr *FinalExpr = getInClassInitializer();
4326
4.25k
  if (!FinalExpr)
4327
4.12k
    FinalExpr = getBitWidth();
4328
4.25k
  if (FinalExpr)
4329
324
    return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4330
3.93k
  return DeclaratorDecl::getSourceRange();
4331
4.25k
}
4332
4333
8.97k
void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4334
8.97k
  assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4335
8.97k
         "capturing type in non-lambda or captured record.");
4336
0
  assert(InitStorage.getInt() == ISK_NoInit &&
4337
8.97k
         InitStorage.getPointer() == nullptr &&
4338
8.97k
         "bit width, initializer or captured type already set");
4339
0
  InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4340
8.97k
                               ISK_CapturedVLAType);
4341
8.97k
}
4342
4343
//===----------------------------------------------------------------------===//
4344
// TagDecl Implementation
4345
//===----------------------------------------------------------------------===//
4346
4347
TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4348
                 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4349
                 SourceLocation StartL)
4350
    : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4351
7.50M
      TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4352
7.50M
  assert((DK != Enum || TK == TTK_Enum) &&
4353
7.50M
         "EnumDecl not matched with TTK_Enum");
4354
0
  setPreviousDecl(PrevDecl);
4355
7.50M
  setTagKind(TK);
4356
7.50M
  setCompleteDefinition(false);
4357
7.50M
  setBeingDefined(false);
4358
7.50M
  setEmbeddedInDeclarator(false);
4359
7.50M
  setFreeStanding(false);
4360
7.50M
  setCompleteDefinitionRequired(false);
4361
7.50M
  TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4362
7.50M
}
4363
4364
433k
SourceLocation TagDecl::getOuterLocStart() const {
4365
433k
  return getTemplateOrInnerLocStart(this);
4366
433k
}
4367
4368
433k
SourceRange TagDecl::getSourceRange() const {
4369
433k
  SourceLocation RBraceLoc = BraceRange.getEnd();
4370
433k
  SourceLocation E = RBraceLoc.isValid() ? 
RBraceLoc306k
:
getLocation()127k
;
4371
433k
  return SourceRange(getOuterLocStart(), E);
4372
433k
}
4373
4374
54.5M
TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4375
4376
162k
void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4377
162k
  TypedefNameDeclOrQualifier = TDD;
4378
162k
  if (const Type *T = getTypeForDecl()) {
4379
162k
    (void)T;
4380
162k
    assert(T->isLinkageValid());
4381
162k
  }
4382
0
  assert(isLinkageValid());
4383
162k
}
4384
4385
3.52M
void TagDecl::startDefinition() {
4386
3.52M
  setBeingDefined(true);
4387
4388
3.52M
  if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4389
2.59M
    struct CXXRecordDecl::DefinitionData *Data =
4390
2.59M
      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4391
2.59M
    for (auto I : redecls())
4392
2.62M
      cast<CXXRecordDecl>(I)->DefinitionData = Data;
4393
2.59M
  }
4394
3.52M
}
4395
4396
3.56M
void TagDecl::completeDefinition() {
4397
3.56M
  assert((!isa<CXXRecordDecl>(this) ||
4398
3.56M
          cast<CXXRecordDecl>(this)->hasDefinition()) &&
4399
3.56M
         "definition completed but not started");
4400
4401
0
  setCompleteDefinition(true);
4402
3.56M
  setBeingDefined(false);
4403
4404
3.56M
  if (ASTMutationListener *L = getASTMutationListener())
4405
169k
    L->CompletedTagDefinition(this);
4406
3.56M
}
4407
4408
306M
TagDecl *TagDecl::getDefinition() const {
4409
306M
  if (isCompleteDefinition())
4410
212M
    return const_cast<TagDecl *>(this);
4411
4412
  // If it's possible for us to have an out-of-date definition, check now.
4413
94.4M
  if (mayHaveOutOfDateDef()) {
4414
4.91M
    if (IdentifierInfo *II = getIdentifier()) {
4415
4.03M
      if (II->isOutOfDate()) {
4416
0
        updateOutOfDate(*II);
4417
0
      }
4418
4.03M
    }
4419
4.91M
  }
4420
4421
94.4M
  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4422
81.0M
    return CXXRD->getDefinition();
4423
4424
13.3M
  for (auto R : redecls())
4425
14.5M
    if (R->isCompleteDefinition())
4426
9.01k
      return R;
4427
4428
13.3M
  return nullptr;
4429
13.3M
}
4430
4431
327k
void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4432
327k
  if (QualifierLoc) {
4433
    // Make sure the extended qualifier info is allocated.
4434
2.00k
    if (!hasExtInfo())
4435
2.00k
      TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4436
    // Set qualifier info.
4437
2.00k
    getExtInfo()->QualifierLoc = QualifierLoc;
4438
325k
  } else {
4439
    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4440
325k
    if (hasExtInfo()) {
4441
0
      if (getExtInfo()->NumTemplParamLists == 0) {
4442
0
        getASTContext().Deallocate(getExtInfo());
4443
0
        TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4444
0
      }
4445
0
      else
4446
0
        getExtInfo()->QualifierLoc = QualifierLoc;
4447
0
    }
4448
325k
  }
4449
327k
}
4450
4451
void TagDecl::setTemplateParameterListsInfo(
4452
74.2k
    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4453
74.2k
  assert(!TPLists.empty());
4454
  // Make sure the extended decl info is allocated.
4455
74.2k
  if (!hasExtInfo())
4456
    // Allocate external info struct.
4457
73.5k
    TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4458
  // Set the template parameter lists info.
4459
74.2k
  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4460
74.2k
}
4461
4462
//===----------------------------------------------------------------------===//
4463
// EnumDecl Implementation
4464
//===----------------------------------------------------------------------===//
4465
4466
EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4467
                   SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4468
                   bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4469
555k
    : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4470
555k
  assert(Scoped || !ScopedUsingClassTag);
4471
0
  IntegerType = nullptr;
4472
555k
  setNumPositiveBits(0);
4473
555k
  setNumNegativeBits(0);
4474
555k
  setScoped(Scoped);
4475
555k
  setScopedUsingClassTag(ScopedUsingClassTag);
4476
555k
  setFixed(Fixed);
4477
555k
  setHasODRHash(false);
4478
555k
  ODRHash = 0;
4479
555k
}
4480
4481
0
void EnumDecl::anchor() {}
4482
4483
EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4484
                           SourceLocation StartLoc, SourceLocation IdLoc,
4485
                           IdentifierInfo *Id,
4486
                           EnumDecl *PrevDecl, bool IsScoped,
4487
549k
                           bool IsScopedUsingClassTag, bool IsFixed) {
4488
549k
  auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4489
549k
                                    IsScoped, IsScopedUsingClassTag, IsFixed);
4490
549k
  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4491
549k
  C.getTypeDeclType(Enum, PrevDecl);
4492
549k
  return Enum;
4493
549k
}
4494
4495
6.10k
EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4496
6.10k
  EnumDecl *Enum =
4497
6.10k
      new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4498
6.10k
                           nullptr, nullptr, false, false, false);
4499
6.10k
  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4500
6.10k
  return Enum;
4501
6.10k
}
4502
4503
42
SourceRange EnumDecl::getIntegerTypeRange() const {
4504
42
  if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4505
32
    return TI->getTypeLoc().getSourceRange();
4506
10
  return SourceRange();
4507
42
}
4508
4509
void EnumDecl::completeDefinition(QualType NewType,
4510
                                  QualType NewPromotionType,
4511
                                  unsigned NumPositiveBits,
4512
479k
                                  unsigned NumNegativeBits) {
4513
479k
  assert(!isCompleteDefinition() && "Cannot redefine enums!");
4514
479k
  if (!IntegerType)
4515
371k
    IntegerType = NewType.getTypePtr();
4516
479k
  PromotionType = NewPromotionType;
4517
479k
  setNumPositiveBits(NumPositiveBits);
4518
479k
  setNumNegativeBits(NumNegativeBits);
4519
479k
  TagDecl::completeDefinition();
4520
479k
}
4521
4522
475k
bool EnumDecl::isClosed() const {
4523
475k
  if (const auto *A = getAttr<EnumExtensibilityAttr>())
4524
98.6k
    return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4525
376k
  return true;
4526
475k
}
4527
4528
472k
bool EnumDecl::isClosedFlag() const {
4529
472k
  return isClosed() && 
hasAttr<FlagEnumAttr>()375k
;
4530
472k
}
4531
4532
84
bool EnumDecl::isClosedNonFlag() const {
4533
84
  return isClosed() && 
!hasAttr<FlagEnumAttr>()80
;
4534
84
}
4535
4536
920k
TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4537
920k
  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4538
216
    return MSI->getTemplateSpecializationKind();
4539
4540
920k
  return TSK_Undeclared;
4541
920k
}
4542
4543
void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4544
34
                                         SourceLocation PointOfInstantiation) {
4545
34
  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4546
34
  assert(MSI && "Not an instantiated member enumeration?");
4547
0
  MSI->setTemplateSpecializationKind(TSK);
4548
34
  if (TSK != TSK_ExplicitSpecialization &&
4549
34
      
PointOfInstantiation.isValid()0
&&
4550
34
      
MSI->getPointOfInstantiation().isInvalid()0
)
4551
0
    MSI->setPointOfInstantiation(PointOfInstantiation);
4552
34
}
4553
4554
993k
EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4555
993k
  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4556
73.3k
    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4557
73.1k
      EnumDecl *ED = getInstantiatedFromMemberEnum();
4558
73.1k
      while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4559
0
        ED = NewED;
4560
73.1k
      return getDefinitionOrSelf(ED);
4561
73.1k
    }
4562
73.3k
  }
4563
4564
920k
  assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4565
920k
         "couldn't find pattern for enum instantiation");
4566
0
  return nullptr;
4567
993k
}
4568
4569
165k
EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4570
165k
  if (SpecializationInfo)
4571
86.5k
    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4572
4573
78.6k
  return nullptr;
4574
165k
}
4575
4576
void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4577
6.25k
                                            TemplateSpecializationKind TSK) {
4578
6.25k
  assert(!SpecializationInfo && "Member enum is already a specialization");
4579
0
  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4580
6.25k
}
4581
4582
21.7k
unsigned EnumDecl::getODRHash() {
4583
21.7k
  if (hasODRHash())
4584
104
    return ODRHash;
4585
4586
21.6k
  class ODRHash Hash;
4587
21.6k
  Hash.AddEnumDecl(this);
4588
21.6k
  setHasODRHash(true);
4589
21.6k
  ODRHash = Hash.CalculateHash();
4590
21.6k
  return ODRHash;
4591
21.7k
}
4592
4593
1.01k
SourceRange EnumDecl::getSourceRange() const {
4594
1.01k
  auto Res = TagDecl::getSourceRange();
4595
  // Set end-point to enum-base, e.g. enum foo : ^bar
4596
1.01k
  if (auto *TSI = getIntegerTypeSourceInfo()) {
4597
    // TagDecl doesn't know about the enum base.
4598
63
    if (!getBraceRange().getEnd().isValid())
4599
25
      Res.setEnd(TSI->getTypeLoc().getEndLoc());
4600
63
  }
4601
1.01k
  return Res;
4602
1.01k
}
4603
4604
//===----------------------------------------------------------------------===//
4605
// RecordDecl Implementation
4606
//===----------------------------------------------------------------------===//
4607
4608
RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4609
                       DeclContext *DC, SourceLocation StartLoc,
4610
                       SourceLocation IdLoc, IdentifierInfo *Id,
4611
                       RecordDecl *PrevDecl)
4612
6.94M
    : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4613
6.94M
  assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4614
0
  setHasFlexibleArrayMember(false);
4615
6.94M
  setAnonymousStructOrUnion(false);
4616
6.94M
  setHasObjectMember(false);
4617
6.94M
  setHasVolatileMember(false);
4618
6.94M
  setHasLoadedFieldsFromExternalStorage(false);
4619
6.94M
  setNonTrivialToPrimitiveDefaultInitialize(false);
4620
6.94M
  setNonTrivialToPrimitiveCopy(false);
4621
6.94M
  setNonTrivialToPrimitiveDestroy(false);
4622
6.94M
  setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4623
6.94M
  setHasNonTrivialToPrimitiveDestructCUnion(false);
4624
6.94M
  setHasNonTrivialToPrimitiveCopyCUnion(false);
4625
6.94M
  setParamDestroyedInCallee(false);
4626
6.94M
  setArgPassingRestrictions(APK_CanPassInRegs);
4627
6.94M
  setIsRandomized(false);
4628
6.94M
}
4629
4630
RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4631
                               SourceLocation StartLoc, SourceLocation IdLoc,
4632
546k
                               IdentifierInfo *Id, RecordDecl* PrevDecl) {
4633
546k
  RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4634
546k
                                         StartLoc, IdLoc, Id, PrevDecl);
4635
546k
  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4636
4637
546k
  C.getTypeDeclType(R, PrevDecl);
4638
546k
  return R;
4639
546k
}
4640
4641
5.08k
RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4642
5.08k
  RecordDecl *R =
4643
5.08k
      new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4644
5.08k
                             SourceLocation(), nullptr, nullptr);
4645
5.08k
  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4646
5.08k
  return R;
4647
5.08k
}
4648
4649
6.49M
bool RecordDecl::isInjectedClassName() const {
4650
6.49M
  return isImplicit() && 
getDeclName()3.49M
&&
getDeclContext()->isRecord()3.49M
&&
4651
6.49M
    
cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName()3.49M
;
4652
6.49M
}
4653
4654
225k
bool RecordDecl::isLambda() const {
4655
225k
  if (auto RD = dyn_cast<CXXRecordDecl>(this))
4656
224k
    return RD->isLambda();
4657
161
  return false;
4658
225k
}
4659
4660
8.91k
bool RecordDecl::isCapturedRecord() const {
4661
8.91k
  return hasAttr<CapturedRecordAttr>();
4662
8.91k
}
4663
4664
616k
void RecordDecl::setCapturedRecord() {
4665
616k
  addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4666
616k
}
4667
4668
147
bool RecordDecl::isOrContainsUnion() const {
4669
147
  if (isUnion())
4670
11
    return true;
4671
4672
136
  if (const RecordDecl *Def = getDefinition()) {
4673
367
    for (const FieldDecl *FD : Def->fields()) {
4674
367
      const RecordType *RT = FD->getType()->getAs<RecordType>();
4675
367
      if (RT && 
RT->getDecl()->isOrContainsUnion()16
)
4676
1
        return true;
4677
367
    }
4678
136
  }
4679
4680
135
  return false;
4681
136
}
4682
4683
8.61M
RecordDecl::field_iterator RecordDecl::field_begin() const {
4684
8.61M
  if (hasExternalLexicalStorage() && 
!hasLoadedFieldsFromExternalStorage()152k
)
4685
40.6k
    LoadFieldsFromExternalStorage();
4686
4687
8.61M
  return field_iterator(decl_iterator(FirstDecl));
4688
8.61M
}
4689
4690
/// completeDefinition - Notes that the definition of this type is now
4691
/// complete.
4692
3.09M
void RecordDecl::completeDefinition() {
4693
3.09M
  assert(!isCompleteDefinition() && "Cannot redefine record!");
4694
0
  TagDecl::completeDefinition();
4695
4696
3.09M
  ASTContext &Ctx = getASTContext();
4697
4698
  // Layouts are dumped when computed, so if we are dumping for all complete
4699
  // types, we need to force usage to get types that wouldn't be used elsewhere.
4700
3.09M
  if (Ctx.getLangOpts().DumpRecordLayoutsComplete)
4701
5
    (void)Ctx.getASTRecordLayout(this);
4702
3.09M
}
4703
4704
/// isMsStruct - Get whether or not this record uses ms_struct layout.
4705
/// This which can be turned on with an attribute, pragma, or the
4706
/// -mms-bitfields command-line option.
4707
2.20M
bool RecordDecl::isMsStruct(const ASTContext &C) const {
4708
2.20M
  return hasAttr<MSStructAttr>() || 
C.getLangOpts().MSBitfields == 12.20M
;
4709
2.20M
}
4710
4711
19
void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {
4712
19
  std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
4713
19
  LastDecl->NextInContextAndBits.setPointer(nullptr);
4714
19
  setIsRandomized(true);
4715
19
}
4716
4717
40.6k
void RecordDecl::LoadFieldsFromExternalStorage() const {
4718
40.6k
  ExternalASTSource *Source = getASTContext().getExternalSource();
4719
40.6k
  assert(hasExternalLexicalStorage() && Source && "No external storage?");
4720
4721
  // Notify that we have a RecordDecl doing some initialization.
4722
0
  ExternalASTSource::Deserializing TheFields(Source);
4723
4724
40.6k
  SmallVector<Decl*, 64> Decls;
4725
40.6k
  setHasLoadedFieldsFromExternalStorage(true);
4726
400k
  Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4727
400k
    return FieldDecl::classofKind(K) || 
IndirectFieldDecl::classofKind(K)358k
;
4728
400k
  }, Decls);
4729
4730
40.6k
#ifndef NDEBUG
4731
  // Check that all decls we got were FieldDecls.
4732
68.3k
  for (unsigned i=0, e=Decls.size(); i != e; 
++i27.7k
)
4733
27.7k
    assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4734
40.6k
#endif
4735
4736
40.6k
  if (Decls.empty())
4737
30.4k
    return;
4738
4739
10.2k
  std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4740
10.2k
                                                 /*FieldsAlreadyLoaded=*/false);
4741
10.2k
}
4742
4743
473k
bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4744
473k
  ASTContext &Context = getASTContext();
4745
473k
  const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4746
473k
      (SanitizerKind::Address | SanitizerKind::KernelAddress);
4747
473k
  if (!EnabledAsanMask || 
!Context.getLangOpts().SanitizeAddressFieldPadding406
)
4748
472k
    return false;
4749
169
  const auto &NoSanitizeList = Context.getNoSanitizeList();
4750
169
  const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4751
  // We may be able to relax some of these requirements.
4752
169
  int ReasonToReject = -1;
4753
169
  if (!CXXRD || CXXRD->isExternCContext())
4754
13
    ReasonToReject = 0;  // is not C++.
4755
156
  else if (CXXRD->hasAttr<PackedAttr>())
4756
13
    ReasonToReject = 1;  // is packed.
4757
143
  else if (CXXRD->isUnion())
4758
3
    ReasonToReject = 2;  // is a union.
4759
140
  else if (CXXRD->isTriviallyCopyable())
4760
27
    ReasonToReject = 3;  // is trivially copyable.
4761
113
  else if (CXXRD->hasTrivialDestructor())
4762
0
    ReasonToReject = 4;  // has trivial destructor.
4763
113
  else if (CXXRD->isStandardLayout())
4764
0
    ReasonToReject = 5;  // is standard layout.
4765
113
  else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
4766
113
                                           "field-padding"))
4767
39
    ReasonToReject = 6;  // is in an excluded file.
4768
74
  else if (NoSanitizeList.containsType(
4769
74
               EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4770
8
    ReasonToReject = 7;  // The type is excluded.
4771
4772
169
  if (EmitRemark) {
4773
48
    if (ReasonToReject >= 0)
4774
32
      Context.getDiagnostics().Report(
4775
32
          getLocation(),
4776
32
          diag::remark_sanitize_address_insert_extra_padding_rejected)
4777
32
          << getQualifiedNameAsString() << ReasonToReject;
4778
16
    else
4779
16
      Context.getDiagnostics().Report(
4780
16
          getLocation(),
4781
16
          diag::remark_sanitize_address_insert_extra_padding_accepted)
4782
16
          << getQualifiedNameAsString();
4783
48
  }
4784
169
  return ReasonToReject < 0;
4785
473k
}
4786
4787
49
const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4788
49
  for (const auto *I : fields()) {
4789
46
    if (I->getIdentifier())
4790
38
      return I;
4791
4792
8
    if (const auto *RT = I->getType()->getAs<RecordType>())
4793
6
      if (const FieldDecl *NamedDataMember =
4794
6
              RT->getDecl()->findFirstNamedDataMember())
4795
3
        return NamedDataMember;
4796
8
  }
4797
4798
  // We didn't find a named data member.
4799
8
  return nullptr;
4800
49
}
4801
4802
//===----------------------------------------------------------------------===//
4803
// BlockDecl Implementation
4804
//===----------------------------------------------------------------------===//
4805
4806
BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4807
3.54k
    : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4808
3.54k
  setIsVariadic(false);
4809
3.54k
  setCapturesCXXThis(false);
4810
3.54k
  setBlockMissingReturnType(true);
4811
3.54k
  setIsConversionFromLambda(false);
4812
3.54k
  setDoesNotEscape(false);
4813
3.54k
  setCanAvoidCopyToHeap(false);
4814
3.54k
}
4815
4816
1.11k
void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4817
1.11k
  assert(!ParamInfo && "Already has param info!");
4818
4819
  // Zero params -> null pointer.
4820
1.11k
  if (!NewParamInfo.empty()) {
4821
1.08k
    NumParams = NewParamInfo.size();
4822
1.08k
    ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4823
1.08k
    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4824
1.08k
  }
4825
1.11k
}
4826
4827
void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4828
3.30k
                            bool CapturesCXXThis) {
4829
3.30k
  this->setCapturesCXXThis(CapturesCXXThis);
4830
3.30k
  this->NumCaptures = Captures.size();
4831
4832
3.30k
  if (Captures.empty()) {
4833
1.79k
    this->Captures = nullptr;
4834
1.79k
    return;
4835
1.79k
  }
4836
4837
1.51k
  this->Captures = Captures.copy(Context).data();
4838
1.51k
}
4839
4840
123
bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4841
123
  for (const auto &I : captures())
4842
    // Only auto vars can be captured, so no redeclaration worries.
4843
136
    if (I.getVariable() == variable)
4844
82
      return true;
4845
4846
41
  return false;
4847
123
}
4848
4849
23.7k
SourceRange BlockDecl::getSourceRange() const {
4850
23.7k
  return SourceRange(getLocation(), Body ? Body->getEndLoc() : 
getLocation()0
);
4851
23.7k
}
4852
4853
//===----------------------------------------------------------------------===//
4854
// Other Decl Allocation/Deallocation Method Implementations
4855
//===----------------------------------------------------------------------===//
4856
4857
0
void TranslationUnitDecl::anchor() {}
4858
4859
96.7k
TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4860
96.7k
  return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4861
96.7k
}
4862
4863
0
void PragmaCommentDecl::anchor() {}
4864
4865
PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4866
                                             TranslationUnitDecl *DC,
4867
                                             SourceLocation CommentLoc,
4868
                                             PragmaMSCommentKind CommentKind,
4869
66
                                             StringRef Arg) {
4870
66
  PragmaCommentDecl *PCD =
4871
66
      new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4872
66
          PragmaCommentDecl(DC, CommentLoc, CommentKind);
4873
66
  memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4874
66
  PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4875
66
  return PCD;
4876
66
}
4877
4878
PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4879
                                                         unsigned ID,
4880
2
                                                         unsigned ArgSize) {
4881
2
  return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4882
2
      PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4883
2
}
4884
4885
0
void PragmaDetectMismatchDecl::anchor() {}
4886
4887
PragmaDetectMismatchDecl *
4888
PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4889
                                 SourceLocation Loc, StringRef Name,
4890
16
                                 StringRef Value) {
4891
16
  size_t ValueStart = Name.size() + 1;
4892
16
  PragmaDetectMismatchDecl *PDMD =
4893
16
      new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4894
16
          PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4895
16
  memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4896
16
  PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4897
16
  memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4898
16
         Value.size());
4899
16
  PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4900
16
  return PDMD;
4901
16
}
4902
4903
PragmaDetectMismatchDecl *
4904
PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4905
2
                                             unsigned NameValueSize) {
4906
2
  return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4907
2
      PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4908
2
}
4909
4910
0
void ExternCContextDecl::anchor() {}
4911
4912
ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4913
68.4k
                                               TranslationUnitDecl *DC) {
4914
68.4k
  return new (C, DC) ExternCContextDecl(DC);
4915
68.4k
}
4916
4917
0
void LabelDecl::anchor() {}
4918
4919
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4920
4.30k
                             SourceLocation IdentL, IdentifierInfo *II) {
4921
4.30k
  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4922
4.30k
}
4923
4924
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4925
                             SourceLocation IdentL, IdentifierInfo *II,
4926
11
                             SourceLocation GnuLabelL) {
4927
11
  assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4928
0
  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4929
11
}
4930
4931
270
LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4932
270
  return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4933
270
                               SourceLocation());
4934
270
}
4935
4936
27
void LabelDecl::setMSAsmLabel(StringRef Name) {
4937
27
char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4938
27
  memcpy(Buffer, Name.data(), Name.size());
4939
27
  Buffer[Name.size()] = '\0';
4940
27
  MSAsmName = Buffer;
4941
27
}
4942
4943
0
void ValueDecl::anchor() {}
4944
4945
21.0M
bool ValueDecl::isWeak() const {
4946
21.0M
  auto *MostRecent = getMostRecentDecl();
4947
21.0M
  return MostRecent->hasAttr<WeakAttr>() ||
4948
21.0M
         
MostRecent->hasAttr<WeakRefAttr>()21.0M
||
isWeakImported()21.0M
;
4949
21.0M
}
4950
4951
0
void ImplicitParamDecl::anchor() {}
4952
4953
ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4954
                                             SourceLocation IdLoc,
4955
                                             IdentifierInfo *Id, QualType Type,
4956
4.79M
                                             ImplicitParamKind ParamKind) {
4957
4.79M
  return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4958
4.79M
}
4959
4960
ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4961
10
                                             ImplicitParamKind ParamKind) {
4962
10
  return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4963
10
}
4964
4965
ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4966
166k
                                                         unsigned ID) {
4967
166k
  return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);