Coverage Report

Created: 2020-09-19 12:23

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