xref: /llvm-project/clang/lib/AST/Decl.cpp (revision abc8812df02599fc413d9ed77b992f8236ed2af9)
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/DeclTemplate.h"
25 #include "clang/AST/DeclarationName.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExternalASTSource.h"
29 #include "clang/AST/ODRHash.h"
30 #include "clang/AST/PrettyDeclStackTrace.h"
31 #include "clang/AST/PrettyPrinter.h"
32 #include "clang/AST/Randstruct.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Redeclarable.h"
35 #include "clang/AST/Stmt.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
39 #include "clang/Basic/Builtins.h"
40 #include "clang/Basic/IdentifierTable.h"
41 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/LangOptions.h"
43 #include "clang/Basic/Linkage.h"
44 #include "clang/Basic/Module.h"
45 #include "clang/Basic/NoSanitizeList.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/Sanitizers.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/TargetCXXABI.h"
52 #include "clang/Basic/TargetInfo.h"
53 #include "clang/Basic/Visibility.h"
54 #include "llvm/ADT/APSInt.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/ADT/StringSwitch.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/TargetParser/Triple.h"
64 #include <algorithm>
65 #include <cassert>
66 #include <cstddef>
67 #include <cstring>
68 #include <memory>
69 #include <optional>
70 #include <string>
71 #include <tuple>
72 #include <type_traits>
73 
74 using namespace clang;
75 
76 Decl *clang::getPrimaryMergedDecl(Decl *D) {
77   return D->getASTContext().getPrimaryMergedDecl(D);
78 }
79 
80 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81   SourceLocation Loc = this->Loc;
82   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83   if (Loc.isValid()) {
84     Loc.print(OS, Context.getSourceManager());
85     OS << ": ";
86   }
87   OS << Message;
88 
89   if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {
90     OS << " '";
91     ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92     OS << "'";
93   }
94 
95   OS << '\n';
96 }
97 
98 // Defined here so that it can be inlined into its direct callers.
99 bool Decl::isOutOfLine() const {
100   return !getLexicalDeclContext()->Equals(getDeclContext());
101 }
102 
103 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104     : Decl(TranslationUnit, nullptr, SourceLocation()),
105       DeclContext(TranslationUnit), redeclarable_base(ctx), 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 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
160   return computation.IgnoreExplicitVisibility;
161 }
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 withExplicitVisibilityAlready(LVComputationKind Kind) {
167   Kind.IgnoreExplicitVisibility = true;
168   return Kind;
169 }
170 
171 static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172                                                        LVComputationKind kind) {
173   assert(!kind.IgnoreExplicitVisibility &&
174          "asking for explicit visibility when we shouldn't be");
175   return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
176 }
177 
178 /// Is the given declaration a "type" or a "value" for the purposes of
179 /// visibility computation?
180 static bool usesTypeVisibility(const NamedDecl *D) {
181   return isa<TypeDecl>(D) ||
182          isa<ClassTemplateDecl>(D) ||
183          isa<ObjCInterfaceDecl>(D);
184 }
185 
186 /// Does the given declaration have member specialization information,
187 /// and if so, is it an explicit specialization?
188 template <class T>
189 static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>
190 isExplicitMemberSpecialization(const T *D) {
191   if (const MemberSpecializationInfo *member =
192         D->getMemberSpecializationInfo()) {
193     return member->isExplicitSpecialization();
194   }
195   return false;
196 }
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 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202   return D->isMemberSpecialization();
203 }
204 
205 /// Given a visibility attribute, return the explicit visibility
206 /// associated with it.
207 template <class T>
208 static Visibility getVisibilityFromAttr(const T *attr) {
209   switch (attr->getVisibility()) {
210   case T::Default:
211     return DefaultVisibility;
212   case T::Hidden:
213     return HiddenVisibility;
214   case T::Protected:
215     return ProtectedVisibility;
216   }
217   llvm_unreachable("bad visibility kind");
218 }
219 
220 /// Return the explicit visibility of the given declaration.
221 static std::optional<Visibility>
222 getVisibilityOf(const NamedDecl *D, 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   if (kind == NamedDecl::VisibilityForType) {
226     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
227       return getVisibilityFromAttr(A);
228     }
229   }
230 
231   // If this declaration has an explicit visibility attribute, use it.
232   if (const auto *A = D->getAttr<VisibilityAttr>()) {
233     return getVisibilityFromAttr(A);
234   }
235 
236   return std::nullopt;
237 }
238 
239 LinkageInfo LinkageComputer::getLVForType(const Type &T,
240                                           LVComputationKind computation) {
241   if (computation.IgnoreAllVisibility)
242     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
243   return getTypeLinkageAndVisibility(&T);
244 }
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     const TemplateParameterList *Params, LVComputationKind computation) {
251   LinkageInfo LV;
252   for (const NamedDecl *P : *Params) {
253     // Template type parameters are the most common and never
254     // contribute to visibility, pack or not.
255     if (isa<TemplateTypeParmDecl>(P))
256       continue;
257 
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     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
263       // Handle the non-pack case first.
264       if (!NTTP->isExpandedParameterPack()) {
265         if (!NTTP->getType()->isDependentType()) {
266           LV.merge(getLVForType(*NTTP->getType(), computation));
267         }
268         continue;
269       }
270 
271       // Look at all the types in an expanded pack.
272       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273         QualType type = NTTP->getExpansionType(i);
274         if (!type->isDependentType())
275           LV.merge(getTypeLinkageAndVisibility(type));
276       }
277       continue;
278     }
279 
280     // Template template parameters can be restricted by their
281     // template parameters, recursively.
282     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
283 
284     // Handle the non-pack case first.
285     if (!TTP->isExpandedParameterPack()) {
286       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287                                              computation));
288       continue;
289     }
290 
291     // Look at all expansions in an expanded pack.
292     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293            i != n; ++i) {
294       LV.merge(getLVForTemplateParameterList(
295           TTP->getExpansionTemplateParameters(i), computation));
296     }
297   }
298 
299   return LV;
300 }
301 
302 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
303   const Decl *Ret = nullptr;
304   const DeclContext *DC = D->getDeclContext();
305   while (DC->getDeclKind() != Decl::TranslationUnit) {
306     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307       Ret = cast<Decl>(DC);
308     DC = DC->getParent();
309   }
310   return Ret;
311 }
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                                               LVComputationKind computation) {
321   LinkageInfo LV;
322 
323   for (const TemplateArgument &Arg : Args) {
324     switch (Arg.getKind()) {
325     case TemplateArgument::Null:
326     case TemplateArgument::Integral:
327     case TemplateArgument::Expression:
328       continue;
329 
330     case TemplateArgument::Type:
331       LV.merge(getLVForType(*Arg.getAsType(), computation));
332       continue;
333 
334     case TemplateArgument::Declaration: {
335       const NamedDecl *ND = Arg.getAsDecl();
336       assert(!usesTypeVisibility(ND));
337       LV.merge(getLVForDecl(ND, computation));
338       continue;
339     }
340 
341     case TemplateArgument::NullPtr:
342       LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
343       continue;
344 
345     case TemplateArgument::StructuralValue:
346       LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));
347       continue;
348 
349     case TemplateArgument::Template:
350     case TemplateArgument::TemplateExpansion:
351       if (TemplateDecl *Template =
352               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl(
353                   /*IgnoreDeduced=*/true))
354         LV.merge(getLVForDecl(Template, computation));
355       continue;
356 
357     case TemplateArgument::Pack:
358       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
359       continue;
360     }
361     llvm_unreachable("bad template argument kind");
362   }
363 
364   return LV;
365 }
366 
367 LinkageInfo
368 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
369                                               LVComputationKind computation) {
370   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
371 }
372 
373 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
374                         const FunctionTemplateSpecializationInfo *specInfo) {
375   // Include visibility from the template parameters and arguments
376   // only if this is not an explicit instantiation or specialization
377   // with direct explicit visibility.  (Implicit instantiations won't
378   // have a direct attribute.)
379   if (!specInfo->isExplicitInstantiationOrSpecialization())
380     return true;
381 
382   return !fn->hasAttr<VisibilityAttr>();
383 }
384 
385 /// Merge in template-related linkage and visibility for the given
386 /// function template specialization.
387 ///
388 /// We don't need a computation kind here because we can assume
389 /// LVForValue.
390 ///
391 /// \param[out] LV the computation to use for the parent
392 void LinkageComputer::mergeTemplateLV(
393     LinkageInfo &LV, const FunctionDecl *fn,
394     const FunctionTemplateSpecializationInfo *specInfo,
395     LVComputationKind computation) {
396   bool considerVisibility =
397     shouldConsiderTemplateVisibility(fn, specInfo);
398 
399   FunctionTemplateDecl *temp = specInfo->getTemplate();
400   // Merge information from the template declaration.
401   LinkageInfo tempLV = getLVForDecl(temp, computation);
402   // The linkage of the specialization should be consistent with the
403   // template declaration.
404   LV.setLinkage(tempLV.getLinkage());
405 
406   // Merge information from the template parameters.
407   LinkageInfo paramsLV =
408       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
409   LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
410 
411   // Merge information from the template arguments.
412   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
413   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
414   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
415 }
416 
417 /// Does the given declaration have a direct visibility attribute
418 /// that would match the given rules?
419 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
420                                          LVComputationKind computation) {
421   if (computation.IgnoreAllVisibility)
422     return false;
423 
424   return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
425          D->hasAttr<VisibilityAttr>();
426 }
427 
428 /// Should we consider visibility associated with the template
429 /// arguments and parameters of the given class template specialization?
430 static bool shouldConsiderTemplateVisibility(
431                                  const ClassTemplateSpecializationDecl *spec,
432                                  LVComputationKind computation) {
433   // Include visibility from the template parameters and arguments
434   // only if this is not an explicit instantiation or specialization
435   // with direct explicit visibility (and note that implicit
436   // instantiations won't have a direct attribute).
437   //
438   // Furthermore, we want to ignore template parameters and arguments
439   // for an explicit specialization when computing the visibility of a
440   // member thereof with explicit visibility.
441   //
442   // This is a bit complex; let's unpack it.
443   //
444   // An explicit class specialization is an independent, top-level
445   // declaration.  As such, if it or any of its members has an
446   // explicit visibility attribute, that must directly express the
447   // user's intent, and we should honor it.  The same logic applies to
448   // an explicit instantiation of a member of such a thing.
449 
450   // Fast path: if this is not an explicit instantiation or
451   // specialization, we always want to consider template-related
452   // visibility restrictions.
453   if (!spec->isExplicitInstantiationOrSpecialization())
454     return true;
455 
456   // This is the 'member thereof' check.
457   if (spec->isExplicitSpecialization() &&
458       hasExplicitVisibilityAlready(computation))
459     return false;
460 
461   return !hasDirectVisibilityAttribute(spec, computation);
462 }
463 
464 /// Merge in template-related linkage and visibility for the given
465 /// class template specialization.
466 void LinkageComputer::mergeTemplateLV(
467     LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
468     LVComputationKind computation) {
469   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
470 
471   // Merge information from the template parameters, but ignore
472   // visibility if we're only considering template arguments.
473   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
474   // Merge information from the template declaration.
475   LinkageInfo tempLV = getLVForDecl(temp, computation);
476   // The linkage of the specialization should be consistent with the
477   // template declaration.
478   LV.setLinkage(tempLV.getLinkage());
479 
480   LinkageInfo paramsLV =
481     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
482   LV.mergeMaybeWithVisibility(paramsLV,
483            considerVisibility && !hasExplicitVisibilityAlready(computation));
484 
485   // Merge information from the template arguments.  We ignore
486   // template-argument visibility if we've got an explicit
487   // instantiation with a visibility attribute.
488   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
489   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
490   if (considerVisibility)
491     LV.mergeVisibility(argsLV);
492   LV.mergeExternalVisibility(argsLV);
493 }
494 
495 /// Should we consider visibility associated with the template
496 /// arguments and parameters of the given variable template
497 /// specialization? As usual, follow class template specialization
498 /// logic up to initialization.
499 static bool shouldConsiderTemplateVisibility(
500                                  const VarTemplateSpecializationDecl *spec,
501                                  LVComputationKind computation) {
502   // Include visibility from the template parameters and arguments
503   // only if this is not an explicit instantiation or specialization
504   // with direct explicit visibility (and note that implicit
505   // instantiations won't have a direct attribute).
506   if (!spec->isExplicitInstantiationOrSpecialization())
507     return true;
508 
509   // An explicit variable specialization is an independent, top-level
510   // declaration.  As such, if it has an explicit visibility attribute,
511   // that must directly express the user's intent, and we should honor
512   // it.
513   if (spec->isExplicitSpecialization() &&
514       hasExplicitVisibilityAlready(computation))
515     return false;
516 
517   return !hasDirectVisibilityAttribute(spec, computation);
518 }
519 
520 /// Merge in template-related linkage and visibility for the given
521 /// variable template specialization. As usual, follow class template
522 /// specialization logic up to initialization.
523 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
524                                       const VarTemplateSpecializationDecl *spec,
525                                       LVComputationKind computation) {
526   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
527 
528   // Merge information from the template parameters, but ignore
529   // visibility if we're only considering template arguments.
530   VarTemplateDecl *temp = spec->getSpecializedTemplate();
531   LinkageInfo tempLV =
532     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
533   LV.mergeMaybeWithVisibility(tempLV,
534            considerVisibility && !hasExplicitVisibilityAlready(computation));
535 
536   // Merge information from the template arguments.  We ignore
537   // template-argument visibility if we've got an explicit
538   // instantiation with a visibility attribute.
539   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
540   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
541   if (considerVisibility)
542     LV.mergeVisibility(argsLV);
543   LV.mergeExternalVisibility(argsLV);
544 }
545 
546 static bool useInlineVisibilityHidden(const NamedDecl *D) {
547   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
548   const LangOptions &Opts = D->getASTContext().getLangOpts();
549   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
550     return false;
551 
552   const auto *FD = dyn_cast<FunctionDecl>(D);
553   if (!FD)
554     return false;
555 
556   TemplateSpecializationKind TSK = TSK_Undeclared;
557   if (FunctionTemplateSpecializationInfo *spec
558       = FD->getTemplateSpecializationInfo()) {
559     TSK = spec->getTemplateSpecializationKind();
560   } else if (MemberSpecializationInfo *MSI =
561              FD->getMemberSpecializationInfo()) {
562     TSK = MSI->getTemplateSpecializationKind();
563   }
564 
565   const FunctionDecl *Def = nullptr;
566   // InlineVisibilityHidden only applies to definitions, and
567   // isInlined() only gives meaningful answers on definitions
568   // anyway.
569   return TSK != TSK_ExplicitInstantiationDeclaration &&
570     TSK != TSK_ExplicitInstantiationDefinition &&
571     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
572 }
573 
574 template <typename T> static bool isFirstInExternCContext(T *D) {
575   const T *First = D->getFirstDecl();
576   return First->isInExternCContext();
577 }
578 
579 static bool isSingleLineLanguageLinkage(const Decl &D) {
580   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
581     if (!SD->hasBraces())
582       return true;
583   return false;
584 }
585 
586 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
587   return LinkageInfo::external();
588 }
589 
590 static StorageClass getStorageClass(const Decl *D) {
591   if (auto *TD = dyn_cast<TemplateDecl>(D))
592     D = TD->getTemplatedDecl();
593   if (D) {
594     if (auto *VD = dyn_cast<VarDecl>(D))
595       return VD->getStorageClass();
596     if (auto *FD = dyn_cast<FunctionDecl>(D))
597       return FD->getStorageClass();
598   }
599   return SC_None;
600 }
601 
602 LinkageInfo
603 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
604                                             LVComputationKind computation,
605                                             bool IgnoreVarTypeLinkage) {
606   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
607          "Not a name having namespace scope");
608   ASTContext &Context = D->getASTContext();
609   const auto *Var = dyn_cast<VarDecl>(D);
610 
611   // C++ [basic.link]p3:
612   //   A name having namespace scope (3.3.6) has internal linkage if it
613   //   is the name of
614 
615   if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) ||
616       (Context.getLangOpts().C23 && Var && Var->isConstexpr())) {
617     // - a variable, variable template, function, or function template
618     //   that is explicitly declared static; or
619     // (This bullet corresponds to C99 6.2.2p3.)
620 
621     // C23 6.2.2p3
622     // If the declaration of a file scope identifier for
623     // an object contains any of the storage-class specifiers static or
624     // constexpr then the identifier has internal linkage.
625     return LinkageInfo::internal();
626   }
627 
628   if (Var) {
629     // - a non-template variable of non-volatile const-qualified type, unless
630     //   - it is explicitly declared extern, or
631     //   - it is declared in the purview of a module interface unit
632     //     (outside the private-module-fragment, if any) or module partition, or
633     //   - it is inline, or
634     //   - it was previously declared and the prior declaration did not have
635     //     internal linkage
636     // (There is no equivalent in C99.)
637     if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
638         !Var->getType().isVolatileQualified() && !Var->isInline() &&
639         ![Var]() {
640           // Check if it is module purview except private module fragment
641           // and implementation unit.
642           if (auto *M = Var->getOwningModule())
643             return M->isInterfaceOrPartition() || M->isImplicitGlobalModule();
644           return false;
645         }() &&
646         !isa<VarTemplateSpecializationDecl>(Var) &&
647         !Var->getDescribedVarTemplate()) {
648       const VarDecl *PrevVar = Var->getPreviousDecl();
649       if (PrevVar)
650         return getLVForDecl(PrevVar, computation);
651 
652       if (Var->getStorageClass() != SC_Extern &&
653           Var->getStorageClass() != SC_PrivateExtern &&
654           !isSingleLineLanguageLinkage(*Var))
655         return LinkageInfo::internal();
656     }
657 
658     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
659          PrevVar = PrevVar->getPreviousDecl()) {
660       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
661           Var->getStorageClass() == SC_None)
662         return getDeclLinkageAndVisibility(PrevVar);
663       // Explicitly declared static.
664       if (PrevVar->getStorageClass() == SC_Static)
665         return LinkageInfo::internal();
666     }
667   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668     //   - a data member of an anonymous union.
669     const VarDecl *VD = IFD->getVarDecl();
670     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
671     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
672   }
673   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
674 
675   // FIXME: This gives internal linkage to names that should have no linkage
676   // (those not covered by [basic.link]p6).
677   if (D->isInAnonymousNamespace()) {
678     const auto *Var = dyn_cast<VarDecl>(D);
679     const auto *Func = dyn_cast<FunctionDecl>(D);
680     // FIXME: The check for extern "C" here is not justified by the standard
681     // wording, but we retain it from the pre-DR1113 model to avoid breaking
682     // code.
683     //
684     // C++11 [basic.link]p4:
685     //   An unnamed namespace or a namespace declared directly or indirectly
686     //   within an unnamed namespace has internal linkage.
687     if ((!Var || !isFirstInExternCContext(Var)) &&
688         (!Func || !isFirstInExternCContext(Func)))
689       return LinkageInfo::internal();
690   }
691 
692   // Set up the defaults.
693 
694   // C99 6.2.2p5:
695   //   If the declaration of an identifier for an object has file
696   //   scope and no storage-class specifier, its linkage is
697   //   external.
698   LinkageInfo LV = getExternalLinkageFor(D);
699 
700   if (!hasExplicitVisibilityAlready(computation)) {
701     if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
702       LV.mergeVisibility(*Vis, true);
703     } else {
704       // If we're declared in a namespace with a visibility attribute,
705       // use that namespace's visibility, and it still counts as explicit.
706       for (const DeclContext *DC = D->getDeclContext();
707            !isa<TranslationUnitDecl>(DC);
708            DC = DC->getParent()) {
709         const auto *ND = dyn_cast<NamespaceDecl>(DC);
710         if (!ND) continue;
711         if (std::optional<Visibility> Vis =
712                 getExplicitVisibility(ND, computation)) {
713           LV.mergeVisibility(*Vis, true);
714           break;
715         }
716       }
717     }
718 
719     // Add in global settings if the above didn't give us direct visibility.
720     if (!LV.isVisibilityExplicit()) {
721       // Use global type/value visibility as appropriate.
722       Visibility globalVisibility =
723           computation.isValueVisibility()
724               ? Context.getLangOpts().getValueVisibilityMode()
725               : Context.getLangOpts().getTypeVisibilityMode();
726       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
727 
728       // If we're paying attention to global visibility, apply
729       // -finline-visibility-hidden if this is an inline method.
730       if (useInlineVisibilityHidden(D))
731         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
732     }
733   }
734 
735   // C++ [basic.link]p4:
736 
737   //   A name having namespace scope that has not been given internal linkage
738   //   above and that is the name of
739   //   [...bullets...]
740   //   has its linkage determined as follows:
741   //     - if the enclosing namespace has internal linkage, the name has
742   //       internal linkage; [handled above]
743   //     - otherwise, if the declaration of the name is attached to a named
744   //       module and is not exported, the name has module linkage;
745   //     - otherwise, the name has external linkage.
746   // LV is currently set up to handle the last two bullets.
747   //
748   //   The bullets are:
749 
750   //     - a variable; or
751   if (const auto *Var = dyn_cast<VarDecl>(D)) {
752     // GCC applies the following optimization to variables and static
753     // data members, but not to functions:
754     //
755     // Modify the variable's LV by the LV of its type unless this is
756     // C or extern "C".  This follows from [basic.link]p9:
757     //   A type without linkage shall not be used as the type of a
758     //   variable or function with external linkage unless
759     //    - the entity has C language linkage, or
760     //    - the entity is declared within an unnamed namespace, or
761     //    - the entity is not used or is defined in the same
762     //      translation unit.
763     // and [basic.link]p10:
764     //   ...the types specified by all declarations referring to a
765     //   given variable or function shall be identical...
766     // C does not have an equivalent rule.
767     //
768     // Ignore this if we've got an explicit attribute;  the user
769     // probably knows what they're doing.
770     //
771     // Note that we don't want to make the variable non-external
772     // because of this, but unique-external linkage suits us.
773 
774     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
775         !IgnoreVarTypeLinkage) {
776       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
777       if (!isExternallyVisible(TypeLV.getLinkage()))
778         return LinkageInfo::uniqueExternal();
779       if (!LV.isVisibilityExplicit())
780         LV.mergeVisibility(TypeLV);
781     }
782 
783     if (Var->getStorageClass() == SC_PrivateExtern)
784       LV.mergeVisibility(HiddenVisibility, true);
785 
786     // Note that Sema::MergeVarDecl already takes care of implementing
787     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
788     // to do it here.
789 
790     // As per function and class template specializations (below),
791     // consider LV for the template and template arguments.  We're at file
792     // scope, so we do not need to worry about nested specializations.
793     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
794       mergeTemplateLV(LV, spec, computation);
795     }
796 
797   //     - a function; or
798   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
799     // In theory, we can modify the function's LV by the LV of its
800     // type unless it has C linkage (see comment above about variables
801     // for justification).  In practice, GCC doesn't do this, so it's
802     // just too painful to make work.
803 
804     if (Function->getStorageClass() == SC_PrivateExtern)
805       LV.mergeVisibility(HiddenVisibility, true);
806 
807     // OpenMP target declare device functions are not callable from the host so
808     // they should not be exported from the device image. This applies to all
809     // functions as the host-callable kernel functions are emitted at codegen.
810     if (Context.getLangOpts().OpenMP &&
811         Context.getLangOpts().OpenMPIsTargetDevice &&
812         ((Context.getTargetInfo().getTriple().isAMDGPU() ||
813           Context.getTargetInfo().getTriple().isNVPTX()) ||
814          OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
815       LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
816 
817     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
818     // merging storage classes and visibility attributes, so we don't have to
819     // look at previous decls in here.
820 
821     // In C++, then if the type of the function uses a type with
822     // unique-external linkage, it's not legally usable from outside
823     // this translation unit.  However, we should use the C linkage
824     // rules instead for extern "C" declarations.
825     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
826       // Only look at the type-as-written. Otherwise, deducing the return type
827       // of a function could change its linkage.
828       QualType TypeAsWritten = Function->getType();
829       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
830         TypeAsWritten = TSI->getType();
831       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
832         return LinkageInfo::uniqueExternal();
833     }
834 
835     // Consider LV from the template and the template arguments.
836     // We're at file scope, so we do not need to worry about nested
837     // specializations.
838     if (FunctionTemplateSpecializationInfo *specInfo
839                                = Function->getTemplateSpecializationInfo()) {
840       mergeTemplateLV(LV, Function, specInfo, computation);
841     }
842 
843   //     - a named class (Clause 9), or an unnamed class defined in a
844   //       typedef declaration in which the class has the typedef name
845   //       for linkage purposes (7.1.3); or
846   //     - a named enumeration (7.2), or an unnamed enumeration
847   //       defined in a typedef declaration in which the enumeration
848   //       has the typedef name for linkage purposes (7.1.3); or
849   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
850     // Unnamed tags have no linkage.
851     if (!Tag->hasNameForLinkage())
852       return LinkageInfo::none();
853 
854     // If this is a class template specialization, consider the
855     // linkage of the template and template arguments.  We're at file
856     // scope, so we do not need to worry about nested specializations.
857     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
858       mergeTemplateLV(LV, spec, computation);
859     }
860 
861   // FIXME: This is not part of the C++ standard any more.
862   //     - an enumerator belonging to an enumeration with external linkage; or
863   } else if (isa<EnumConstantDecl>(D)) {
864     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
865                                       computation);
866     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
867       return LinkageInfo::none();
868     LV.merge(EnumLV);
869 
870   //     - a template
871   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
872     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
873     LinkageInfo tempLV =
874       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
875     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
876 
877   //     An unnamed namespace or a namespace declared directly or indirectly
878   //     within an unnamed namespace has internal linkage. All other namespaces
879   //     have external linkage.
880   //
881   // We handled names in anonymous namespaces above.
882   } else if (isa<NamespaceDecl>(D)) {
883     return LV;
884 
885   // By extension, we assign external linkage to Objective-C
886   // interfaces.
887   } else if (isa<ObjCInterfaceDecl>(D)) {
888     // fallout
889 
890   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
891     // A typedef declaration has linkage if it gives a type a name for
892     // linkage purposes.
893     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
894       return LinkageInfo::none();
895 
896   } else if (isa<MSGuidDecl>(D)) {
897     // A GUID behaves like an inline variable with external linkage. Fall
898     // through.
899 
900   // Everything not covered here has no linkage.
901   } else {
902     return LinkageInfo::none();
903   }
904 
905   // If we ended up with non-externally-visible linkage, visibility should
906   // always be default.
907   if (!isExternallyVisible(LV.getLinkage()))
908     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
909 
910   return LV;
911 }
912 
913 LinkageInfo
914 LinkageComputer::getLVForClassMember(const NamedDecl *D,
915                                      LVComputationKind computation,
916                                      bool IgnoreVarTypeLinkage) {
917   // Only certain class members have linkage.  Note that fields don't
918   // really have linkage, but it's convenient to say they do for the
919   // purposes of calculating linkage of pointer-to-data-member
920   // template arguments.
921   //
922   // Templates also don't officially have linkage, but since we ignore
923   // the C++ standard and look at template arguments when determining
924   // linkage and visibility of a template specialization, we might hit
925   // a template template argument that way. If we do, we need to
926   // consider its linkage.
927   if (!(isa<CXXMethodDecl>(D) ||
928         isa<VarDecl>(D) ||
929         isa<FieldDecl>(D) ||
930         isa<IndirectFieldDecl>(D) ||
931         isa<TagDecl>(D) ||
932         isa<TemplateDecl>(D)))
933     return LinkageInfo::none();
934 
935   LinkageInfo LV;
936 
937   // If we have an explicit visibility attribute, merge that in.
938   if (!hasExplicitVisibilityAlready(computation)) {
939     if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
940       LV.mergeVisibility(*Vis, true);
941     // If we're paying attention to global visibility, apply
942     // -finline-visibility-hidden if this is an inline method.
943     //
944     // Note that we do this before merging information about
945     // the class visibility.
946     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
947       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
948   }
949 
950   // If this class member has an explicit visibility attribute, the only
951   // thing that can change its visibility is the template arguments, so
952   // only look for them when processing the class.
953   LVComputationKind classComputation = computation;
954   if (LV.isVisibilityExplicit())
955     classComputation = withExplicitVisibilityAlready(computation);
956 
957   LinkageInfo classLV =
958     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
959   // The member has the same linkage as the class. If that's not externally
960   // visible, we don't need to compute anything about the linkage.
961   // FIXME: If we're only computing linkage, can we bail out here?
962   if (!isExternallyVisible(classLV.getLinkage()))
963     return classLV;
964 
965 
966   // Otherwise, don't merge in classLV yet, because in certain cases
967   // we need to completely ignore the visibility from it.
968 
969   // Specifically, if this decl exists and has an explicit attribute.
970   const NamedDecl *explicitSpecSuppressor = nullptr;
971 
972   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
973     // Only look at the type-as-written. Otherwise, deducing the return type
974     // of a function could change its linkage.
975     QualType TypeAsWritten = MD->getType();
976     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
977       TypeAsWritten = TSI->getType();
978     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
979       return LinkageInfo::uniqueExternal();
980 
981     // If this is a method template specialization, use the linkage for
982     // the template parameters and arguments.
983     if (FunctionTemplateSpecializationInfo *spec
984            = MD->getTemplateSpecializationInfo()) {
985       mergeTemplateLV(LV, MD, spec, computation);
986       if (spec->isExplicitSpecialization()) {
987         explicitSpecSuppressor = MD;
988       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
989         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
990       }
991     } else if (isExplicitMemberSpecialization(MD)) {
992       explicitSpecSuppressor = MD;
993     }
994 
995     // OpenMP target declare device functions are not callable from the host so
996     // they should not be exported from the device image. This applies to all
997     // functions as the host-callable kernel functions are emitted at codegen.
998     ASTContext &Context = D->getASTContext();
999     if (Context.getLangOpts().OpenMP &&
1000         Context.getLangOpts().OpenMPIsTargetDevice &&
1001         ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1002           Context.getTargetInfo().getTriple().isNVPTX()) ||
1003          OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1004       LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1005 
1006   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1007     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1008       mergeTemplateLV(LV, spec, computation);
1009       if (spec->isExplicitSpecialization()) {
1010         explicitSpecSuppressor = spec;
1011       } else {
1012         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1013         if (isExplicitMemberSpecialization(temp)) {
1014           explicitSpecSuppressor = temp->getTemplatedDecl();
1015         }
1016       }
1017     } else if (isExplicitMemberSpecialization(RD)) {
1018       explicitSpecSuppressor = RD;
1019     }
1020 
1021   // Static data members.
1022   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1023     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1024       mergeTemplateLV(LV, spec, computation);
1025 
1026     // Modify the variable's linkage by its type, but ignore the
1027     // type's visibility unless it's a definition.
1028     if (!IgnoreVarTypeLinkage) {
1029       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1030       // FIXME: If the type's linkage is not externally visible, we can
1031       // give this static data member UniqueExternalLinkage.
1032       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1033         LV.mergeVisibility(typeLV);
1034       LV.mergeExternalVisibility(typeLV);
1035     }
1036 
1037     if (isExplicitMemberSpecialization(VD)) {
1038       explicitSpecSuppressor = VD;
1039     }
1040 
1041   // Template members.
1042   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1043     bool considerVisibility =
1044       (!LV.isVisibilityExplicit() &&
1045        !classLV.isVisibilityExplicit() &&
1046        !hasExplicitVisibilityAlready(computation));
1047     LinkageInfo tempLV =
1048       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1049     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1050 
1051     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1052       if (isExplicitMemberSpecialization(redeclTemp)) {
1053         explicitSpecSuppressor = temp->getTemplatedDecl();
1054       }
1055     }
1056   }
1057 
1058   // We should never be looking for an attribute directly on a template.
1059   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1060 
1061   // If this member is an explicit member specialization, and it has
1062   // an explicit attribute, ignore visibility from the parent.
1063   bool considerClassVisibility = true;
1064   if (explicitSpecSuppressor &&
1065       // optimization: hasDVA() is true only with explicit visibility.
1066       LV.isVisibilityExplicit() &&
1067       classLV.getVisibility() != DefaultVisibility &&
1068       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1069     considerClassVisibility = false;
1070   }
1071 
1072   // Finally, merge in information from the class.
1073   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1074   return LV;
1075 }
1076 
1077 void NamedDecl::anchor() {}
1078 
1079 bool NamedDecl::isLinkageValid() const {
1080   if (!hasCachedLinkage())
1081     return true;
1082 
1083   Linkage L = LinkageComputer{}
1084                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1085                   .getLinkage();
1086   return L == getCachedLinkage();
1087 }
1088 
1089 bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {
1090   // [C++2c] [basic.scope.scope]/p5
1091   // A declaration is name-independent if its name is _ and it declares
1092   // - a variable with automatic storage duration,
1093   // - a structured binding not inhabiting a namespace scope,
1094   // - the variable introduced by an init-capture
1095   // - or a non-static data member.
1096 
1097   if (!LangOpts.CPlusPlus || !getIdentifier() ||
1098       !getIdentifier()->isPlaceholder())
1099     return false;
1100   if (isa<FieldDecl>(this))
1101     return true;
1102   if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {
1103     if (!getDeclContext()->isFunctionOrMethod() &&
1104         !getDeclContext()->isRecord())
1105       return false;
1106     const VarDecl *VD = IFD->getVarDecl();
1107     return !VD || VD->getStorageDuration() == SD_Automatic;
1108   }
1109   // and it declares a variable with automatic storage duration
1110   if (const auto *VD = dyn_cast<VarDecl>(this)) {
1111     if (isa<ParmVarDecl>(VD))
1112       return false;
1113     if (VD->isInitCapture())
1114       return true;
1115     return VD->getStorageDuration() == StorageDuration::SD_Automatic;
1116   }
1117   if (const auto *BD = dyn_cast<BindingDecl>(this);
1118       BD && getDeclContext()->isFunctionOrMethod()) {
1119     const VarDecl *VD = BD->getHoldingVar();
1120     return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic;
1121   }
1122   return false;
1123 }
1124 
1125 ReservedIdentifierStatus
1126 NamedDecl::isReserved(const LangOptions &LangOpts) const {
1127   const IdentifierInfo *II = getIdentifier();
1128 
1129   // This triggers at least for CXXLiteralIdentifiers, which we already checked
1130   // at lexing time.
1131   if (!II)
1132     return ReservedIdentifierStatus::NotReserved;
1133 
1134   ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1135   if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1136     // This name is only reserved at global scope. Check if this declaration
1137     // conflicts with a global scope declaration.
1138     if (isa<ParmVarDecl>(this) || isTemplateParameter())
1139       return ReservedIdentifierStatus::NotReserved;
1140 
1141     // C++ [dcl.link]/7:
1142     //   Two declarations [conflict] if [...] one declares a function or
1143     //   variable with C language linkage, and the other declares [...] a
1144     //   variable that belongs to the global scope.
1145     //
1146     // Therefore names that are reserved at global scope are also reserved as
1147     // names of variables and functions with C language linkage.
1148     const DeclContext *DC = getDeclContext()->getRedeclContext();
1149     if (DC->isTranslationUnit())
1150       return Status;
1151     if (auto *VD = dyn_cast<VarDecl>(this))
1152       if (VD->isExternC())
1153         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1154     if (auto *FD = dyn_cast<FunctionDecl>(this))
1155       if (FD->isExternC())
1156         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1157     return ReservedIdentifierStatus::NotReserved;
1158   }
1159 
1160   return Status;
1161 }
1162 
1163 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1164   StringRef name = getName();
1165   if (name.empty()) return SFF_None;
1166 
1167   if (name.front() == 'C')
1168     if (name == "CFStringCreateWithFormat" ||
1169         name == "CFStringCreateWithFormatAndArguments" ||
1170         name == "CFStringAppendFormat" ||
1171         name == "CFStringAppendFormatAndArguments")
1172       return SFF_CFString;
1173   return SFF_None;
1174 }
1175 
1176 Linkage NamedDecl::getLinkageInternal() const {
1177   // We don't care about visibility here, so ask for the cheapest
1178   // possible visibility analysis.
1179   return LinkageComputer{}
1180       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1181       .getLinkage();
1182 }
1183 
1184 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
1185   // FIXME: Handle isModulePrivate.
1186   switch (D->getModuleOwnershipKind()) {
1187   case Decl::ModuleOwnershipKind::Unowned:
1188   case Decl::ModuleOwnershipKind::ReachableWhenImported:
1189   case Decl::ModuleOwnershipKind::ModulePrivate:
1190     return false;
1191   case Decl::ModuleOwnershipKind::Visible:
1192   case Decl::ModuleOwnershipKind::VisibleWhenImported:
1193     return D->isInNamedModule();
1194   }
1195   llvm_unreachable("unexpected module ownership kind");
1196 }
1197 
1198 /// Get the linkage from a semantic point of view. Entities in
1199 /// anonymous namespaces are external (in c++98).
1200 Linkage NamedDecl::getFormalLinkage() const {
1201   Linkage InternalLinkage = getLinkageInternal();
1202 
1203   // C++ [basic.link]p4.8:
1204   //   - if the declaration of the name is attached to a named module and is not
1205   //   exported
1206   //     the name has module linkage;
1207   //
1208   // [basic.namespace.general]/p2
1209   //   A namespace is never attached to a named module and never has a name with
1210   //   module linkage.
1211   if (isInNamedModule() && InternalLinkage == Linkage::External &&
1212       !isExportedFromModuleInterfaceUnit(
1213           cast<NamedDecl>(this->getCanonicalDecl())) &&
1214       !isa<NamespaceDecl>(this))
1215     InternalLinkage = Linkage::Module;
1216 
1217   return clang::getFormalLinkage(InternalLinkage);
1218 }
1219 
1220 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1221   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1222 }
1223 
1224 static std::optional<Visibility>
1225 getExplicitVisibilityAux(const NamedDecl *ND,
1226                          NamedDecl::ExplicitVisibilityKind kind,
1227                          bool IsMostRecent) {
1228   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1229 
1230   // Check the declaration itself first.
1231   if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1232     return V;
1233 
1234   // If this is a member class of a specialization of a class template
1235   // and the corresponding decl has explicit visibility, use that.
1236   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1237     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1238     if (InstantiatedFrom)
1239       return getVisibilityOf(InstantiatedFrom, kind);
1240   }
1241 
1242   // If there wasn't explicit visibility there, and this is a
1243   // specialization of a class template, check for visibility
1244   // on the pattern.
1245   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1246     // Walk all the template decl till this point to see if there are
1247     // explicit visibility attributes.
1248     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1249     while (TD != nullptr) {
1250       auto Vis = getVisibilityOf(TD, kind);
1251       if (Vis != std::nullopt)
1252         return Vis;
1253       TD = TD->getPreviousDecl();
1254     }
1255     return std::nullopt;
1256   }
1257 
1258   // Use the most recent declaration.
1259   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1260     const NamedDecl *MostRecent = ND->getMostRecentDecl();
1261     if (MostRecent != ND)
1262       return getExplicitVisibilityAux(MostRecent, kind, true);
1263   }
1264 
1265   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1266     if (Var->isStaticDataMember()) {
1267       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1268       if (InstantiatedFrom)
1269         return getVisibilityOf(InstantiatedFrom, kind);
1270     }
1271 
1272     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1273       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1274                              kind);
1275 
1276     return std::nullopt;
1277   }
1278   // Also handle function template specializations.
1279   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1280     // If the function is a specialization of a template with an
1281     // explicit visibility attribute, use that.
1282     if (FunctionTemplateSpecializationInfo *templateInfo
1283           = fn->getTemplateSpecializationInfo())
1284       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1285                              kind);
1286 
1287     // If the function is a member of a specialization of a class template
1288     // and the corresponding decl has explicit visibility, use that.
1289     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1290     if (InstantiatedFrom)
1291       return getVisibilityOf(InstantiatedFrom, kind);
1292 
1293     return std::nullopt;
1294   }
1295 
1296   // The visibility of a template is stored in the templated decl.
1297   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1298     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1299 
1300   return std::nullopt;
1301 }
1302 
1303 std::optional<Visibility>
1304 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1305   return getExplicitVisibilityAux(this, kind, false);
1306 }
1307 
1308 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1309                                              Decl *ContextDecl,
1310                                              LVComputationKind computation) {
1311   // This lambda has its linkage/visibility determined by its owner.
1312   const NamedDecl *Owner;
1313   if (!ContextDecl)
1314     Owner = dyn_cast<NamedDecl>(DC);
1315   else if (isa<ParmVarDecl>(ContextDecl))
1316     Owner =
1317         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1318   else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1319     // Replace with the concept's owning decl, which is either a namespace or a
1320     // TU, so this needs a dyn_cast.
1321     Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1322   } else {
1323     Owner = cast<NamedDecl>(ContextDecl);
1324   }
1325 
1326   if (!Owner)
1327     return LinkageInfo::none();
1328 
1329   // If the owner has a deduced type, we need to skip querying the linkage and
1330   // visibility of that type, because it might involve this closure type.  The
1331   // only effect of this is that we might give a lambda VisibleNoLinkage rather
1332   // than NoLinkage when we don't strictly need to, which is benign.
1333   auto *VD = dyn_cast<VarDecl>(Owner);
1334   LinkageInfo OwnerLV =
1335       VD && VD->getType()->getContainedDeducedType()
1336           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1337           : getLVForDecl(Owner, computation);
1338 
1339   // A lambda never formally has linkage. But if the owner is externally
1340   // visible, then the lambda is too. We apply the same rules to blocks.
1341   if (!isExternallyVisible(OwnerLV.getLinkage()))
1342     return LinkageInfo::none();
1343   return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(),
1344                      OwnerLV.isVisibilityExplicit());
1345 }
1346 
1347 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1348                                                LVComputationKind computation) {
1349   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1350     if (Function->isInAnonymousNamespace() &&
1351         !isFirstInExternCContext(Function))
1352       return LinkageInfo::internal();
1353 
1354     // This is a "void f();" which got merged with a file static.
1355     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1356       return LinkageInfo::internal();
1357 
1358     LinkageInfo LV;
1359     if (!hasExplicitVisibilityAlready(computation)) {
1360       if (std::optional<Visibility> Vis =
1361               getExplicitVisibility(Function, computation))
1362         LV.mergeVisibility(*Vis, true);
1363     }
1364 
1365     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1366     // merging storage classes and visibility attributes, so we don't have to
1367     // look at previous decls in here.
1368 
1369     return LV;
1370   }
1371 
1372   if (const auto *Var = dyn_cast<VarDecl>(D)) {
1373     if (Var->hasExternalStorage()) {
1374       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1375         return LinkageInfo::internal();
1376 
1377       LinkageInfo LV;
1378       if (Var->getStorageClass() == SC_PrivateExtern)
1379         LV.mergeVisibility(HiddenVisibility, true);
1380       else if (!hasExplicitVisibilityAlready(computation)) {
1381         if (std::optional<Visibility> Vis =
1382                 getExplicitVisibility(Var, computation))
1383           LV.mergeVisibility(*Vis, true);
1384       }
1385 
1386       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1387         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1388         if (PrevLV.getLinkage() != Linkage::Invalid)
1389           LV.setLinkage(PrevLV.getLinkage());
1390         LV.mergeVisibility(PrevLV);
1391       }
1392 
1393       return LV;
1394     }
1395 
1396     if (!Var->isStaticLocal())
1397       return LinkageInfo::none();
1398   }
1399 
1400   ASTContext &Context = D->getASTContext();
1401   if (!Context.getLangOpts().CPlusPlus)
1402     return LinkageInfo::none();
1403 
1404   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1405   if (!OuterD || OuterD->isInvalidDecl())
1406     return LinkageInfo::none();
1407 
1408   LinkageInfo LV;
1409   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1410     if (!BD->getBlockManglingNumber())
1411       return LinkageInfo::none();
1412 
1413     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1414                          BD->getBlockManglingContextDecl(), computation);
1415   } else {
1416     const auto *FD = cast<FunctionDecl>(OuterD);
1417     if (!FD->isInlined() &&
1418         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1419       return LinkageInfo::none();
1420 
1421     // If a function is hidden by -fvisibility-inlines-hidden option and
1422     // is not explicitly attributed as a hidden function,
1423     // we should not make static local variables in the function hidden.
1424     LV = getLVForDecl(FD, computation);
1425     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1426         !LV.isVisibilityExplicit() &&
1427         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1428       assert(cast<VarDecl>(D)->isStaticLocal());
1429       // If this was an implicitly hidden inline method, check again for
1430       // explicit visibility on the parent class, and use that for static locals
1431       // if present.
1432       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1433         LV = getLVForDecl(MD->getParent(), computation);
1434       if (!LV.isVisibilityExplicit()) {
1435         Visibility globalVisibility =
1436             computation.isValueVisibility()
1437                 ? Context.getLangOpts().getValueVisibilityMode()
1438                 : Context.getLangOpts().getTypeVisibilityMode();
1439         return LinkageInfo(Linkage::VisibleNone, globalVisibility,
1440                            /*visibilityExplicit=*/false);
1441       }
1442     }
1443   }
1444   if (!isExternallyVisible(LV.getLinkage()))
1445     return LinkageInfo::none();
1446   return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(),
1447                      LV.isVisibilityExplicit());
1448 }
1449 
1450 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1451                                               LVComputationKind computation,
1452                                               bool IgnoreVarTypeLinkage) {
1453   // Internal_linkage attribute overrides other considerations.
1454   if (D->hasAttr<InternalLinkageAttr>())
1455     return LinkageInfo::internal();
1456 
1457   // Objective-C: treat all Objective-C declarations as having external
1458   // linkage.
1459   switch (D->getKind()) {
1460     default:
1461       break;
1462 
1463     // Per C++ [basic.link]p2, only the names of objects, references,
1464     // functions, types, templates, namespaces, and values ever have linkage.
1465     //
1466     // Note that the name of a typedef, namespace alias, using declaration,
1467     // and so on are not the name of the corresponding type, namespace, or
1468     // declaration, so they do *not* have linkage.
1469     case Decl::ImplicitParam:
1470     case Decl::Label:
1471     case Decl::NamespaceAlias:
1472     case Decl::ParmVar:
1473     case Decl::Using:
1474     case Decl::UsingEnum:
1475     case Decl::UsingShadow:
1476     case Decl::UsingDirective:
1477       return LinkageInfo::none();
1478 
1479     case Decl::EnumConstant:
1480       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1481       if (D->getASTContext().getLangOpts().CPlusPlus)
1482         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1483       return LinkageInfo::visible_none();
1484 
1485     case Decl::Typedef:
1486     case Decl::TypeAlias:
1487       // A typedef declaration has linkage if it gives a type a name for
1488       // linkage purposes.
1489       if (!cast<TypedefNameDecl>(D)
1490                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1491         return LinkageInfo::none();
1492       break;
1493 
1494     case Decl::TemplateTemplateParm: // count these as external
1495     case Decl::NonTypeTemplateParm:
1496     case Decl::ObjCAtDefsField:
1497     case Decl::ObjCCategory:
1498     case Decl::ObjCCategoryImpl:
1499     case Decl::ObjCCompatibleAlias:
1500     case Decl::ObjCImplementation:
1501     case Decl::ObjCMethod:
1502     case Decl::ObjCProperty:
1503     case Decl::ObjCPropertyImpl:
1504     case Decl::ObjCProtocol:
1505       return getExternalLinkageFor(D);
1506 
1507     case Decl::CXXRecord: {
1508       const auto *Record = cast<CXXRecordDecl>(D);
1509       if (Record->isLambda()) {
1510         if (Record->hasKnownLambdaInternalLinkage() ||
1511             !Record->getLambdaManglingNumber()) {
1512           // This lambda has no mangling number, so it's internal.
1513           return LinkageInfo::internal();
1514         }
1515 
1516         return getLVForClosure(
1517                   Record->getDeclContext()->getRedeclContext(),
1518                   Record->getLambdaContextDecl(), computation);
1519       }
1520 
1521       break;
1522     }
1523 
1524     case Decl::TemplateParamObject: {
1525       // The template parameter object can be referenced from anywhere its type
1526       // and value can be referenced.
1527       auto *TPO = cast<TemplateParamObjectDecl>(D);
1528       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1529       LV.merge(getLVForValue(TPO->getValue(), computation));
1530       return LV;
1531     }
1532   }
1533 
1534   // Handle linkage for namespace-scope names.
1535   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1536     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1537 
1538   // C++ [basic.link]p5:
1539   //   In addition, a member function, static data member, a named
1540   //   class or enumeration of class scope, or an unnamed class or
1541   //   enumeration defined in a class-scope typedef declaration such
1542   //   that the class or enumeration has the typedef name for linkage
1543   //   purposes (7.1.3), has external linkage if the name of the class
1544   //   has external linkage.
1545   if (D->getDeclContext()->isRecord())
1546     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1547 
1548   // C++ [basic.link]p6:
1549   //   The name of a function declared in block scope and the name of
1550   //   an object declared by a block scope extern declaration have
1551   //   linkage. If there is a visible declaration of an entity with
1552   //   linkage having the same name and type, ignoring entities
1553   //   declared outside the innermost enclosing namespace scope, the
1554   //   block scope declaration declares that same entity and receives
1555   //   the linkage of the previous declaration. If there is more than
1556   //   one such matching entity, the program is ill-formed. Otherwise,
1557   //   if no matching entity is found, the block scope entity receives
1558   //   external linkage.
1559   if (D->getDeclContext()->isFunctionOrMethod())
1560     return getLVForLocalDecl(D, computation);
1561 
1562   // C++ [basic.link]p6:
1563   //   Names not covered by these rules have no linkage.
1564   return LinkageInfo::none();
1565 }
1566 
1567 /// getLVForDecl - Get the linkage and visibility for the given declaration.
1568 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1569                                           LVComputationKind computation) {
1570   // Internal_linkage attribute overrides other considerations.
1571   if (D->hasAttr<InternalLinkageAttr>())
1572     return LinkageInfo::internal();
1573 
1574   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1575     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1576 
1577   if (std::optional<LinkageInfo> LI = lookup(D, computation))
1578     return *LI;
1579 
1580   LinkageInfo LV = computeLVForDecl(D, computation);
1581   if (D->hasCachedLinkage())
1582     assert(D->getCachedLinkage() == LV.getLinkage());
1583 
1584   D->setCachedLinkage(LV.getLinkage());
1585   cache(D, computation, LV);
1586 
1587 #ifndef NDEBUG
1588   // In C (because of gnu inline) and in c++ with microsoft extensions an
1589   // static can follow an extern, so we can have two decls with different
1590   // linkages.
1591   const LangOptions &Opts = D->getASTContext().getLangOpts();
1592   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1593     return LV;
1594 
1595   // We have just computed the linkage for this decl. By induction we know
1596   // that all other computed linkages match, check that the one we just
1597   // computed also does.
1598   NamedDecl *Old = nullptr;
1599   for (auto *I : D->redecls()) {
1600     auto *T = cast<NamedDecl>(I);
1601     if (T == D)
1602       continue;
1603     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1604       Old = T;
1605       break;
1606     }
1607   }
1608   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1609 #endif
1610 
1611   return LV;
1612 }
1613 
1614 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1615   NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1616                                              ? NamedDecl::VisibilityForType
1617                                              : NamedDecl::VisibilityForValue;
1618   LVComputationKind CK(EK);
1619   return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1620                              ? CK.forLinkageOnly()
1621                              : CK);
1622 }
1623 
1624 Module *Decl::getOwningModuleForLinkage() const {
1625   if (isa<NamespaceDecl>(this))
1626     // Namespaces never have module linkage.  It is the entities within them
1627     // that [may] do.
1628     return nullptr;
1629 
1630   Module *M = getOwningModule();
1631   if (!M)
1632     return nullptr;
1633 
1634   switch (M->Kind) {
1635   case Module::ModuleMapModule:
1636     // Module map modules have no special linkage semantics.
1637     return nullptr;
1638 
1639   case Module::ModuleInterfaceUnit:
1640   case Module::ModuleImplementationUnit:
1641   case Module::ModulePartitionInterface:
1642   case Module::ModulePartitionImplementation:
1643     return M;
1644 
1645   case Module::ModuleHeaderUnit:
1646   case Module::ExplicitGlobalModuleFragment:
1647   case Module::ImplicitGlobalModuleFragment:
1648     // The global module shouldn't change the linkage.
1649     return nullptr;
1650 
1651   case Module::PrivateModuleFragment:
1652     // The private module fragment is part of its containing module for linkage
1653     // purposes.
1654     return M->Parent;
1655   }
1656 
1657   llvm_unreachable("unknown module kind");
1658 }
1659 
1660 void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1661   Name.print(OS, Policy);
1662 }
1663 
1664 void NamedDecl::printName(raw_ostream &OS) const {
1665   printName(OS, getASTContext().getPrintingPolicy());
1666 }
1667 
1668 std::string NamedDecl::getQualifiedNameAsString() const {
1669   std::string QualName;
1670   llvm::raw_string_ostream OS(QualName);
1671   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1672   return QualName;
1673 }
1674 
1675 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1676   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1677 }
1678 
1679 void NamedDecl::printQualifiedName(raw_ostream &OS,
1680                                    const PrintingPolicy &P) const {
1681   if (getDeclContext()->isFunctionOrMethod()) {
1682     // We do not print '(anonymous)' for function parameters without name.
1683     printName(OS, P);
1684     return;
1685   }
1686   printNestedNameSpecifier(OS, P);
1687   if (getDeclName())
1688     OS << *this;
1689   else {
1690     // Give the printName override a chance to pick a different name before we
1691     // fall back to "(anonymous)".
1692     SmallString<64> NameBuffer;
1693     llvm::raw_svector_ostream NameOS(NameBuffer);
1694     printName(NameOS, P);
1695     if (NameBuffer.empty())
1696       OS << "(anonymous)";
1697     else
1698       OS << NameBuffer;
1699   }
1700 }
1701 
1702 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1703   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1704 }
1705 
1706 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1707                                          const PrintingPolicy &P) const {
1708   const DeclContext *Ctx = getDeclContext();
1709 
1710   // For ObjC methods and properties, look through categories and use the
1711   // interface as context.
1712   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1713     if (auto *ID = MD->getClassInterface())
1714       Ctx = ID;
1715   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1716     if (auto *MD = PD->getGetterMethodDecl())
1717       if (auto *ID = MD->getClassInterface())
1718         Ctx = ID;
1719   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1720     if (auto *CI = ID->getContainingInterface())
1721       Ctx = CI;
1722   }
1723 
1724   if (Ctx->isFunctionOrMethod())
1725     return;
1726 
1727   using ContextsTy = SmallVector<const DeclContext *, 8>;
1728   ContextsTy Contexts;
1729 
1730   // Collect named contexts.
1731   DeclarationName NameInScope = getDeclName();
1732   for (; Ctx; Ctx = Ctx->getParent()) {
1733     // Suppress anonymous namespace if requested.
1734     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1735         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1736       continue;
1737 
1738     // Suppress inline namespace if it doesn't make the result ambiguous.
1739     if (Ctx->isInlineNamespace() && NameInScope) {
1740       if (P.SuppressInlineNamespace ==
1741               PrintingPolicy::SuppressInlineNamespaceMode::All ||
1742           (P.SuppressInlineNamespace ==
1743                PrintingPolicy::SuppressInlineNamespaceMode::Redundant &&
1744            cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(
1745                NameInScope))) {
1746         continue;
1747       }
1748     }
1749 
1750     // Skip non-named contexts such as linkage specifications and ExportDecls.
1751     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1752     if (!ND)
1753       continue;
1754 
1755     Contexts.push_back(Ctx);
1756     NameInScope = ND->getDeclName();
1757   }
1758 
1759   for (const DeclContext *DC : llvm::reverse(Contexts)) {
1760     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1761       OS << Spec->getName();
1762       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1763       printTemplateArgumentList(
1764           OS, TemplateArgs.asArray(), P,
1765           Spec->getSpecializedTemplate()->getTemplateParameters());
1766     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1767       if (ND->isAnonymousNamespace()) {
1768         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1769                                 : "(anonymous namespace)");
1770       }
1771       else
1772         OS << *ND;
1773     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1774       if (!RD->getIdentifier())
1775         OS << "(anonymous " << RD->getKindName() << ')';
1776       else
1777         OS << *RD;
1778     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1779       const FunctionProtoType *FT = nullptr;
1780       if (FD->hasWrittenPrototype())
1781         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1782 
1783       OS << *FD << '(';
1784       if (FT) {
1785         unsigned NumParams = FD->getNumParams();
1786         for (unsigned i = 0; i < NumParams; ++i) {
1787           if (i)
1788             OS << ", ";
1789           OS << FD->getParamDecl(i)->getType().stream(P);
1790         }
1791 
1792         if (FT->isVariadic()) {
1793           if (NumParams > 0)
1794             OS << ", ";
1795           OS << "...";
1796         }
1797       }
1798       OS << ')';
1799     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1800       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1801       // enumerator is declared in the scope that immediately contains
1802       // the enum-specifier. Each scoped enumerator is declared in the
1803       // scope of the enumeration.
1804       // For the case of unscoped enumerator, do not include in the qualified
1805       // name any information about its enum enclosing scope, as its visibility
1806       // is global.
1807       if (ED->isScoped())
1808         OS << *ED;
1809       else
1810         continue;
1811     } else {
1812       OS << *cast<NamedDecl>(DC);
1813     }
1814     OS << "::";
1815   }
1816 }
1817 
1818 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1819                                      const PrintingPolicy &Policy,
1820                                      bool Qualified) const {
1821   if (Qualified)
1822     printQualifiedName(OS, Policy);
1823   else
1824     printName(OS, Policy);
1825 }
1826 
1827 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1828   return true;
1829 }
1830 static bool isRedeclarableImpl(...) { return false; }
1831 static bool isRedeclarable(Decl::Kind K) {
1832   switch (K) {
1833 #define DECL(Type, Base) \
1834   case Decl::Type: \
1835     return isRedeclarableImpl((Type##Decl *)nullptr);
1836 #define ABSTRACT_DECL(DECL)
1837 #include "clang/AST/DeclNodes.inc"
1838   }
1839   llvm_unreachable("unknown decl kind");
1840 }
1841 
1842 bool NamedDecl::declarationReplaces(const NamedDecl *OldD,
1843                                     bool IsKnownNewer) const {
1844   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1845 
1846   // Never replace one imported declaration with another; we need both results
1847   // when re-exporting.
1848   if (OldD->isFromASTFile() && isFromASTFile())
1849     return false;
1850 
1851   // A kind mismatch implies that the declaration is not replaced.
1852   if (OldD->getKind() != getKind())
1853     return false;
1854 
1855   // For method declarations, we never replace. (Why?)
1856   if (isa<ObjCMethodDecl>(this))
1857     return false;
1858 
1859   // For parameters, pick the newer one. This is either an error or (in
1860   // Objective-C) permitted as an extension.
1861   if (isa<ParmVarDecl>(this))
1862     return true;
1863 
1864   // Inline namespaces can give us two declarations with the same
1865   // name and kind in the same scope but different contexts; we should
1866   // keep both declarations in this case.
1867   if (!this->getDeclContext()->getRedeclContext()->Equals(
1868           OldD->getDeclContext()->getRedeclContext()))
1869     return false;
1870 
1871   // Using declarations can be replaced if they import the same name from the
1872   // same context.
1873   if (const auto *UD = dyn_cast<UsingDecl>(this)) {
1874     ASTContext &Context = getASTContext();
1875     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1876            Context.getCanonicalNestedNameSpecifier(
1877                cast<UsingDecl>(OldD)->getQualifier());
1878   }
1879   if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1880     ASTContext &Context = getASTContext();
1881     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1882            Context.getCanonicalNestedNameSpecifier(
1883                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1884   }
1885 
1886   if (isRedeclarable(getKind())) {
1887     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1888       return false;
1889 
1890     if (IsKnownNewer)
1891       return true;
1892 
1893     // Check whether this is actually newer than OldD. We want to keep the
1894     // newer declaration. This loop will usually only iterate once, because
1895     // OldD is usually the previous declaration.
1896     for (const auto *D : redecls()) {
1897       if (D == OldD)
1898         break;
1899 
1900       // If we reach the canonical declaration, then OldD is not actually older
1901       // than this one.
1902       //
1903       // FIXME: In this case, we should not add this decl to the lookup table.
1904       if (D->isCanonicalDecl())
1905         return false;
1906     }
1907 
1908     // It's a newer declaration of the same kind of declaration in the same
1909     // scope: we want this decl instead of the existing one.
1910     return true;
1911   }
1912 
1913   // In all other cases, we need to keep both declarations in case they have
1914   // different visibility. Any attempt to use the name will result in an
1915   // ambiguity if more than one is visible.
1916   return false;
1917 }
1918 
1919 bool NamedDecl::hasLinkage() const {
1920   switch (getFormalLinkage()) {
1921   case Linkage::Invalid:
1922     llvm_unreachable("Linkage hasn't been computed!");
1923   case Linkage::None:
1924     return false;
1925   case Linkage::Internal:
1926     return true;
1927   case Linkage::UniqueExternal:
1928   case Linkage::VisibleNone:
1929     llvm_unreachable("Non-formal linkage is not allowed here!");
1930   case Linkage::Module:
1931   case Linkage::External:
1932     return true;
1933   }
1934   llvm_unreachable("Unhandled Linkage enum");
1935 }
1936 
1937 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1938   NamedDecl *ND = this;
1939   if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1940     ND = UD->getTargetDecl();
1941 
1942   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1943     return AD->getClassInterface();
1944 
1945   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1946     return AD->getNamespace();
1947 
1948   return ND;
1949 }
1950 
1951 bool NamedDecl::isCXXInstanceMember() const {
1952   if (!isCXXClassMember())
1953     return false;
1954 
1955   const NamedDecl *D = this;
1956   if (isa<UsingShadowDecl>(D))
1957     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1958 
1959   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1960     return true;
1961   if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))
1962     return MD->isInstance();
1963   return false;
1964 }
1965 
1966 //===----------------------------------------------------------------------===//
1967 // DeclaratorDecl Implementation
1968 //===----------------------------------------------------------------------===//
1969 
1970 template <typename DeclT>
1971 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1972   if (decl->getNumTemplateParameterLists() > 0)
1973     return decl->getTemplateParameterList(0)->getTemplateLoc();
1974   return decl->getInnerLocStart();
1975 }
1976 
1977 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1978   TypeSourceInfo *TSI = getTypeSourceInfo();
1979   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1980   return SourceLocation();
1981 }
1982 
1983 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1984   TypeSourceInfo *TSI = getTypeSourceInfo();
1985   if (TSI) return TSI->getTypeLoc().getEndLoc();
1986   return SourceLocation();
1987 }
1988 
1989 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1990   if (QualifierLoc) {
1991     // Make sure the extended decl info is allocated.
1992     if (!hasExtInfo()) {
1993       // Save (non-extended) type source info pointer.
1994       auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
1995       // Allocate external info struct.
1996       DeclInfo = new (getASTContext()) ExtInfo;
1997       // Restore savedTInfo into (extended) decl info.
1998       getExtInfo()->TInfo = savedTInfo;
1999     }
2000     // Set qualifier info.
2001     getExtInfo()->QualifierLoc = QualifierLoc;
2002   } else if (hasExtInfo()) {
2003     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2004     getExtInfo()->QualifierLoc = QualifierLoc;
2005   }
2006 }
2007 
2008 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
2009   assert(TrailingRequiresClause);
2010   // Make sure the extended decl info is allocated.
2011   if (!hasExtInfo()) {
2012     // Save (non-extended) type source info pointer.
2013     auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
2014     // Allocate external info struct.
2015     DeclInfo = new (getASTContext()) ExtInfo;
2016     // Restore savedTInfo into (extended) decl info.
2017     getExtInfo()->TInfo = savedTInfo;
2018   }
2019   // Set requires clause info.
2020   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
2021 }
2022 
2023 void DeclaratorDecl::setTemplateParameterListsInfo(
2024     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2025   assert(!TPLists.empty());
2026   // Make sure the extended decl info is allocated.
2027   if (!hasExtInfo()) {
2028     // Save (non-extended) type source info pointer.
2029     auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
2030     // Allocate external info struct.
2031     DeclInfo = new (getASTContext()) ExtInfo;
2032     // Restore savedTInfo into (extended) decl info.
2033     getExtInfo()->TInfo = savedTInfo;
2034   }
2035   // Set the template parameter lists info.
2036   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
2037 }
2038 
2039 SourceLocation DeclaratorDecl::getOuterLocStart() const {
2040   return getTemplateOrInnerLocStart(this);
2041 }
2042 
2043 // Helper function: returns true if QT is or contains a type
2044 // having a postfix component.
2045 static bool typeIsPostfix(QualType QT) {
2046   while (true) {
2047     const Type* T = QT.getTypePtr();
2048     switch (T->getTypeClass()) {
2049     default:
2050       return false;
2051     case Type::Pointer:
2052       QT = cast<PointerType>(T)->getPointeeType();
2053       break;
2054     case Type::BlockPointer:
2055       QT = cast<BlockPointerType>(T)->getPointeeType();
2056       break;
2057     case Type::MemberPointer:
2058       QT = cast<MemberPointerType>(T)->getPointeeType();
2059       break;
2060     case Type::LValueReference:
2061     case Type::RValueReference:
2062       QT = cast<ReferenceType>(T)->getPointeeType();
2063       break;
2064     case Type::PackExpansion:
2065       QT = cast<PackExpansionType>(T)->getPattern();
2066       break;
2067     case Type::Paren:
2068     case Type::ConstantArray:
2069     case Type::DependentSizedArray:
2070     case Type::IncompleteArray:
2071     case Type::VariableArray:
2072     case Type::FunctionProto:
2073     case Type::FunctionNoProto:
2074       return true;
2075     }
2076   }
2077 }
2078 
2079 SourceRange DeclaratorDecl::getSourceRange() const {
2080   SourceLocation RangeEnd = getLocation();
2081   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2082     // If the declaration has no name or the type extends past the name take the
2083     // end location of the type.
2084     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2085       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2086   }
2087   return SourceRange(getOuterLocStart(), RangeEnd);
2088 }
2089 
2090 void QualifierInfo::setTemplateParameterListsInfo(
2091     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2092   // Free previous template parameters (if any).
2093   if (NumTemplParamLists > 0) {
2094     Context.Deallocate(TemplParamLists);
2095     TemplParamLists = nullptr;
2096     NumTemplParamLists = 0;
2097   }
2098   // Set info on matched template parameter lists (if any).
2099   if (!TPLists.empty()) {
2100     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2101     NumTemplParamLists = TPLists.size();
2102     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2103   }
2104 }
2105 
2106 //===----------------------------------------------------------------------===//
2107 // VarDecl Implementation
2108 //===----------------------------------------------------------------------===//
2109 
2110 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
2111   switch (SC) {
2112   case SC_None:                 break;
2113   case SC_Auto:                 return "auto";
2114   case SC_Extern:               return "extern";
2115   case SC_PrivateExtern:        return "__private_extern__";
2116   case SC_Register:             return "register";
2117   case SC_Static:               return "static";
2118   }
2119 
2120   llvm_unreachable("Invalid storage class");
2121 }
2122 
2123 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2124                  SourceLocation StartLoc, SourceLocation IdLoc,
2125                  const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2126                  StorageClass SC)
2127     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2128       redeclarable_base(C) {
2129   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2130                 "VarDeclBitfields too large!");
2131   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2132                 "ParmVarDeclBitfields too large!");
2133   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2134                 "NonParmVarDeclBitfields too large!");
2135   AllBits = 0;
2136   VarDeclBits.SClass = SC;
2137   // Everything else is implicitly initialized to false.
2138 }
2139 
2140 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,
2141                          SourceLocation IdL, const IdentifierInfo *Id,
2142                          QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2143   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2144 }
2145 
2146 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2147   return new (C, ID)
2148       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2149               QualType(), nullptr, SC_None);
2150 }
2151 
2152 void VarDecl::setStorageClass(StorageClass SC) {
2153   assert(isLegalForVariable(SC));
2154   VarDeclBits.SClass = SC;
2155 }
2156 
2157 VarDecl::TLSKind VarDecl::getTLSKind() const {
2158   switch (VarDeclBits.TSCSpec) {
2159   case TSCS_unspecified:
2160     if (!hasAttr<ThreadAttr>() &&
2161         !(getASTContext().getLangOpts().OpenMPUseTLS &&
2162           getASTContext().getTargetInfo().isTLSSupported() &&
2163           hasAttr<OMPThreadPrivateDeclAttr>()))
2164       return TLS_None;
2165     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2166                 LangOptions::MSVC2015)) ||
2167             hasAttr<OMPThreadPrivateDeclAttr>())
2168                ? TLS_Dynamic
2169                : TLS_Static;
2170   case TSCS___thread: // Fall through.
2171   case TSCS__Thread_local:
2172     return TLS_Static;
2173   case TSCS_thread_local:
2174     return TLS_Dynamic;
2175   }
2176   llvm_unreachable("Unknown thread storage class specifier!");
2177 }
2178 
2179 SourceRange VarDecl::getSourceRange() const {
2180   if (const Expr *Init = getInit()) {
2181     SourceLocation InitEnd = Init->getEndLoc();
2182     // If Init is implicit, ignore its source range and fallback on
2183     // DeclaratorDecl::getSourceRange() to handle postfix elements.
2184     if (InitEnd.isValid() && InitEnd != getLocation())
2185       return SourceRange(getOuterLocStart(), InitEnd);
2186   }
2187   return DeclaratorDecl::getSourceRange();
2188 }
2189 
2190 template<typename T>
2191 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2192   // C++ [dcl.link]p1: All function types, function names with external linkage,
2193   // and variable names with external linkage have a language linkage.
2194   if (!D.hasExternalFormalLinkage())
2195     return NoLanguageLinkage;
2196 
2197   // Language linkage is a C++ concept, but saying that everything else in C has
2198   // C language linkage fits the implementation nicely.
2199   if (!D.getASTContext().getLangOpts().CPlusPlus)
2200     return CLanguageLinkage;
2201 
2202   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2203   // language linkage of the names of class members and the function type of
2204   // class member functions.
2205   const DeclContext *DC = D.getDeclContext();
2206   if (DC->isRecord())
2207     return CXXLanguageLinkage;
2208 
2209   // If the first decl is in an extern "C" context, any other redeclaration
2210   // will have C language linkage. If the first one is not in an extern "C"
2211   // context, we would have reported an error for any other decl being in one.
2212   if (isFirstInExternCContext(&D))
2213     return CLanguageLinkage;
2214   return CXXLanguageLinkage;
2215 }
2216 
2217 template<typename T>
2218 static bool isDeclExternC(const T &D) {
2219   // Since the context is ignored for class members, they can only have C++
2220   // language linkage or no language linkage.
2221   const DeclContext *DC = D.getDeclContext();
2222   if (DC->isRecord()) {
2223     assert(D.getASTContext().getLangOpts().CPlusPlus);
2224     return false;
2225   }
2226 
2227   return D.getLanguageLinkage() == CLanguageLinkage;
2228 }
2229 
2230 LanguageLinkage VarDecl::getLanguageLinkage() const {
2231   return getDeclLanguageLinkage(*this);
2232 }
2233 
2234 bool VarDecl::isExternC() const {
2235   return isDeclExternC(*this);
2236 }
2237 
2238 bool VarDecl::isInExternCContext() const {
2239   return getLexicalDeclContext()->isExternCContext();
2240 }
2241 
2242 bool VarDecl::isInExternCXXContext() const {
2243   return getLexicalDeclContext()->isExternCXXContext();
2244 }
2245 
2246 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2247 
2248 VarDecl::DefinitionKind
2249 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2250   if (isThisDeclarationADemotedDefinition())
2251     return DeclarationOnly;
2252 
2253   // C++ [basic.def]p2:
2254   //   A declaration is a definition unless [...] it contains the 'extern'
2255   //   specifier or a linkage-specification and neither an initializer [...],
2256   //   it declares a non-inline static data member in a class declaration [...],
2257   //   it declares a static data member outside a class definition and the variable
2258   //   was defined within the class with the constexpr specifier [...],
2259   // C++1y [temp.expl.spec]p15:
2260   //   An explicit specialization of a static data member or an explicit
2261   //   specialization of a static data member template is a definition if the
2262   //   declaration includes an initializer; otherwise, it is a declaration.
2263   //
2264   // FIXME: How do you declare (but not define) a partial specialization of
2265   // a static data member template outside the containing class?
2266   if (isStaticDataMember()) {
2267     if (isOutOfLine() &&
2268         !(getCanonicalDecl()->isInline() &&
2269           getCanonicalDecl()->isConstexpr()) &&
2270         (hasInit() ||
2271          // If the first declaration is out-of-line, this may be an
2272          // instantiation of an out-of-line partial specialization of a variable
2273          // template for which we have not yet instantiated the initializer.
2274          (getFirstDecl()->isOutOfLine()
2275               ? getTemplateSpecializationKind() == TSK_Undeclared
2276               : getTemplateSpecializationKind() !=
2277                     TSK_ExplicitSpecialization) ||
2278          isa<VarTemplatePartialSpecializationDecl>(this)))
2279       return Definition;
2280     if (!isOutOfLine() && isInline())
2281       return Definition;
2282     return DeclarationOnly;
2283   }
2284   // C99 6.7p5:
2285   //   A definition of an identifier is a declaration for that identifier that
2286   //   [...] causes storage to be reserved for that object.
2287   // Note: that applies for all non-file-scope objects.
2288   // C99 6.9.2p1:
2289   //   If the declaration of an identifier for an object has file scope and an
2290   //   initializer, the declaration is an external definition for the identifier
2291   if (hasInit())
2292     return Definition;
2293 
2294   if (hasDefiningAttr())
2295     return Definition;
2296 
2297   if (const auto *SAA = getAttr<SelectAnyAttr>())
2298     if (!SAA->isInherited())
2299       return Definition;
2300 
2301   // A variable template specialization (other than a static data member
2302   // template or an explicit specialization) is a declaration until we
2303   // instantiate its initializer.
2304   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2305     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2306         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2307         !VTSD->IsCompleteDefinition)
2308       return DeclarationOnly;
2309   }
2310 
2311   if (hasExternalStorage())
2312     return DeclarationOnly;
2313 
2314   // [dcl.link] p7:
2315   //   A declaration directly contained in a linkage-specification is treated
2316   //   as if it contains the extern specifier for the purpose of determining
2317   //   the linkage of the declared name and whether it is a definition.
2318   if (isSingleLineLanguageLinkage(*this))
2319     return DeclarationOnly;
2320 
2321   // C99 6.9.2p2:
2322   //   A declaration of an object that has file scope without an initializer,
2323   //   and without a storage class specifier or the scs 'static', constitutes
2324   //   a tentative definition.
2325   // No such thing in C++.
2326   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2327     return TentativeDefinition;
2328 
2329   // What's left is (in C, block-scope) declarations without initializers or
2330   // external storage. These are definitions.
2331   return Definition;
2332 }
2333 
2334 VarDecl *VarDecl::getActingDefinition() {
2335   DefinitionKind Kind = isThisDeclarationADefinition();
2336   if (Kind != TentativeDefinition)
2337     return nullptr;
2338 
2339   VarDecl *LastTentative = nullptr;
2340 
2341   // Loop through the declaration chain, starting with the most recent.
2342   for (VarDecl *Decl = getMostRecentDecl(); Decl;
2343        Decl = Decl->getPreviousDecl()) {
2344     Kind = Decl->isThisDeclarationADefinition();
2345     if (Kind == Definition)
2346       return nullptr;
2347     // Record the first (most recent) TentativeDefinition that is encountered.
2348     if (Kind == TentativeDefinition && !LastTentative)
2349       LastTentative = Decl;
2350   }
2351 
2352   return LastTentative;
2353 }
2354 
2355 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2356   VarDecl *First = getFirstDecl();
2357   for (auto *I : First->redecls()) {
2358     if (I->isThisDeclarationADefinition(C) == Definition)
2359       return I;
2360   }
2361   return nullptr;
2362 }
2363 
2364 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2365   DefinitionKind Kind = DeclarationOnly;
2366 
2367   const VarDecl *First = getFirstDecl();
2368   for (auto *I : First->redecls()) {
2369     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2370     if (Kind == Definition)
2371       break;
2372   }
2373 
2374   return Kind;
2375 }
2376 
2377 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2378   for (auto *I : redecls()) {
2379     if (auto Expr = I->getInit()) {
2380       D = I;
2381       return Expr;
2382     }
2383   }
2384   return nullptr;
2385 }
2386 
2387 bool VarDecl::hasInit() const {
2388   if (auto *P = dyn_cast<ParmVarDecl>(this))
2389     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2390       return false;
2391 
2392   if (auto *Eval = getEvaluatedStmt())
2393     return Eval->Value.isValid();
2394 
2395   return !Init.isNull();
2396 }
2397 
2398 Expr *VarDecl::getInit() {
2399   if (!hasInit())
2400     return nullptr;
2401 
2402   if (auto *S = dyn_cast<Stmt *>(Init))
2403     return cast<Expr>(S);
2404 
2405   auto *Eval = getEvaluatedStmt();
2406 
2407   return cast<Expr>(Eval->Value.get(
2408       Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));
2409 }
2410 
2411 Stmt **VarDecl::getInitAddress() {
2412   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2413     return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2414 
2415   return Init.getAddrOfPtr1();
2416 }
2417 
2418 VarDecl *VarDecl::getInitializingDeclaration() {
2419   VarDecl *Def = nullptr;
2420   for (auto *I : redecls()) {
2421     if (I->hasInit())
2422       return I;
2423 
2424     if (I->isThisDeclarationADefinition()) {
2425       if (isStaticDataMember())
2426         return I;
2427       Def = I;
2428     }
2429   }
2430   return Def;
2431 }
2432 
2433 bool VarDecl::isOutOfLine() const {
2434   if (Decl::isOutOfLine())
2435     return true;
2436 
2437   if (!isStaticDataMember())
2438     return false;
2439 
2440   // If this static data member was instantiated from a static data member of
2441   // a class template, check whether that static data member was defined
2442   // out-of-line.
2443   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2444     return VD->isOutOfLine();
2445 
2446   return false;
2447 }
2448 
2449 void VarDecl::setInit(Expr *I) {
2450   if (auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init)) {
2451     Eval->~EvaluatedStmt();
2452     getASTContext().Deallocate(Eval);
2453   }
2454 
2455   Init = I;
2456 }
2457 
2458 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2459   const LangOptions &Lang = C.getLangOpts();
2460 
2461   // OpenCL permits const integral variables to be used in constant
2462   // expressions, like in C++98.
2463   if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2464     return false;
2465 
2466   // Function parameters are never usable in constant expressions.
2467   if (isa<ParmVarDecl>(this))
2468     return false;
2469 
2470   // The values of weak variables are never usable in constant expressions.
2471   if (isWeak())
2472     return false;
2473 
2474   // In C++11, any variable of reference type can be used in a constant
2475   // expression if it is initialized by a constant expression.
2476   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2477     return true;
2478 
2479   // Only const objects can be used in constant expressions in C++. C++98 does
2480   // not require the variable to be non-volatile, but we consider this to be a
2481   // defect.
2482   if (!getType().isConstant(C) || getType().isVolatileQualified())
2483     return false;
2484 
2485   // In C++, but not in C, const, non-volatile variables of integral or
2486   // enumeration types can be used in constant expressions.
2487   if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2488     return true;
2489 
2490   // C23 6.6p7: An identifier that is:
2491   // ...
2492   // - declared with storage-class specifier constexpr and has an object type,
2493   // is a named constant, ... such a named constant is a constant expression
2494   // with the type and value of the declared object.
2495   // Additionally, in C++11, non-volatile constexpr variables can be used in
2496   // constant expressions.
2497   return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2498 }
2499 
2500 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2501   // C++2a [expr.const]p3:
2502   //   A variable is usable in constant expressions after its initializing
2503   //   declaration is encountered...
2504   const VarDecl *DefVD = nullptr;
2505   const Expr *Init = getAnyInitializer(DefVD);
2506   if (!Init || Init->isValueDependent() || getType()->isDependentType())
2507     return false;
2508   //   ... if it is a constexpr variable, or it is of reference type or of
2509   //   const-qualified integral or enumeration type, ...
2510   if (!DefVD->mightBeUsableInConstantExpressions(Context))
2511     return false;
2512   //   ... and its initializer is a constant initializer.
2513   if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) &&
2514       !DefVD->hasConstantInitialization())
2515     return false;
2516   // C++98 [expr.const]p1:
2517   //   An integral constant-expression can involve only [...] const variables
2518   //   or static data members of integral or enumeration types initialized with
2519   //   [integer] constant expressions (dcl.init)
2520   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2521       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2522     return false;
2523   return true;
2524 }
2525 
2526 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2527 /// form, which contains extra information on the evaluated value of the
2528 /// initializer.
2529 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2530   auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init);
2531   if (!Eval) {
2532     // Note: EvaluatedStmt contains an APValue, which usually holds
2533     // resources not allocated from the ASTContext.  We need to do some
2534     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2535     // where we can detect whether there's anything to clean up or not.
2536     Eval = new (getASTContext()) EvaluatedStmt;
2537     Eval->Value = cast<Stmt *>(Init);
2538     Init = Eval;
2539   }
2540   return Eval;
2541 }
2542 
2543 EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2544   return dyn_cast_if_present<EvaluatedStmt *>(Init);
2545 }
2546 
2547 APValue *VarDecl::evaluateValue() const {
2548   SmallVector<PartialDiagnosticAt, 8> Notes;
2549   return evaluateValueImpl(Notes, hasConstantInitialization());
2550 }
2551 
2552 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2553                                     bool IsConstantInitialization) const {
2554   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2555 
2556   const auto *Init = getInit();
2557   assert(!Init->isValueDependent());
2558 
2559   // We only produce notes indicating why an initializer is non-constant the
2560   // first time it is evaluated. FIXME: The notes won't always be emitted the
2561   // first time we try evaluation, so might not be produced at all.
2562   if (Eval->WasEvaluated)
2563     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2564 
2565   if (Eval->IsEvaluating) {
2566     // FIXME: Produce a diagnostic for self-initialization.
2567     return nullptr;
2568   }
2569 
2570   Eval->IsEvaluating = true;
2571 
2572   ASTContext &Ctx = getASTContext();
2573   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2574                                             IsConstantInitialization);
2575 
2576   // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2577   // a constant initializer if we produced notes. In that case, we can't keep
2578   // the result, because it may only be correct under the assumption that the
2579   // initializer is a constant context.
2580   if (IsConstantInitialization &&
2581       (Ctx.getLangOpts().CPlusPlus ||
2582        (isConstexpr() && Ctx.getLangOpts().C23)) &&
2583       !Notes.empty())
2584     Result = false;
2585 
2586   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2587   // or that it's empty (so that there's nothing to clean up) if evaluation
2588   // failed.
2589   if (!Result)
2590     Eval->Evaluated = APValue();
2591   else if (Eval->Evaluated.needsCleanup())
2592     Ctx.addDestruction(&Eval->Evaluated);
2593 
2594   Eval->IsEvaluating = false;
2595   Eval->WasEvaluated = true;
2596 
2597   return Result ? &Eval->Evaluated : nullptr;
2598 }
2599 
2600 APValue *VarDecl::getEvaluatedValue() const {
2601   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2602     if (Eval->WasEvaluated)
2603       return &Eval->Evaluated;
2604 
2605   return nullptr;
2606 }
2607 
2608 bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2609   const Expr *Init = getInit();
2610   assert(Init && "no initializer");
2611 
2612   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2613   if (!Eval->CheckedForICEInit) {
2614     Eval->CheckedForICEInit = true;
2615     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2616   }
2617   return Eval->HasICEInit;
2618 }
2619 
2620 bool VarDecl::hasConstantInitialization() const {
2621   // In C, all globals and constexpr variables should have constant
2622   // initialization. For constexpr variables in C check that initializer is a
2623   // constant initializer because they can be used in constant expressions.
2624   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus &&
2625       !isConstexpr())
2626     return true;
2627 
2628   // In C++, it depends on whether the evaluation at the point of definition
2629   // was evaluatable as a constant initializer.
2630   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2631     return Eval->HasConstantInitialization;
2632 
2633   return false;
2634 }
2635 
2636 bool VarDecl::checkForConstantInitialization(
2637     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2638   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2639   // If we ask for the value before we know whether we have a constant
2640   // initializer, we can compute the wrong value (for example, due to
2641   // std::is_constant_evaluated()).
2642   assert(!Eval->WasEvaluated &&
2643          "already evaluated var value before checking for constant init");
2644   assert((getASTContext().getLangOpts().CPlusPlus ||
2645           getASTContext().getLangOpts().C23) &&
2646          "only meaningful in C++/C23");
2647 
2648   assert(!getInit()->isValueDependent());
2649 
2650   // Evaluate the initializer to check whether it's a constant expression.
2651   Eval->HasConstantInitialization =
2652       evaluateValueImpl(Notes, true) && Notes.empty();
2653 
2654   // If evaluation as a constant initializer failed, allow re-evaluation as a
2655   // non-constant initializer if we later find we want the value.
2656   if (!Eval->HasConstantInitialization)
2657     Eval->WasEvaluated = false;
2658 
2659   return Eval->HasConstantInitialization;
2660 }
2661 
2662 template<typename DeclT>
2663 static DeclT *getDefinitionOrSelf(DeclT *D) {
2664   assert(D);
2665   if (auto *Def = D->getDefinition())
2666     return Def;
2667   return D;
2668 }
2669 
2670 bool VarDecl::isEscapingByref() const {
2671   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2672 }
2673 
2674 bool VarDecl::isNonEscapingByref() const {
2675   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2676 }
2677 
2678 bool VarDecl::hasDependentAlignment() const {
2679   QualType T = getType();
2680   return T->isDependentType() || T->isUndeducedType() ||
2681          llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2682            return AA->isAlignmentDependent();
2683          });
2684 }
2685 
2686 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2687   const VarDecl *VD = this;
2688 
2689   // If this is an instantiated member, walk back to the template from which
2690   // it was instantiated.
2691   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2692     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2693       VD = VD->getInstantiatedFromStaticDataMember();
2694       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2695         VD = NewVD;
2696     }
2697   }
2698 
2699   // If it's an instantiated variable template specialization, find the
2700   // template or partial specialization from which it was instantiated.
2701   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2702     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2703       auto From = VDTemplSpec->getInstantiatedFrom();
2704       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2705         while (!VTD->isMemberSpecialization()) {
2706           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2707           if (!NewVTD)
2708             break;
2709           VTD = NewVTD;
2710         }
2711         return getDefinitionOrSelf(VTD->getTemplatedDecl());
2712       }
2713       if (auto *VTPSD =
2714               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2715         while (!VTPSD->isMemberSpecialization()) {
2716           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2717           if (!NewVTPSD)
2718             break;
2719           VTPSD = NewVTPSD;
2720         }
2721         return getDefinitionOrSelf<VarDecl>(VTPSD);
2722       }
2723     }
2724   }
2725 
2726   // If this is the pattern of a variable template, find where it was
2727   // instantiated from. FIXME: Is this necessary?
2728   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2729     while (!VarTemplate->isMemberSpecialization()) {
2730       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2731       if (!NewVT)
2732         break;
2733       VarTemplate = NewVT;
2734     }
2735 
2736     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2737   }
2738 
2739   if (VD == this)
2740     return nullptr;
2741   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2742 }
2743 
2744 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2745   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2746     return cast<VarDecl>(MSI->getInstantiatedFrom());
2747 
2748   return nullptr;
2749 }
2750 
2751 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2752   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2753     return Spec->getSpecializationKind();
2754 
2755   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2756     return MSI->getTemplateSpecializationKind();
2757 
2758   return TSK_Undeclared;
2759 }
2760 
2761 TemplateSpecializationKind
2762 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2763   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2764     return MSI->getTemplateSpecializationKind();
2765 
2766   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2767     return Spec->getSpecializationKind();
2768 
2769   return TSK_Undeclared;
2770 }
2771 
2772 SourceLocation VarDecl::getPointOfInstantiation() const {
2773   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2774     return Spec->getPointOfInstantiation();
2775 
2776   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2777     return MSI->getPointOfInstantiation();
2778 
2779   return SourceLocation();
2780 }
2781 
2782 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2783   return dyn_cast_if_present<VarTemplateDecl *>(
2784       getASTContext().getTemplateOrSpecializationInfo(this));
2785 }
2786 
2787 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2788   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2789 }
2790 
2791 bool VarDecl::isKnownToBeDefined() const {
2792   const auto &LangOpts = getASTContext().getLangOpts();
2793   // In CUDA mode without relocatable device code, variables of form 'extern
2794   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2795   // memory pool.  These are never undefined variables, even if they appear
2796   // inside of an anon namespace or static function.
2797   //
2798   // With CUDA relocatable device code enabled, these variables don't get
2799   // special handling; they're treated like regular extern variables.
2800   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2801       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2802       isa<IncompleteArrayType>(getType()))
2803     return true;
2804 
2805   return hasDefinition();
2806 }
2807 
2808 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2809   if (!hasGlobalStorage())
2810     return false;
2811   if (hasAttr<NoDestroyAttr>())
2812     return true;
2813   if (hasAttr<AlwaysDestroyAttr>())
2814     return false;
2815 
2816   using RSDKind = LangOptions::RegisterStaticDestructorsKind;
2817   RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors();
2818   return K == RSDKind::None ||
2819          (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None);
2820 }
2821 
2822 QualType::DestructionKind
2823 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2824   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2825     if (Eval->HasConstantDestruction)
2826       return QualType::DK_none;
2827 
2828   if (isNoDestroy(Ctx))
2829     return QualType::DK_none;
2830 
2831   return getType().isDestructedType();
2832 }
2833 
2834 bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
2835   assert(hasInit() && "Expect initializer to check for flexible array init");
2836   auto *Ty = getType()->getAs<RecordType>();
2837   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2838     return false;
2839   auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2840   if (!List)
2841     return false;
2842   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2843   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2844   if (!InitTy)
2845     return false;
2846   return !InitTy->isZeroSize();
2847 }
2848 
2849 CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
2850   assert(hasInit() && "Expect initializer to check for flexible array init");
2851   auto *Ty = getType()->getAs<RecordType>();
2852   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2853     return CharUnits::Zero();
2854   auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2855   if (!List || List->getNumInits() == 0)
2856     return CharUnits::Zero();
2857   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2858   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2859   if (!InitTy)
2860     return CharUnits::Zero();
2861   CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2862   const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2863   CharUnits FlexibleArrayOffset =
2864       Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));
2865   if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2866     return CharUnits::Zero();
2867   return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2868 }
2869 
2870 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2871   if (isStaticDataMember())
2872     // FIXME: Remove ?
2873     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2874     return dyn_cast_if_present<MemberSpecializationInfo *>(
2875         getASTContext().getTemplateOrSpecializationInfo(this));
2876   return nullptr;
2877 }
2878 
2879 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2880                                          SourceLocation PointOfInstantiation) {
2881   assert((isa<VarTemplateSpecializationDecl>(this) ||
2882           getMemberSpecializationInfo()) &&
2883          "not a variable or static data member template specialization");
2884 
2885   if (VarTemplateSpecializationDecl *Spec =
2886           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2887     Spec->setSpecializationKind(TSK);
2888     if (TSK != TSK_ExplicitSpecialization &&
2889         PointOfInstantiation.isValid() &&
2890         Spec->getPointOfInstantiation().isInvalid()) {
2891       Spec->setPointOfInstantiation(PointOfInstantiation);
2892       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2893         L->InstantiationRequested(this);
2894     }
2895   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2896     MSI->setTemplateSpecializationKind(TSK);
2897     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2898         MSI->getPointOfInstantiation().isInvalid()) {
2899       MSI->setPointOfInstantiation(PointOfInstantiation);
2900       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2901         L->InstantiationRequested(this);
2902     }
2903   }
2904 }
2905 
2906 void
2907 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2908                                             TemplateSpecializationKind TSK) {
2909   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2910          "Previous template or instantiation?");
2911   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2912 }
2913 
2914 //===----------------------------------------------------------------------===//
2915 // ParmVarDecl Implementation
2916 //===----------------------------------------------------------------------===//
2917 
2918 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2919                                  SourceLocation StartLoc, SourceLocation IdLoc,
2920                                  const IdentifierInfo *Id, QualType T,
2921                                  TypeSourceInfo *TInfo, StorageClass S,
2922                                  Expr *DefArg) {
2923   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2924                                  S, DefArg);
2925 }
2926 
2927 QualType ParmVarDecl::getOriginalType() const {
2928   TypeSourceInfo *TSI = getTypeSourceInfo();
2929   QualType T = TSI ? TSI->getType() : getType();
2930   if (const auto *DT = dyn_cast<DecayedType>(T))
2931     return DT->getOriginalType();
2932   return T;
2933 }
2934 
2935 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2936   return new (C, ID)
2937       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2938                   nullptr, QualType(), nullptr, SC_None, nullptr);
2939 }
2940 
2941 SourceRange ParmVarDecl::getSourceRange() const {
2942   if (!hasInheritedDefaultArg()) {
2943     SourceRange ArgRange = getDefaultArgRange();
2944     if (ArgRange.isValid())
2945       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2946   }
2947 
2948   // DeclaratorDecl considers the range of postfix types as overlapping with the
2949   // declaration name, but this is not the case with parameters in ObjC methods.
2950   if (isa<ObjCMethodDecl>(getDeclContext()))
2951     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2952 
2953   return DeclaratorDecl::getSourceRange();
2954 }
2955 
2956 bool ParmVarDecl::isDestroyedInCallee() const {
2957   // ns_consumed only affects code generation in ARC
2958   if (hasAttr<NSConsumedAttr>())
2959     return getASTContext().getLangOpts().ObjCAutoRefCount;
2960 
2961   // FIXME: isParamDestroyedInCallee() should probably imply
2962   // isDestructedType()
2963   const auto *RT = getType()->getAs<RecordType>();
2964   if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2965       getType().isDestructedType())
2966     return true;
2967 
2968   return false;
2969 }
2970 
2971 Expr *ParmVarDecl::getDefaultArg() {
2972   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2973   assert(!hasUninstantiatedDefaultArg() &&
2974          "Default argument is not yet instantiated!");
2975 
2976   Expr *Arg = getInit();
2977   if (auto *E = dyn_cast_if_present<FullExpr>(Arg))
2978     return E->getSubExpr();
2979 
2980   return Arg;
2981 }
2982 
2983 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2984   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2985   Init = defarg;
2986 }
2987 
2988 SourceRange ParmVarDecl::getDefaultArgRange() const {
2989   switch (ParmVarDeclBits.DefaultArgKind) {
2990   case DAK_None:
2991   case DAK_Unparsed:
2992     // Nothing we can do here.
2993     return SourceRange();
2994 
2995   case DAK_Uninstantiated:
2996     return getUninstantiatedDefaultArg()->getSourceRange();
2997 
2998   case DAK_Normal:
2999     if (const Expr *E = getInit())
3000       return E->getSourceRange();
3001 
3002     // Missing an actual expression, may be invalid.
3003     return SourceRange();
3004   }
3005   llvm_unreachable("Invalid default argument kind.");
3006 }
3007 
3008 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
3009   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
3010   Init = arg;
3011 }
3012 
3013 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
3014   assert(hasUninstantiatedDefaultArg() &&
3015          "Wrong kind of initialization expression!");
3016   return cast_if_present<Expr>(cast<Stmt *>(Init));
3017 }
3018 
3019 bool ParmVarDecl::hasDefaultArg() const {
3020   // FIXME: We should just return false for DAK_None here once callers are
3021   // prepared for the case that we encountered an invalid default argument and
3022   // were unable to even build an invalid expression.
3023   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
3024          !Init.isNull();
3025 }
3026 
3027 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3028   getASTContext().setParameterIndex(this, parameterIndex);
3029   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3030 }
3031 
3032 unsigned ParmVarDecl::getParameterIndexLarge() const {
3033   return getASTContext().getParameterIndex(this);
3034 }
3035 
3036 //===----------------------------------------------------------------------===//
3037 // FunctionDecl Implementation
3038 //===----------------------------------------------------------------------===//
3039 
3040 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
3041                            SourceLocation StartLoc,
3042                            const DeclarationNameInfo &NameInfo, QualType T,
3043                            TypeSourceInfo *TInfo, StorageClass S,
3044                            bool UsesFPIntrin, bool isInlineSpecified,
3045                            ConstexprSpecKind ConstexprKind,
3046                            Expr *TrailingRequiresClause)
3047     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3048                      StartLoc),
3049       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3050       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3051   assert(T.isNull() || T->isFunctionType());
3052   FunctionDeclBits.SClass = S;
3053   FunctionDeclBits.IsInline = isInlineSpecified;
3054   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3055   FunctionDeclBits.IsVirtualAsWritten = false;
3056   FunctionDeclBits.IsPureVirtual = false;
3057   FunctionDeclBits.HasInheritedPrototype = false;
3058   FunctionDeclBits.HasWrittenPrototype = true;
3059   FunctionDeclBits.IsDeleted = false;
3060   FunctionDeclBits.IsTrivial = false;
3061   FunctionDeclBits.IsTrivialForCall = false;
3062   FunctionDeclBits.IsDefaulted = false;
3063   FunctionDeclBits.IsExplicitlyDefaulted = false;
3064   FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3065   FunctionDeclBits.IsIneligibleOrNotSelected = false;
3066   FunctionDeclBits.HasImplicitReturnZero = false;
3067   FunctionDeclBits.IsLateTemplateParsed = false;
3068   FunctionDeclBits.IsInstantiatedFromMemberTemplate = false;
3069   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3070   FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3071   FunctionDeclBits.InstantiationIsPending = false;
3072   FunctionDeclBits.UsesSEHTry = false;
3073   FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3074   FunctionDeclBits.HasSkippedBody = false;
3075   FunctionDeclBits.WillHaveBody = false;
3076   FunctionDeclBits.IsMultiVersion = false;
3077   FunctionDeclBits.DeductionCandidateKind =
3078       static_cast<unsigned char>(DeductionCandidate::Normal);
3079   FunctionDeclBits.HasODRHash = false;
3080   FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3081   if (TrailingRequiresClause)
3082     setTrailingRequiresClause(TrailingRequiresClause);
3083 }
3084 
3085 void FunctionDecl::getNameForDiagnostic(
3086     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3087   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
3088   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
3089   if (TemplateArgs)
3090     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3091 }
3092 
3093 bool FunctionDecl::isVariadic() const {
3094   if (const auto *FT = getType()->getAs<FunctionProtoType>())
3095     return FT->isVariadic();
3096   return false;
3097 }
3098 
3099 FunctionDecl::DefaultedOrDeletedFunctionInfo *
3100 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
3101     ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3102     StringLiteral *DeletedMessage) {
3103   static constexpr size_t Alignment =
3104       std::max({alignof(DefaultedOrDeletedFunctionInfo),
3105                 alignof(DeclAccessPair), alignof(StringLiteral *)});
3106   size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3107       Lookups.size(), DeletedMessage != nullptr);
3108 
3109   DefaultedOrDeletedFunctionInfo *Info =
3110       new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;
3111   Info->NumLookups = Lookups.size();
3112   Info->HasDeletedMessage = DeletedMessage != nullptr;
3113 
3114   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3115                           Info->getTrailingObjects<DeclAccessPair>());
3116   if (DeletedMessage)
3117     *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3118   return Info;
3119 }
3120 
3121 void FunctionDecl::setDefaultedOrDeletedInfo(
3122     DefaultedOrDeletedFunctionInfo *Info) {
3123   assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3124   assert(!Body && "can't replace function body with defaulted function info");
3125 
3126   FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3127   DefaultedOrDeletedInfo = Info;
3128 }
3129 
3130 void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) {
3131   FunctionDeclBits.IsDeleted = D;
3132 
3133   if (Message) {
3134     assert(isDeletedAsWritten() && "Function must be deleted");
3135     if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3136       DefaultedOrDeletedInfo->setDeletedMessage(Message);
3137     else
3138       setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create(
3139           getASTContext(), /*Lookups=*/{}, Message));
3140   }
3141 }
3142 
3143 void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage(
3144     StringLiteral *Message) {
3145   // We should never get here with the DefaultedOrDeletedInfo populated, but
3146   // no space allocated for the deleted message, since that would require
3147   // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3148   // an already existing DefaultedOrDeletedFunctionInfo.
3149   assert(HasDeletedMessage &&
3150          "No space to store a delete message in this DefaultedOrDeletedInfo");
3151   *getTrailingObjects<StringLiteral *>() = Message;
3152 }
3153 
3154 FunctionDecl::DefaultedOrDeletedFunctionInfo *
3155 FunctionDecl::getDefalutedOrDeletedInfo() const {
3156   return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3157                                                     : nullptr;
3158 }
3159 
3160 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3161   for (const auto *I : redecls()) {
3162     if (I->doesThisDeclarationHaveABody()) {
3163       Definition = I;
3164       return true;
3165     }
3166   }
3167 
3168   return false;
3169 }
3170 
3171 bool FunctionDecl::hasTrivialBody() const {
3172   const Stmt *S = getBody();
3173   if (!S) {
3174     // Since we don't have a body for this function, we don't know if it's
3175     // trivial or not.
3176     return false;
3177   }
3178 
3179   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3180     return true;
3181   return false;
3182 }
3183 
3184 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
3185   if (!getFriendObjectKind())
3186     return false;
3187 
3188   // Check for a friend function instantiated from a friend function
3189   // definition in a templated class.
3190   if (const FunctionDecl *InstantiatedFrom =
3191           getInstantiatedFromMemberFunction())
3192     return InstantiatedFrom->getFriendObjectKind() &&
3193            InstantiatedFrom->isThisDeclarationADefinition();
3194 
3195   // Check for a friend function template instantiated from a friend
3196   // function template definition in a templated class.
3197   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3198     if (const FunctionTemplateDecl *InstantiatedFrom =
3199             Template->getInstantiatedFromMemberTemplate())
3200       return InstantiatedFrom->getFriendObjectKind() &&
3201              InstantiatedFrom->isThisDeclarationADefinition();
3202   }
3203 
3204   return false;
3205 }
3206 
3207 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3208                              bool CheckForPendingFriendDefinition) const {
3209   for (const FunctionDecl *FD : redecls()) {
3210     if (FD->isThisDeclarationADefinition()) {
3211       Definition = FD;
3212       return true;
3213     }
3214 
3215     // If this is a friend function defined in a class template, it does not
3216     // have a body until it is used, nevertheless it is a definition, see
3217     // [temp.inst]p2:
3218     //
3219     // ... for the purpose of determining whether an instantiated redeclaration
3220     // is valid according to [basic.def.odr] and [class.mem], a declaration that
3221     // corresponds to a definition in the template is considered to be a
3222     // definition.
3223     //
3224     // The following code must produce redefinition error:
3225     //
3226     //     template<typename T> struct C20 { friend void func_20() {} };
3227     //     C20<int> c20i;
3228     //     void func_20() {}
3229     //
3230     if (CheckForPendingFriendDefinition &&
3231         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3232       Definition = FD;
3233       return true;
3234     }
3235   }
3236 
3237   return false;
3238 }
3239 
3240 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3241   if (!hasBody(Definition))
3242     return nullptr;
3243 
3244   assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3245          "definition should not have a body");
3246   if (Definition->Body)
3247     return Definition->Body.get(getASTContext().getExternalSource());
3248 
3249   return nullptr;
3250 }
3251 
3252 void FunctionDecl::setBody(Stmt *B) {
3253   FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3254   Body = LazyDeclStmtPtr(B);
3255   if (B)
3256     EndRangeLoc = B->getEndLoc();
3257 }
3258 
3259 void FunctionDecl::setIsPureVirtual(bool P) {
3260   FunctionDeclBits.IsPureVirtual = P;
3261   if (P)
3262     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3263       Parent->markedVirtualFunctionPure();
3264 }
3265 
3266 template<std::size_t Len>
3267 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3268   const IdentifierInfo *II = ND->getIdentifier();
3269   return II && II->isStr(Str);
3270 }
3271 
3272 bool FunctionDecl::isImmediateEscalating() const {
3273   // C++23 [expr.const]/p17
3274   // An immediate-escalating function is
3275   //  - the call operator of a lambda that is not declared with the consteval
3276   //  specifier,
3277   if (isLambdaCallOperator(this) && !isConsteval())
3278     return true;
3279   // - a defaulted special member function that is not declared with the
3280   // consteval specifier,
3281   if (isDefaulted() && !isConsteval())
3282     return true;
3283 
3284   if (auto *CD = dyn_cast<CXXConstructorDecl>(this);
3285       CD && CD->isInheritingConstructor())
3286     return CD->getInheritedConstructor().getConstructor();
3287 
3288   // - a function that results from the instantiation of a templated entity
3289   // defined with the constexpr specifier.
3290   TemplatedKind TK = getTemplatedKind();
3291   if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3292       isConstexprSpecified())
3293     return true;
3294   return false;
3295 }
3296 
3297 bool FunctionDecl::isImmediateFunction() const {
3298   // C++23 [expr.const]/p18
3299   // An immediate function is a function or constructor that is
3300   // - declared with the consteval specifier
3301   if (isConsteval())
3302     return true;
3303   // - an immediate-escalating function F whose function body contains an
3304   // immediate-escalating expression
3305   if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions())
3306     return true;
3307 
3308   if (auto *CD = dyn_cast<CXXConstructorDecl>(this);
3309       CD && CD->isInheritingConstructor())
3310     return CD->getInheritedConstructor()
3311         .getConstructor()
3312         ->isImmediateFunction();
3313 
3314   if (FunctionDecl *P = getTemplateInstantiationPattern();
3315       P && P->isImmediateFunction())
3316     return true;
3317 
3318   if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3319       MD && MD->isLambdaStaticInvoker())
3320     return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3321 
3322   return false;
3323 }
3324 
3325 bool FunctionDecl::isMain() const {
3326   return isNamed(this, "main") && !getLangOpts().Freestanding &&
3327          !getLangOpts().HLSL &&
3328          (getDeclContext()->getRedeclContext()->isTranslationUnit() ||
3329           isExternC());
3330 }
3331 
3332 bool FunctionDecl::isMSVCRTEntryPoint() const {
3333   const TranslationUnitDecl *TUnit =
3334       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3335   if (!TUnit)
3336     return false;
3337 
3338   // Even though we aren't really targeting MSVCRT if we are freestanding,
3339   // semantic analysis for these functions remains the same.
3340 
3341   // MSVCRT entry points only exist on MSVCRT targets.
3342   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3343     return false;
3344 
3345   // Nameless functions like constructors cannot be entry points.
3346   if (!getIdentifier())
3347     return false;
3348 
3349   return llvm::StringSwitch<bool>(getName())
3350       .Cases("main",     // an ANSI console app
3351              "wmain",    // a Unicode console App
3352              "WinMain",  // an ANSI GUI app
3353              "wWinMain", // a Unicode GUI app
3354              "DllMain",  // a DLL
3355              true)
3356       .Default(false);
3357 }
3358 
3359 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3360   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3361     return false;
3362   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3363       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3364       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3365       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3366     return false;
3367 
3368   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3369     return false;
3370 
3371   const auto *proto = getType()->castAs<FunctionProtoType>();
3372   if (proto->getNumParams() != 2 || proto->isVariadic())
3373     return false;
3374 
3375   const ASTContext &Context =
3376       cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3377           ->getASTContext();
3378 
3379   // The result type and first argument type are constant across all
3380   // these operators.  The second argument must be exactly void*.
3381   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3382 }
3383 
3384 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3385     std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3386   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3387     return false;
3388   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3389       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3390       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3391       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3392     return false;
3393 
3394   if (isa<CXXRecordDecl>(getDeclContext()))
3395     return false;
3396 
3397   // This can only fail for an invalid 'operator new' declaration.
3398   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3399     return false;
3400 
3401   const auto *FPT = getType()->castAs<FunctionProtoType>();
3402   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())
3403     return false;
3404 
3405   // If this is a single-parameter function, it must be a replaceable global
3406   // allocation or deallocation function.
3407   if (FPT->getNumParams() == 1)
3408     return true;
3409 
3410   unsigned Params = 1;
3411   QualType Ty = FPT->getParamType(Params);
3412   const ASTContext &Ctx = getASTContext();
3413 
3414   auto Consume = [&] {
3415     ++Params;
3416     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3417   };
3418 
3419   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3420   bool IsSizedDelete = false;
3421   if (Ctx.getLangOpts().SizedDeallocation &&
3422       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3423        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3424       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3425     IsSizedDelete = true;
3426     Consume();
3427   }
3428 
3429   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3430   // new/delete.
3431   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3432     Consume();
3433     if (AlignmentParam)
3434       *AlignmentParam = Params;
3435   }
3436 
3437   // If this is not a sized delete, the next parameter can be a
3438   // 'const std::nothrow_t&'.
3439   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3440     Ty = Ty->getPointeeType();
3441     if (Ty.getCVRQualifiers() != Qualifiers::Const)
3442       return false;
3443     if (Ty->isNothrowT()) {
3444       if (IsNothrow)
3445         *IsNothrow = true;
3446       Consume();
3447     }
3448   }
3449 
3450   // Finally, recognize the not yet standard versions of new that take a
3451   // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3452   // tcmalloc (see
3453   // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3454   if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3455     QualType T = Ty;
3456     while (const auto *TD = T->getAs<TypedefType>())
3457       T = TD->getDecl()->getUnderlyingType();
3458     const IdentifierInfo *II =
3459         T->castAs<EnumType>()->getDecl()->getIdentifier();
3460     if (II && II->isStr("__hot_cold_t"))
3461       Consume();
3462   }
3463 
3464   return Params == FPT->getNumParams();
3465 }
3466 
3467 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3468   if (!getBuiltinID())
3469     return false;
3470 
3471   const FunctionDecl *Definition;
3472   if (!hasBody(Definition))
3473     return false;
3474 
3475   if (!Definition->isInlineSpecified() ||
3476       !Definition->hasAttr<AlwaysInlineAttr>())
3477     return false;
3478 
3479   ASTContext &Context = getASTContext();
3480   switch (Context.GetGVALinkageForFunction(Definition)) {
3481   case GVA_Internal:
3482   case GVA_DiscardableODR:
3483   case GVA_StrongODR:
3484     return false;
3485   case GVA_AvailableExternally:
3486   case GVA_StrongExternal:
3487     return true;
3488   }
3489   llvm_unreachable("Unknown GVALinkage");
3490 }
3491 
3492 bool FunctionDecl::isDestroyingOperatorDelete() const {
3493   // C++ P0722:
3494   //   Within a class C, a single object deallocation function with signature
3495   //     (T, std::destroying_delete_t, <more params>)
3496   //   is a destroying operator delete.
3497   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3498       getNumParams() < 2)
3499     return false;
3500 
3501   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3502   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3503          RD->getIdentifier()->isStr("destroying_delete_t");
3504 }
3505 
3506 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3507   return getDeclLanguageLinkage(*this);
3508 }
3509 
3510 bool FunctionDecl::isExternC() const {
3511   return isDeclExternC(*this);
3512 }
3513 
3514 bool FunctionDecl::isInExternCContext() const {
3515   if (hasAttr<OpenCLKernelAttr>())
3516     return true;
3517   return getLexicalDeclContext()->isExternCContext();
3518 }
3519 
3520 bool FunctionDecl::isInExternCXXContext() const {
3521   return getLexicalDeclContext()->isExternCXXContext();
3522 }
3523 
3524 bool FunctionDecl::isGlobal() const {
3525   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3526     return Method->isStatic();
3527 
3528   if (getCanonicalDecl()->getStorageClass() == SC_Static)
3529     return false;
3530 
3531   for (const DeclContext *DC = getDeclContext();
3532        DC->isNamespace();
3533        DC = DC->getParent()) {
3534     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3535       if (!Namespace->getDeclName())
3536         return false;
3537     }
3538   }
3539 
3540   return true;
3541 }
3542 
3543 bool FunctionDecl::isNoReturn() const {
3544   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3545       hasAttr<C11NoReturnAttr>())
3546     return true;
3547 
3548   if (auto *FnTy = getType()->getAs<FunctionType>())
3549     return FnTy->getNoReturnAttr();
3550 
3551   return false;
3552 }
3553 
3554 bool FunctionDecl::isMemberLikeConstrainedFriend() const {
3555   // C++20 [temp.friend]p9:
3556   //   A non-template friend declaration with a requires-clause [or]
3557   //   a friend function template with a constraint that depends on a template
3558   //   parameter from an enclosing template [...] does not declare the same
3559   //   function or function template as a declaration in any other scope.
3560 
3561   // If this isn't a friend then it's not a member-like constrained friend.
3562   if (!getFriendObjectKind()) {
3563     return false;
3564   }
3565 
3566   if (!getDescribedFunctionTemplate()) {
3567     // If these friends don't have constraints, they aren't constrained, and
3568     // thus don't fall under temp.friend p9. Else the simple presence of a
3569     // constraint makes them unique.
3570     return getTrailingRequiresClause();
3571   }
3572 
3573   return FriendConstraintRefersToEnclosingTemplate();
3574 }
3575 
3576 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3577   if (hasAttr<TargetAttr>())
3578     return MultiVersionKind::Target;
3579   if (hasAttr<TargetVersionAttr>())
3580     return MultiVersionKind::TargetVersion;
3581   if (hasAttr<CPUDispatchAttr>())
3582     return MultiVersionKind::CPUDispatch;
3583   if (hasAttr<CPUSpecificAttr>())
3584     return MultiVersionKind::CPUSpecific;
3585   if (hasAttr<TargetClonesAttr>())
3586     return MultiVersionKind::TargetClones;
3587   return MultiVersionKind::None;
3588 }
3589 
3590 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3591   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3592 }
3593 
3594 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3595   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3596 }
3597 
3598 bool FunctionDecl::isTargetMultiVersion() const {
3599   return isMultiVersion() &&
3600          (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3601 }
3602 
3603 bool FunctionDecl::isTargetMultiVersionDefault() const {
3604   if (!isMultiVersion())
3605     return false;
3606   if (hasAttr<TargetAttr>())
3607     return getAttr<TargetAttr>()->isDefaultVersion();
3608   return hasAttr<TargetVersionAttr>() &&
3609          getAttr<TargetVersionAttr>()->isDefaultVersion();
3610 }
3611 
3612 bool FunctionDecl::isTargetClonesMultiVersion() const {
3613   return isMultiVersion() && hasAttr<TargetClonesAttr>();
3614 }
3615 
3616 bool FunctionDecl::isTargetVersionMultiVersion() const {
3617   return isMultiVersion() && hasAttr<TargetVersionAttr>();
3618 }
3619 
3620 void
3621 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3622   redeclarable_base::setPreviousDecl(PrevDecl);
3623 
3624   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3625     FunctionTemplateDecl *PrevFunTmpl
3626       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3627     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3628     FunTmpl->setPreviousDecl(PrevFunTmpl);
3629   }
3630 
3631   if (PrevDecl && PrevDecl->isInlined())
3632     setImplicitlyInline(true);
3633 }
3634 
3635 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3636 
3637 /// Returns a value indicating whether this function corresponds to a builtin
3638 /// function.
3639 ///
3640 /// The function corresponds to a built-in function if it is declared at
3641 /// translation scope or within an extern "C" block and its name matches with
3642 /// the name of a builtin. The returned value will be 0 for functions that do
3643 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3644 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3645 /// value.
3646 ///
3647 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3648 /// functions as their wrapped builtins. This shouldn't be done in general, but
3649 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3650 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3651   unsigned BuiltinID = 0;
3652 
3653   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3654     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3655   } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3656     BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3657   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3658     BuiltinID = A->getID();
3659   }
3660 
3661   if (!BuiltinID)
3662     return 0;
3663 
3664   // If the function is marked "overloadable", it has a different mangled name
3665   // and is not the C library function.
3666   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3667       (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3668     return 0;
3669 
3670   if (getASTContext().getLangOpts().CPlusPlus &&
3671       BuiltinID == Builtin::BI__builtin_counted_by_ref)
3672     return 0;
3673 
3674   const ASTContext &Context = getASTContext();
3675   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3676     return BuiltinID;
3677 
3678   // This function has the name of a known C library
3679   // function. Determine whether it actually refers to the C library
3680   // function or whether it just has the same name.
3681 
3682   // If this is a static function, it's not a builtin.
3683   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3684     return 0;
3685 
3686   // OpenCL v1.2 s6.9.f - The library functions defined in
3687   // the C99 standard headers are not available.
3688   if (Context.getLangOpts().OpenCL &&
3689       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3690     return 0;
3691 
3692   // CUDA does not have device-side standard library. printf and malloc are the
3693   // only special cases that are supported by device-side runtime.
3694   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3695       !hasAttr<CUDAHostAttr>() &&
3696       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3697     return 0;
3698 
3699   // As AMDGCN implementation of OpenMP does not have a device-side standard
3700   // library, none of the predefined library functions except printf and malloc
3701   // should be treated as a builtin i.e. 0 should be returned for them.
3702   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3703       Context.getLangOpts().OpenMPIsTargetDevice &&
3704       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3705       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3706     return 0;
3707 
3708   return BuiltinID;
3709 }
3710 
3711 /// getNumParams - Return the number of parameters this function must have
3712 /// based on its FunctionType.  This is the length of the ParamInfo array
3713 /// after it has been created.
3714 unsigned FunctionDecl::getNumParams() const {
3715   const auto *FPT = getType()->getAs<FunctionProtoType>();
3716   return FPT ? FPT->getNumParams() : 0;
3717 }
3718 
3719 void FunctionDecl::setParams(ASTContext &C,
3720                              ArrayRef<ParmVarDecl *> NewParamInfo) {
3721   assert(!ParamInfo && "Already has param info!");
3722   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3723 
3724   // Zero params -> null pointer.
3725   if (!NewParamInfo.empty()) {
3726     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3727     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3728   }
3729 }
3730 
3731 /// getMinRequiredArguments - Returns the minimum number of arguments
3732 /// needed to call this function. This may be fewer than the number of
3733 /// function parameters, if some of the parameters have default
3734 /// arguments (in C++) or are parameter packs (C++11).
3735 unsigned FunctionDecl::getMinRequiredArguments() const {
3736   if (!getASTContext().getLangOpts().CPlusPlus)
3737     return getNumParams();
3738 
3739   // Note that it is possible for a parameter with no default argument to
3740   // follow a parameter with a default argument.
3741   unsigned NumRequiredArgs = 0;
3742   unsigned MinParamsSoFar = 0;
3743   for (auto *Param : parameters()) {
3744     if (!Param->isParameterPack()) {
3745       ++MinParamsSoFar;
3746       if (!Param->hasDefaultArg())
3747         NumRequiredArgs = MinParamsSoFar;
3748     }
3749   }
3750   return NumRequiredArgs;
3751 }
3752 
3753 bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const {
3754   return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter();
3755 }
3756 
3757 unsigned FunctionDecl::getNumNonObjectParams() const {
3758   return getNumParams() -
3759          static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3760 }
3761 
3762 unsigned FunctionDecl::getMinRequiredExplicitArguments() const {
3763   return getMinRequiredArguments() -
3764          static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3765 }
3766 
3767 bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3768   return getNumParams() == 1 ||
3769          (getNumParams() > 1 &&
3770           llvm::all_of(llvm::drop_begin(parameters()),
3771                        [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3772 }
3773 
3774 /// The combination of the extern and inline keywords under MSVC forces
3775 /// the function to be required.
3776 ///
3777 /// Note: This function assumes that we will only get called when isInlined()
3778 /// would return true for this FunctionDecl.
3779 bool FunctionDecl::isMSExternInline() const {
3780   assert(isInlined() && "expected to get called on an inlined function!");
3781 
3782   const ASTContext &Context = getASTContext();
3783   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3784       !hasAttr<DLLExportAttr>())
3785     return false;
3786 
3787   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3788        FD = FD->getPreviousDecl())
3789     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3790       return true;
3791 
3792   return false;
3793 }
3794 
3795 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3796   if (Redecl->getStorageClass() != SC_Extern)
3797     return false;
3798 
3799   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3800        FD = FD->getPreviousDecl())
3801     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3802       return false;
3803 
3804   return true;
3805 }
3806 
3807 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3808   // Only consider file-scope declarations in this test.
3809   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3810     return false;
3811 
3812   // Only consider explicit declarations; the presence of a builtin for a
3813   // libcall shouldn't affect whether a definition is externally visible.
3814   if (Redecl->isImplicit())
3815     return false;
3816 
3817   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3818     return true; // Not an inline definition
3819 
3820   return false;
3821 }
3822 
3823 /// For a function declaration in C or C++, determine whether this
3824 /// declaration causes the definition to be externally visible.
3825 ///
3826 /// For instance, this determines if adding the current declaration to the set
3827 /// of redeclarations of the given functions causes
3828 /// isInlineDefinitionExternallyVisible to change from false to true.
3829 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3830   assert(!doesThisDeclarationHaveABody() &&
3831          "Must have a declaration without a body.");
3832 
3833   const ASTContext &Context = getASTContext();
3834 
3835   if (Context.getLangOpts().MSVCCompat) {
3836     const FunctionDecl *Definition;
3837     if (hasBody(Definition) && Definition->isInlined() &&
3838         redeclForcesDefMSVC(this))
3839       return true;
3840   }
3841 
3842   if (Context.getLangOpts().CPlusPlus)
3843     return false;
3844 
3845   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3846     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3847     // an externally visible definition.
3848     //
3849     // FIXME: What happens if gnu_inline gets added on after the first
3850     // declaration?
3851     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3852       return false;
3853 
3854     const FunctionDecl *Prev = this;
3855     bool FoundBody = false;
3856     while ((Prev = Prev->getPreviousDecl())) {
3857       FoundBody |= Prev->doesThisDeclarationHaveABody();
3858 
3859       if (Prev->doesThisDeclarationHaveABody()) {
3860         // If it's not the case that both 'inline' and 'extern' are
3861         // specified on the definition, then it is always externally visible.
3862         if (!Prev->isInlineSpecified() ||
3863             Prev->getStorageClass() != SC_Extern)
3864           return false;
3865       } else if (Prev->isInlineSpecified() &&
3866                  Prev->getStorageClass() != SC_Extern) {
3867         return false;
3868       }
3869     }
3870     return FoundBody;
3871   }
3872 
3873   // C99 6.7.4p6:
3874   //   [...] If all of the file scope declarations for a function in a
3875   //   translation unit include the inline function specifier without extern,
3876   //   then the definition in that translation unit is an inline definition.
3877   if (isInlineSpecified() && getStorageClass() != SC_Extern)
3878     return false;
3879   const FunctionDecl *Prev = this;
3880   bool FoundBody = false;
3881   while ((Prev = Prev->getPreviousDecl())) {
3882     FoundBody |= Prev->doesThisDeclarationHaveABody();
3883     if (RedeclForcesDefC99(Prev))
3884       return false;
3885   }
3886   return FoundBody;
3887 }
3888 
3889 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3890   const TypeSourceInfo *TSI = getTypeSourceInfo();
3891   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3892              : FunctionTypeLoc();
3893 }
3894 
3895 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3896   FunctionTypeLoc FTL = getFunctionTypeLoc();
3897   if (!FTL)
3898     return SourceRange();
3899 
3900   // Skip self-referential return types.
3901   const SourceManager &SM = getASTContext().getSourceManager();
3902   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3903   SourceLocation Boundary = getNameInfo().getBeginLoc();
3904   if (RTRange.isInvalid() || Boundary.isInvalid() ||
3905       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3906     return SourceRange();
3907 
3908   return RTRange;
3909 }
3910 
3911 SourceRange FunctionDecl::getParametersSourceRange() const {
3912   unsigned NP = getNumParams();
3913   SourceLocation EllipsisLoc = getEllipsisLoc();
3914 
3915   if (NP == 0 && EllipsisLoc.isInvalid())
3916     return SourceRange();
3917 
3918   SourceLocation Begin =
3919       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3920   SourceLocation End = EllipsisLoc.isValid()
3921                            ? EllipsisLoc
3922                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3923 
3924   return SourceRange(Begin, End);
3925 }
3926 
3927 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3928   FunctionTypeLoc FTL = getFunctionTypeLoc();
3929   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3930 }
3931 
3932 /// For an inline function definition in C, or for a gnu_inline function
3933 /// in C++, determine whether the definition will be externally visible.
3934 ///
3935 /// Inline function definitions are always available for inlining optimizations.
3936 /// However, depending on the language dialect, declaration specifiers, and
3937 /// attributes, the definition of an inline function may or may not be
3938 /// "externally" visible to other translation units in the program.
3939 ///
3940 /// In C99, inline definitions are not externally visible by default. However,
3941 /// if even one of the global-scope declarations is marked "extern inline", the
3942 /// inline definition becomes externally visible (C99 6.7.4p6).
3943 ///
3944 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3945 /// definition, we use the GNU semantics for inline, which are nearly the
3946 /// opposite of C99 semantics. In particular, "inline" by itself will create
3947 /// an externally visible symbol, but "extern inline" will not create an
3948 /// externally visible symbol.
3949 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3950   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3951           hasAttr<AliasAttr>()) &&
3952          "Must be a function definition");
3953   assert(isInlined() && "Function must be inline");
3954   ASTContext &Context = getASTContext();
3955 
3956   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3957     // Note: If you change the logic here, please change
3958     // doesDeclarationForceExternallyVisibleDefinition as well.
3959     //
3960     // If it's not the case that both 'inline' and 'extern' are
3961     // specified on the definition, then this inline definition is
3962     // externally visible.
3963     if (Context.getLangOpts().CPlusPlus)
3964       return false;
3965     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3966       return true;
3967 
3968     // If any declaration is 'inline' but not 'extern', then this definition
3969     // is externally visible.
3970     for (auto *Redecl : redecls()) {
3971       if (Redecl->isInlineSpecified() &&
3972           Redecl->getStorageClass() != SC_Extern)
3973         return true;
3974     }
3975 
3976     return false;
3977   }
3978 
3979   // The rest of this function is C-only.
3980   assert(!Context.getLangOpts().CPlusPlus &&
3981          "should not use C inline rules in C++");
3982 
3983   // C99 6.7.4p6:
3984   //   [...] If all of the file scope declarations for a function in a
3985   //   translation unit include the inline function specifier without extern,
3986   //   then the definition in that translation unit is an inline definition.
3987   for (auto *Redecl : redecls()) {
3988     if (RedeclForcesDefC99(Redecl))
3989       return true;
3990   }
3991 
3992   // C99 6.7.4p6:
3993   //   An inline definition does not provide an external definition for the
3994   //   function, and does not forbid an external definition in another
3995   //   translation unit.
3996   return false;
3997 }
3998 
3999 /// getOverloadedOperator - Which C++ overloaded operator this
4000 /// function represents, if any.
4001 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
4002   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
4003     return getDeclName().getCXXOverloadedOperator();
4004   return OO_None;
4005 }
4006 
4007 /// getLiteralIdentifier - The literal suffix identifier this function
4008 /// represents, if any.
4009 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
4010   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
4011     return getDeclName().getCXXLiteralIdentifier();
4012   return nullptr;
4013 }
4014 
4015 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
4016   if (TemplateOrSpecialization.isNull())
4017     return TK_NonTemplate;
4018   if (const auto *ND = dyn_cast<NamedDecl *>(TemplateOrSpecialization)) {
4019     if (isa<FunctionDecl>(ND))
4020       return TK_DependentNonTemplate;
4021     assert(isa<FunctionTemplateDecl>(ND) &&
4022            "No other valid types in NamedDecl");
4023     return TK_FunctionTemplate;
4024   }
4025   if (isa<MemberSpecializationInfo *>(TemplateOrSpecialization))
4026     return TK_MemberSpecialization;
4027   if (isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization))
4028     return TK_FunctionTemplateSpecialization;
4029   if (isa<DependentFunctionTemplateSpecializationInfo *>(
4030           TemplateOrSpecialization))
4031     return TK_DependentFunctionTemplateSpecialization;
4032 
4033   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4034 }
4035 
4036 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
4037   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
4038     return cast<FunctionDecl>(Info->getInstantiatedFrom());
4039 
4040   return nullptr;
4041 }
4042 
4043 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
4044   if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>(
4045           TemplateOrSpecialization))
4046     return MSI;
4047   if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4048           TemplateOrSpecialization))
4049     return FTSI->getMemberSpecializationInfo();
4050   return nullptr;
4051 }
4052 
4053 void
4054 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4055                                                FunctionDecl *FD,
4056                                                TemplateSpecializationKind TSK) {
4057   assert(TemplateOrSpecialization.isNull() &&
4058          "Member function is already a specialization");
4059   MemberSpecializationInfo *Info
4060     = new (C) MemberSpecializationInfo(FD, TSK);
4061   TemplateOrSpecialization = Info;
4062 }
4063 
4064 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
4065   return dyn_cast_if_present<FunctionTemplateDecl>(
4066       dyn_cast_if_present<NamedDecl *>(TemplateOrSpecialization));
4067 }
4068 
4069 void FunctionDecl::setDescribedFunctionTemplate(
4070     FunctionTemplateDecl *Template) {
4071   assert(TemplateOrSpecialization.isNull() &&
4072          "Member function is already a specialization");
4073   TemplateOrSpecialization = Template;
4074 }
4075 
4076 bool FunctionDecl::isFunctionTemplateSpecialization() const {
4077   return isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization) ||
4078          isa<DependentFunctionTemplateSpecializationInfo *>(
4079              TemplateOrSpecialization);
4080 }
4081 
4082 void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {
4083   assert(TemplateOrSpecialization.isNull() &&
4084          "Function is already a specialization");
4085   TemplateOrSpecialization = FD;
4086 }
4087 
4088 FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {
4089   return dyn_cast_if_present<FunctionDecl>(
4090       TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4091 }
4092 
4093 bool FunctionDecl::isImplicitlyInstantiable() const {
4094   // If the function is invalid, it can't be implicitly instantiated.
4095   if (isInvalidDecl())
4096     return false;
4097 
4098   switch (getTemplateSpecializationKindForInstantiation()) {
4099   case TSK_Undeclared:
4100   case TSK_ExplicitInstantiationDefinition:
4101   case TSK_ExplicitSpecialization:
4102     return false;
4103 
4104   case TSK_ImplicitInstantiation:
4105     return true;
4106 
4107   case TSK_ExplicitInstantiationDeclaration:
4108     // Handled below.
4109     break;
4110   }
4111 
4112   // Find the actual template from which we will instantiate.
4113   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4114   bool HasPattern = false;
4115   if (PatternDecl)
4116     HasPattern = PatternDecl->hasBody(PatternDecl);
4117 
4118   // C++0x [temp.explicit]p9:
4119   //   Except for inline functions, other explicit instantiation declarations
4120   //   have the effect of suppressing the implicit instantiation of the entity
4121   //   to which they refer.
4122   if (!HasPattern || !PatternDecl)
4123     return true;
4124 
4125   return PatternDecl->isInlined();
4126 }
4127 
4128 bool FunctionDecl::isTemplateInstantiation() const {
4129   // FIXME: Remove this, it's not clear what it means. (Which template
4130   // specialization kind?)
4131   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
4132 }
4133 
4134 FunctionDecl *
4135 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
4136   // If this is a generic lambda call operator specialization, its
4137   // instantiation pattern is always its primary template's pattern
4138   // even if its primary template was instantiated from another
4139   // member template (which happens with nested generic lambdas).
4140   // Since a lambda's call operator's body is transformed eagerly,
4141   // we don't have to go hunting for a prototype definition template
4142   // (i.e. instantiated-from-member-template) to use as an instantiation
4143   // pattern.
4144 
4145   if (isGenericLambdaCallOperatorSpecialization(
4146           dyn_cast<CXXMethodDecl>(this))) {
4147     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4148     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
4149   }
4150 
4151   // Check for a declaration of this function that was instantiated from a
4152   // friend definition.
4153   const FunctionDecl *FD = nullptr;
4154   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4155     FD = this;
4156 
4157   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
4158     if (ForDefinition &&
4159         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
4160       return nullptr;
4161     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4162   }
4163 
4164   if (ForDefinition &&
4165       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
4166     return nullptr;
4167 
4168   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4169     // If we hit a point where the user provided a specialization of this
4170     // template, we're done looking.
4171     while (!ForDefinition || !Primary->isMemberSpecialization()) {
4172       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4173       if (!NewPrimary)
4174         break;
4175       Primary = NewPrimary;
4176     }
4177 
4178     return getDefinitionOrSelf(Primary->getTemplatedDecl());
4179   }
4180 
4181   return nullptr;
4182 }
4183 
4184 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
4185   if (FunctionTemplateSpecializationInfo *Info =
4186           dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4187               TemplateOrSpecialization)) {
4188     return Info->getTemplate();
4189   }
4190   return nullptr;
4191 }
4192 
4193 FunctionTemplateSpecializationInfo *
4194 FunctionDecl::getTemplateSpecializationInfo() const {
4195   return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4196       TemplateOrSpecialization);
4197 }
4198 
4199 const TemplateArgumentList *
4200 FunctionDecl::getTemplateSpecializationArgs() const {
4201   if (FunctionTemplateSpecializationInfo *Info =
4202           dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4203               TemplateOrSpecialization)) {
4204     return Info->TemplateArguments;
4205   }
4206   return nullptr;
4207 }
4208 
4209 const ASTTemplateArgumentListInfo *
4210 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
4211   if (FunctionTemplateSpecializationInfo *Info =
4212           dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4213               TemplateOrSpecialization)) {
4214     return Info->TemplateArgumentsAsWritten;
4215   }
4216   if (DependentFunctionTemplateSpecializationInfo *Info =
4217           dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4218               TemplateOrSpecialization)) {
4219     return Info->TemplateArgumentsAsWritten;
4220   }
4221   return nullptr;
4222 }
4223 
4224 void FunctionDecl::setFunctionTemplateSpecialization(
4225     ASTContext &C, FunctionTemplateDecl *Template,
4226     TemplateArgumentList *TemplateArgs, void *InsertPos,
4227     TemplateSpecializationKind TSK,
4228     const TemplateArgumentListInfo *TemplateArgsAsWritten,
4229     SourceLocation PointOfInstantiation) {
4230   assert((TemplateOrSpecialization.isNull() ||
4231           isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) &&
4232          "Member function is already a specialization");
4233   assert(TSK != TSK_Undeclared &&
4234          "Must specify the type of function template specialization");
4235   assert((TemplateOrSpecialization.isNull() ||
4236           getFriendObjectKind() != FOK_None ||
4237           TSK == TSK_ExplicitSpecialization) &&
4238          "Member specialization must be an explicit specialization");
4239   FunctionTemplateSpecializationInfo *Info =
4240       FunctionTemplateSpecializationInfo::Create(
4241           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4242           PointOfInstantiation,
4243           dyn_cast_if_present<MemberSpecializationInfo *>(
4244               TemplateOrSpecialization));
4245   TemplateOrSpecialization = Info;
4246   Template->addSpecialization(Info, InsertPos);
4247 }
4248 
4249 void FunctionDecl::setDependentTemplateSpecialization(
4250     ASTContext &Context, const UnresolvedSetImpl &Templates,
4251     const TemplateArgumentListInfo *TemplateArgs) {
4252   assert(TemplateOrSpecialization.isNull());
4253   DependentFunctionTemplateSpecializationInfo *Info =
4254       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
4255                                                           TemplateArgs);
4256   TemplateOrSpecialization = Info;
4257 }
4258 
4259 DependentFunctionTemplateSpecializationInfo *
4260 FunctionDecl::getDependentSpecializationInfo() const {
4261   return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4262       TemplateOrSpecialization);
4263 }
4264 
4265 DependentFunctionTemplateSpecializationInfo *
4266 DependentFunctionTemplateSpecializationInfo::Create(
4267     ASTContext &Context, const UnresolvedSetImpl &Candidates,
4268     const TemplateArgumentListInfo *TArgs) {
4269   const auto *TArgsWritten =
4270       TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4271   return new (Context.Allocate(
4272       totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4273       DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4274 }
4275 
4276 DependentFunctionTemplateSpecializationInfo::
4277     DependentFunctionTemplateSpecializationInfo(
4278         const UnresolvedSetImpl &Candidates,
4279         const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4280     : NumCandidates(Candidates.size()),
4281       TemplateArgumentsAsWritten(TemplateArgsWritten) {
4282   std::transform(Candidates.begin(), Candidates.end(),
4283                  getTrailingObjects<FunctionTemplateDecl *>(),
4284                  [](NamedDecl *ND) {
4285                    return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());
4286                  });
4287 }
4288 
4289 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
4290   // For a function template specialization, query the specialization
4291   // information object.
4292   if (FunctionTemplateSpecializationInfo *FTSInfo =
4293           dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4294               TemplateOrSpecialization))
4295     return FTSInfo->getTemplateSpecializationKind();
4296 
4297   if (MemberSpecializationInfo *MSInfo =
4298           dyn_cast_if_present<MemberSpecializationInfo *>(
4299               TemplateOrSpecialization))
4300     return MSInfo->getTemplateSpecializationKind();
4301 
4302   // A dependent function template specialization is an explicit specialization,
4303   // except when it's a friend declaration.
4304   if (isa<DependentFunctionTemplateSpecializationInfo *>(
4305           TemplateOrSpecialization) &&
4306       getFriendObjectKind() == FOK_None)
4307     return TSK_ExplicitSpecialization;
4308 
4309   return TSK_Undeclared;
4310 }
4311 
4312 TemplateSpecializationKind
4313 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
4314   // This is the same as getTemplateSpecializationKind(), except that for a
4315   // function that is both a function template specialization and a member
4316   // specialization, we prefer the member specialization information. Eg:
4317   //
4318   // template<typename T> struct A {
4319   //   template<typename U> void f() {}
4320   //   template<> void f<int>() {}
4321   // };
4322   //
4323   // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4324   // template specialization; both getTemplateSpecializationKind() and
4325   // getTemplateSpecializationKindForInstantiation() will return
4326   // TSK_ExplicitSpecialization.
4327   //
4328   // For A<int>::f<int>():
4329   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4330   // * getTemplateSpecializationKindForInstantiation() will return
4331   //       TSK_ImplicitInstantiation
4332   //
4333   // This reflects the facts that A<int>::f<int> is an explicit specialization
4334   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4335   // from A::f<int> if a definition is needed.
4336   if (FunctionTemplateSpecializationInfo *FTSInfo =
4337           dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4338               TemplateOrSpecialization)) {
4339     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4340       return MSInfo->getTemplateSpecializationKind();
4341     return FTSInfo->getTemplateSpecializationKind();
4342   }
4343 
4344   if (MemberSpecializationInfo *MSInfo =
4345           dyn_cast_if_present<MemberSpecializationInfo *>(
4346               TemplateOrSpecialization))
4347     return MSInfo->getTemplateSpecializationKind();
4348 
4349   if (isa<DependentFunctionTemplateSpecializationInfo *>(
4350           TemplateOrSpecialization) &&
4351       getFriendObjectKind() == FOK_None)
4352     return TSK_ExplicitSpecialization;
4353 
4354   return TSK_Undeclared;
4355 }
4356 
4357 void
4358 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4359                                           SourceLocation PointOfInstantiation) {
4360   if (FunctionTemplateSpecializationInfo *FTSInfo =
4361           dyn_cast<FunctionTemplateSpecializationInfo *>(
4362               TemplateOrSpecialization)) {
4363     FTSInfo->setTemplateSpecializationKind(TSK);
4364     if (TSK != TSK_ExplicitSpecialization &&
4365         PointOfInstantiation.isValid() &&
4366         FTSInfo->getPointOfInstantiation().isInvalid()) {
4367       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4368       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4369         L->InstantiationRequested(this);
4370     }
4371   } else if (MemberSpecializationInfo *MSInfo =
4372                  dyn_cast<MemberSpecializationInfo *>(
4373                      TemplateOrSpecialization)) {
4374     MSInfo->setTemplateSpecializationKind(TSK);
4375     if (TSK != TSK_ExplicitSpecialization &&
4376         PointOfInstantiation.isValid() &&
4377         MSInfo->getPointOfInstantiation().isInvalid()) {
4378       MSInfo->setPointOfInstantiation(PointOfInstantiation);
4379       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4380         L->InstantiationRequested(this);
4381     }
4382   } else
4383     llvm_unreachable("Function cannot have a template specialization kind");
4384 }
4385 
4386 SourceLocation FunctionDecl::getPointOfInstantiation() const {
4387   if (FunctionTemplateSpecializationInfo *FTSInfo
4388         = TemplateOrSpecialization.dyn_cast<
4389                                         FunctionTemplateSpecializationInfo*>())
4390     return FTSInfo->getPointOfInstantiation();
4391   if (MemberSpecializationInfo *MSInfo =
4392           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4393     return MSInfo->getPointOfInstantiation();
4394 
4395   return SourceLocation();
4396 }
4397 
4398 bool FunctionDecl::isOutOfLine() const {
4399   if (Decl::isOutOfLine())
4400     return true;
4401 
4402   // If this function was instantiated from a member function of a
4403   // class template, check whether that member function was defined out-of-line.
4404   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4405     const FunctionDecl *Definition;
4406     if (FD->hasBody(Definition))
4407       return Definition->isOutOfLine();
4408   }
4409 
4410   // If this function was instantiated from a function template,
4411   // check whether that function template was defined out-of-line.
4412   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4413     const FunctionDecl *Definition;
4414     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4415       return Definition->isOutOfLine();
4416   }
4417 
4418   return false;
4419 }
4420 
4421 SourceRange FunctionDecl::getSourceRange() const {
4422   return SourceRange(getOuterLocStart(), EndRangeLoc);
4423 }
4424 
4425 unsigned FunctionDecl::getMemoryFunctionKind() const {
4426   IdentifierInfo *FnInfo = getIdentifier();
4427 
4428   if (!FnInfo)
4429     return 0;
4430 
4431   // Builtin handling.
4432   switch (getBuiltinID()) {
4433   case Builtin::BI__builtin_memset:
4434   case Builtin::BI__builtin___memset_chk:
4435   case Builtin::BImemset:
4436     return Builtin::BImemset;
4437 
4438   case Builtin::BI__builtin_memcpy:
4439   case Builtin::BI__builtin___memcpy_chk:
4440   case Builtin::BImemcpy:
4441     return Builtin::BImemcpy;
4442 
4443   case Builtin::BI__builtin_mempcpy:
4444   case Builtin::BI__builtin___mempcpy_chk:
4445   case Builtin::BImempcpy:
4446     return Builtin::BImempcpy;
4447 
4448   case Builtin::BI__builtin_memmove:
4449   case Builtin::BI__builtin___memmove_chk:
4450   case Builtin::BImemmove:
4451     return Builtin::BImemmove;
4452 
4453   case Builtin::BIstrlcpy:
4454   case Builtin::BI__builtin___strlcpy_chk:
4455     return Builtin::BIstrlcpy;
4456 
4457   case Builtin::BIstrlcat:
4458   case Builtin::BI__builtin___strlcat_chk:
4459     return Builtin::BIstrlcat;
4460 
4461   case Builtin::BI__builtin_memcmp:
4462   case Builtin::BImemcmp:
4463     return Builtin::BImemcmp;
4464 
4465   case Builtin::BI__builtin_bcmp:
4466   case Builtin::BIbcmp:
4467     return Builtin::BIbcmp;
4468 
4469   case Builtin::BI__builtin_strncpy:
4470   case Builtin::BI__builtin___strncpy_chk:
4471   case Builtin::BIstrncpy:
4472     return Builtin::BIstrncpy;
4473 
4474   case Builtin::BI__builtin_strncmp:
4475   case Builtin::BIstrncmp:
4476     return Builtin::BIstrncmp;
4477 
4478   case Builtin::BI__builtin_strncasecmp:
4479   case Builtin::BIstrncasecmp:
4480     return Builtin::BIstrncasecmp;
4481 
4482   case Builtin::BI__builtin_strncat:
4483   case Builtin::BI__builtin___strncat_chk:
4484   case Builtin::BIstrncat:
4485     return Builtin::BIstrncat;
4486 
4487   case Builtin::BI__builtin_strndup:
4488   case Builtin::BIstrndup:
4489     return Builtin::BIstrndup;
4490 
4491   case Builtin::BI__builtin_strlen:
4492   case Builtin::BIstrlen:
4493     return Builtin::BIstrlen;
4494 
4495   case Builtin::BI__builtin_bzero:
4496   case Builtin::BIbzero:
4497     return Builtin::BIbzero;
4498 
4499   case Builtin::BI__builtin_bcopy:
4500   case Builtin::BIbcopy:
4501     return Builtin::BIbcopy;
4502 
4503   case Builtin::BIfree:
4504     return Builtin::BIfree;
4505 
4506   default:
4507     if (isExternC()) {
4508       if (FnInfo->isStr("memset"))
4509         return Builtin::BImemset;
4510       if (FnInfo->isStr("memcpy"))
4511         return Builtin::BImemcpy;
4512       if (FnInfo->isStr("mempcpy"))
4513         return Builtin::BImempcpy;
4514       if (FnInfo->isStr("memmove"))
4515         return Builtin::BImemmove;
4516       if (FnInfo->isStr("memcmp"))
4517         return Builtin::BImemcmp;
4518       if (FnInfo->isStr("bcmp"))
4519         return Builtin::BIbcmp;
4520       if (FnInfo->isStr("strncpy"))
4521         return Builtin::BIstrncpy;
4522       if (FnInfo->isStr("strncmp"))
4523         return Builtin::BIstrncmp;
4524       if (FnInfo->isStr("strncasecmp"))
4525         return Builtin::BIstrncasecmp;
4526       if (FnInfo->isStr("strncat"))
4527         return Builtin::BIstrncat;
4528       if (FnInfo->isStr("strndup"))
4529         return Builtin::BIstrndup;
4530       if (FnInfo->isStr("strlen"))
4531         return Builtin::BIstrlen;
4532       if (FnInfo->isStr("bzero"))
4533         return Builtin::BIbzero;
4534       if (FnInfo->isStr("bcopy"))
4535         return Builtin::BIbcopy;
4536     } else if (isInStdNamespace()) {
4537       if (FnInfo->isStr("free"))
4538         return Builtin::BIfree;
4539     }
4540     break;
4541   }
4542   return 0;
4543 }
4544 
4545 unsigned FunctionDecl::getODRHash() const {
4546   assert(hasODRHash());
4547   return ODRHash;
4548 }
4549 
4550 unsigned FunctionDecl::getODRHash() {
4551   if (hasODRHash())
4552     return ODRHash;
4553 
4554   if (auto *FT = getInstantiatedFromMemberFunction()) {
4555     setHasODRHash(true);
4556     ODRHash = FT->getODRHash();
4557     return ODRHash;
4558   }
4559 
4560   class ODRHash Hash;
4561   Hash.AddFunctionDecl(this);
4562   setHasODRHash(true);
4563   ODRHash = Hash.CalculateHash();
4564   return ODRHash;
4565 }
4566 
4567 //===----------------------------------------------------------------------===//
4568 // FieldDecl Implementation
4569 //===----------------------------------------------------------------------===//
4570 
4571 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4572                              SourceLocation StartLoc, SourceLocation IdLoc,
4573                              const IdentifierInfo *Id, QualType T,
4574                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4575                              InClassInitStyle InitStyle) {
4576   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4577                                BW, Mutable, InitStyle);
4578 }
4579 
4580 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
4581   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4582                                SourceLocation(), nullptr, QualType(), nullptr,
4583                                nullptr, false, ICIS_NoInit);
4584 }
4585 
4586 bool FieldDecl::isAnonymousStructOrUnion() const {
4587   if (!isImplicit() || getDeclName())
4588     return false;
4589 
4590   if (const auto *Record = getType()->getAs<RecordType>())
4591     return Record->getDecl()->isAnonymousStructOrUnion();
4592 
4593   return false;
4594 }
4595 
4596 Expr *FieldDecl::getInClassInitializer() const {
4597   if (!hasInClassInitializer())
4598     return nullptr;
4599 
4600   LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4601   return cast_if_present<Expr>(
4602       InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4603                          : InitPtr.get(nullptr));
4604 }
4605 
4606 void FieldDecl::setInClassInitializer(Expr *NewInit) {
4607   setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4608 }
4609 
4610 void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4611   assert(hasInClassInitializer() && !getInClassInitializer());
4612   if (BitField)
4613     InitAndBitWidth->Init = NewInit;
4614   else
4615     Init = NewInit;
4616 }
4617 
4618 unsigned FieldDecl::getBitWidthValue() const {
4619   assert(isBitField() && "not a bitfield");
4620   assert(isa<ConstantExpr>(getBitWidth()));
4621   assert(cast<ConstantExpr>(getBitWidth())->hasAPValueResult());
4622   assert(cast<ConstantExpr>(getBitWidth())->getAPValueResult().isInt());
4623   return cast<ConstantExpr>(getBitWidth())
4624       ->getAPValueResult()
4625       .getInt()
4626       .getZExtValue();
4627 }
4628 
4629 bool FieldDecl::isZeroLengthBitField() const {
4630   return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&
4631          getBitWidthValue() == 0;
4632 }
4633 
4634 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4635   if (isZeroLengthBitField())
4636     return true;
4637 
4638   // C++2a [intro.object]p7:
4639   //   An object has nonzero size if it
4640   //     -- is not a potentially-overlapping subobject, or
4641   if (!hasAttr<NoUniqueAddressAttr>())
4642     return false;
4643 
4644   //     -- is not of class type, or
4645   const auto *RT = getType()->getAs<RecordType>();
4646   if (!RT)
4647     return false;
4648   const RecordDecl *RD = RT->getDecl()->getDefinition();
4649   if (!RD) {
4650     assert(isInvalidDecl() && "valid field has incomplete type");
4651     return false;
4652   }
4653 
4654   //     -- [has] virtual member functions or virtual base classes, or
4655   //     -- has subobjects of nonzero size or bit-fields of nonzero length
4656   const auto *CXXRD = cast<CXXRecordDecl>(RD);
4657   if (!CXXRD->isEmpty())
4658     return false;
4659 
4660   // Otherwise, [...] the circumstances under which the object has zero size
4661   // are implementation-defined.
4662   if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4663     return true;
4664 
4665   // MS ABI: has nonzero size if it is a class type with class type fields,
4666   // whether or not they have nonzero size
4667   return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4668     return Field->getType()->getAs<RecordType>();
4669   });
4670 }
4671 
4672 bool FieldDecl::isPotentiallyOverlapping() const {
4673   return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4674 }
4675 
4676 void FieldDecl::setCachedFieldIndex() const {
4677   assert(this == getCanonicalDecl() &&
4678          "should be called on the canonical decl");
4679 
4680   unsigned Index = 0;
4681   const RecordDecl *RD = getParent()->getDefinition();
4682   assert(RD && "requested index for field of struct with no definition");
4683 
4684   for (auto *Field : RD->fields()) {
4685     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4686     assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4687            "overflow in field numbering");
4688     ++Index;
4689   }
4690 
4691   assert(CachedFieldIndex && "failed to find field in parent");
4692 }
4693 
4694 SourceRange FieldDecl::getSourceRange() const {
4695   const Expr *FinalExpr = getInClassInitializer();
4696   if (!FinalExpr)
4697     FinalExpr = getBitWidth();
4698   if (FinalExpr)
4699     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4700   return DeclaratorDecl::getSourceRange();
4701 }
4702 
4703 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4704   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4705          "capturing type in non-lambda or captured record.");
4706   assert(StorageKind == ISK_NoInit && !BitField &&
4707          "bit-field or field with default member initializer cannot capture "
4708          "VLA type");
4709   StorageKind = ISK_CapturedVLAType;
4710   CapturedVLAType = VLAType;
4711 }
4712 
4713 void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4714   // Print unnamed members using name of their type.
4715   if (isAnonymousStructOrUnion()) {
4716     this->getType().print(OS, Policy);
4717     return;
4718   }
4719   // Otherwise, do the normal printing.
4720   DeclaratorDecl::printName(OS, Policy);
4721 }
4722 
4723 const FieldDecl *FieldDecl::findCountedByField() const {
4724   const auto *CAT = getType()->getAs<CountAttributedType>();
4725   if (!CAT)
4726     return nullptr;
4727 
4728   const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr());
4729   const auto *CountDecl = CountDRE->getDecl();
4730   if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl))
4731     CountDecl = IFD->getAnonField();
4732 
4733   return dyn_cast<FieldDecl>(CountDecl);
4734 }
4735 
4736 //===----------------------------------------------------------------------===//
4737 // TagDecl Implementation
4738 //===----------------------------------------------------------------------===//
4739 
4740 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4741                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4742                  SourceLocation StartL)
4743     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4744       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4745   assert((DK != Enum || TK == TagTypeKind::Enum) &&
4746          "EnumDecl not matched with TagTypeKind::Enum");
4747   setPreviousDecl(PrevDecl);
4748   setTagKind(TK);
4749   setCompleteDefinition(false);
4750   setBeingDefined(false);
4751   setEmbeddedInDeclarator(false);
4752   setFreeStanding(false);
4753   setCompleteDefinitionRequired(false);
4754   TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4755 }
4756 
4757 SourceLocation TagDecl::getOuterLocStart() const {
4758   return getTemplateOrInnerLocStart(this);
4759 }
4760 
4761 SourceRange TagDecl::getSourceRange() const {
4762   SourceLocation RBraceLoc = BraceRange.getEnd();
4763   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4764   return SourceRange(getOuterLocStart(), E);
4765 }
4766 
4767 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4768 
4769 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4770   TypedefNameDeclOrQualifier = TDD;
4771   if (const Type *T = getTypeForDecl()) {
4772     (void)T;
4773     assert(T->isLinkageValid());
4774   }
4775   assert(isLinkageValid());
4776 }
4777 
4778 void TagDecl::startDefinition() {
4779   setBeingDefined(true);
4780 
4781   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4782     struct CXXRecordDecl::DefinitionData *Data =
4783       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4784     for (auto *I : redecls())
4785       cast<CXXRecordDecl>(I)->DefinitionData = Data;
4786   }
4787 }
4788 
4789 void TagDecl::completeDefinition() {
4790   assert((!isa<CXXRecordDecl>(this) ||
4791           cast<CXXRecordDecl>(this)->hasDefinition()) &&
4792          "definition completed but not started");
4793 
4794   setCompleteDefinition(true);
4795   setBeingDefined(false);
4796 
4797   if (ASTMutationListener *L = getASTMutationListener())
4798     L->CompletedTagDefinition(this);
4799 }
4800 
4801 TagDecl *TagDecl::getDefinition() const {
4802   if (isCompleteDefinition())
4803     return const_cast<TagDecl *>(this);
4804 
4805   // If it's possible for us to have an out-of-date definition, check now.
4806   if (mayHaveOutOfDateDef()) {
4807     if (IdentifierInfo *II = getIdentifier()) {
4808       if (II->isOutOfDate()) {
4809         updateOutOfDate(*II);
4810       }
4811     }
4812   }
4813 
4814   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4815     return CXXRD->getDefinition();
4816 
4817   for (auto *R : redecls())
4818     if (R->isCompleteDefinition())
4819       return R;
4820 
4821   return nullptr;
4822 }
4823 
4824 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4825   if (QualifierLoc) {
4826     // Make sure the extended qualifier info is allocated.
4827     if (!hasExtInfo())
4828       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4829     // Set qualifier info.
4830     getExtInfo()->QualifierLoc = QualifierLoc;
4831   } else {
4832     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4833     if (hasExtInfo()) {
4834       if (getExtInfo()->NumTemplParamLists == 0) {
4835         getASTContext().Deallocate(getExtInfo());
4836         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4837       }
4838       else
4839         getExtInfo()->QualifierLoc = QualifierLoc;
4840     }
4841   }
4842 }
4843 
4844 void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4845   DeclarationName Name = getDeclName();
4846   // If the name is supposed to have an identifier but does not have one, then
4847   // the tag is anonymous and we should print it differently.
4848   if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4849     // If the caller wanted to print a qualified name, they've already printed
4850     // the scope. And if the caller doesn't want that, the scope information
4851     // is already printed as part of the type.
4852     PrintingPolicy Copy(Policy);
4853     Copy.SuppressScope = true;
4854     getASTContext().getTagDeclType(this).print(OS, Copy);
4855     return;
4856   }
4857   // Otherwise, do the normal printing.
4858   Name.print(OS, Policy);
4859 }
4860 
4861 void TagDecl::setTemplateParameterListsInfo(
4862     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4863   assert(!TPLists.empty());
4864   // Make sure the extended decl info is allocated.
4865   if (!hasExtInfo())
4866     // Allocate external info struct.
4867     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4868   // Set the template parameter lists info.
4869   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4870 }
4871 
4872 //===----------------------------------------------------------------------===//
4873 // EnumDecl Implementation
4874 //===----------------------------------------------------------------------===//
4875 
4876 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4877                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4878                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4879     : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4880   assert(Scoped || !ScopedUsingClassTag);
4881   IntegerType = nullptr;
4882   setNumPositiveBits(0);
4883   setNumNegativeBits(0);
4884   setScoped(Scoped);
4885   setScopedUsingClassTag(ScopedUsingClassTag);
4886   setFixed(Fixed);
4887   setHasODRHash(false);
4888   ODRHash = 0;
4889 }
4890 
4891 void EnumDecl::anchor() {}
4892 
4893 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4894                            SourceLocation StartLoc, SourceLocation IdLoc,
4895                            IdentifierInfo *Id,
4896                            EnumDecl *PrevDecl, bool IsScoped,
4897                            bool IsScopedUsingClassTag, bool IsFixed) {
4898   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4899                                     IsScoped, IsScopedUsingClassTag, IsFixed);
4900   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4901   C.getTypeDeclType(Enum, PrevDecl);
4902   return Enum;
4903 }
4904 
4905 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
4906   EnumDecl *Enum =
4907       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4908                            nullptr, nullptr, false, false, false);
4909   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4910   return Enum;
4911 }
4912 
4913 SourceRange EnumDecl::getIntegerTypeRange() const {
4914   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4915     return TI->getTypeLoc().getSourceRange();
4916   return SourceRange();
4917 }
4918 
4919 void EnumDecl::completeDefinition(QualType NewType,
4920                                   QualType NewPromotionType,
4921                                   unsigned NumPositiveBits,
4922                                   unsigned NumNegativeBits) {
4923   assert(!isCompleteDefinition() && "Cannot redefine enums!");
4924   if (!IntegerType)
4925     IntegerType = NewType.getTypePtr();
4926   PromotionType = NewPromotionType;
4927   setNumPositiveBits(NumPositiveBits);
4928   setNumNegativeBits(NumNegativeBits);
4929   TagDecl::completeDefinition();
4930 }
4931 
4932 bool EnumDecl::isClosed() const {
4933   if (const auto *A = getAttr<EnumExtensibilityAttr>())
4934     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4935   return true;
4936 }
4937 
4938 bool EnumDecl::isClosedFlag() const {
4939   return isClosed() && hasAttr<FlagEnumAttr>();
4940 }
4941 
4942 bool EnumDecl::isClosedNonFlag() const {
4943   return isClosed() && !hasAttr<FlagEnumAttr>();
4944 }
4945 
4946 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4947   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4948     return MSI->getTemplateSpecializationKind();
4949 
4950   return TSK_Undeclared;
4951 }
4952 
4953 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4954                                          SourceLocation PointOfInstantiation) {
4955   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4956   assert(MSI && "Not an instantiated member enumeration?");
4957   MSI->setTemplateSpecializationKind(TSK);
4958   if (TSK != TSK_ExplicitSpecialization &&
4959       PointOfInstantiation.isValid() &&
4960       MSI->getPointOfInstantiation().isInvalid())
4961     MSI->setPointOfInstantiation(PointOfInstantiation);
4962 }
4963 
4964 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4965   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4966     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4967       EnumDecl *ED = getInstantiatedFromMemberEnum();
4968       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4969         ED = NewED;
4970       return getDefinitionOrSelf(ED);
4971     }
4972   }
4973 
4974   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4975          "couldn't find pattern for enum instantiation");
4976   return nullptr;
4977 }
4978 
4979 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4980   if (SpecializationInfo)
4981     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4982 
4983   return nullptr;
4984 }
4985 
4986 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4987                                             TemplateSpecializationKind TSK) {
4988   assert(!SpecializationInfo && "Member enum is already a specialization");
4989   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4990 }
4991 
4992 unsigned EnumDecl::getODRHash() {
4993   if (hasODRHash())
4994     return ODRHash;
4995 
4996   class ODRHash Hash;
4997   Hash.AddEnumDecl(this);
4998   setHasODRHash(true);
4999   ODRHash = Hash.CalculateHash();
5000   return ODRHash;
5001 }
5002 
5003 SourceRange EnumDecl::getSourceRange() const {
5004   auto Res = TagDecl::getSourceRange();
5005   // Set end-point to enum-base, e.g. enum foo : ^bar
5006   if (auto *TSI = getIntegerTypeSourceInfo()) {
5007     // TagDecl doesn't know about the enum base.
5008     if (!getBraceRange().getEnd().isValid())
5009       Res.setEnd(TSI->getTypeLoc().getEndLoc());
5010   }
5011   return Res;
5012 }
5013 
5014 void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
5015   unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
5016   unsigned NumNegativeBits = getNumNegativeBits();
5017   unsigned NumPositiveBits = getNumPositiveBits();
5018 
5019   if (NumNegativeBits) {
5020     unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
5021     Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
5022     Min = -Max;
5023   } else {
5024     Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
5025     Min = llvm::APInt::getZero(Bitwidth);
5026   }
5027 }
5028 
5029 //===----------------------------------------------------------------------===//
5030 // RecordDecl Implementation
5031 //===----------------------------------------------------------------------===//
5032 
5033 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
5034                        DeclContext *DC, SourceLocation StartLoc,
5035                        SourceLocation IdLoc, IdentifierInfo *Id,
5036                        RecordDecl *PrevDecl)
5037     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5038   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5039   setHasFlexibleArrayMember(false);
5040   setAnonymousStructOrUnion(false);
5041   setHasObjectMember(false);
5042   setHasVolatileMember(false);
5043   setHasLoadedFieldsFromExternalStorage(false);
5044   setNonTrivialToPrimitiveDefaultInitialize(false);
5045   setNonTrivialToPrimitiveCopy(false);
5046   setNonTrivialToPrimitiveDestroy(false);
5047   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
5048   setHasNonTrivialToPrimitiveDestructCUnion(false);
5049   setHasNonTrivialToPrimitiveCopyCUnion(false);
5050   setHasUninitializedExplicitInitFields(false);
5051   setParamDestroyedInCallee(false);
5052   setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);
5053   setIsRandomized(false);
5054   setODRHash(0);
5055 }
5056 
5057 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
5058                                SourceLocation StartLoc, SourceLocation IdLoc,
5059                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
5060   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
5061                                          StartLoc, IdLoc, Id, PrevDecl);
5062   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5063 
5064   C.getTypeDeclType(R, PrevDecl);
5065   return R;
5066 }
5067 
5068 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C,
5069                                            GlobalDeclID ID) {
5070   RecordDecl *R = new (C, ID)
5071       RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(),
5072                  SourceLocation(), nullptr, nullptr);
5073   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5074   return R;
5075 }
5076 
5077 bool RecordDecl::isInjectedClassName() const {
5078   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
5079     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
5080 }
5081 
5082 bool RecordDecl::isLambda() const {
5083   if (auto RD = dyn_cast<CXXRecordDecl>(this))
5084     return RD->isLambda();
5085   return false;
5086 }
5087 
5088 bool RecordDecl::isCapturedRecord() const {
5089   return hasAttr<CapturedRecordAttr>();
5090 }
5091 
5092 void RecordDecl::setCapturedRecord() {
5093   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
5094 }
5095 
5096 bool RecordDecl::isOrContainsUnion() const {
5097   if (isUnion())
5098     return true;
5099 
5100   if (const RecordDecl *Def = getDefinition()) {
5101     for (const FieldDecl *FD : Def->fields()) {
5102       const RecordType *RT = FD->getType()->getAs<RecordType>();
5103       if (RT && RT->getDecl()->isOrContainsUnion())
5104         return true;
5105     }
5106   }
5107 
5108   return false;
5109 }
5110 
5111 RecordDecl::field_iterator RecordDecl::field_begin() const {
5112   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
5113     LoadFieldsFromExternalStorage();
5114   // This is necessary for correctness for C++ with modules.
5115   // FIXME: Come up with a test case that breaks without definition.
5116   if (RecordDecl *D = getDefinition(); D && D != this)
5117     return D->field_begin();
5118   return field_iterator(decl_iterator(FirstDecl));
5119 }
5120 
5121 /// completeDefinition - Notes that the definition of this type is now
5122 /// complete.
5123 void RecordDecl::completeDefinition() {
5124   assert(!isCompleteDefinition() && "Cannot redefine record!");
5125   TagDecl::completeDefinition();
5126 
5127   ASTContext &Ctx = getASTContext();
5128 
5129   // Layouts are dumped when computed, so if we are dumping for all complete
5130   // types, we need to force usage to get types that wouldn't be used elsewhere.
5131   //
5132   // If the type is dependent, then we can't compute its layout because there
5133   // is no way for us to know the size or alignment of a dependent type. Also
5134   // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5135   // on that.
5136   if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5137       !isInvalidDecl())
5138     (void)Ctx.getASTRecordLayout(this);
5139 }
5140 
5141 /// isMsStruct - Get whether or not this record uses ms_struct layout.
5142 /// This which can be turned on with an attribute, pragma, or the
5143 /// -mms-bitfields command-line option.
5144 bool RecordDecl::isMsStruct(const ASTContext &C) const {
5145   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
5146 }
5147 
5148 void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {
5149   std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
5150   LastDecl->NextInContextAndBits.setPointer(nullptr);
5151   setIsRandomized(true);
5152 }
5153 
5154 void RecordDecl::LoadFieldsFromExternalStorage() const {
5155   ExternalASTSource *Source = getASTContext().getExternalSource();
5156   assert(hasExternalLexicalStorage() && Source && "No external storage?");
5157 
5158   // Notify that we have a RecordDecl doing some initialization.
5159   ExternalASTSource::Deserializing TheFields(Source);
5160 
5161   SmallVector<Decl*, 64> Decls;
5162   setHasLoadedFieldsFromExternalStorage(true);
5163   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
5164     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
5165   }, Decls);
5166 
5167 #ifndef NDEBUG
5168   // Check that all decls we got were FieldDecls.
5169   for (unsigned i=0, e=Decls.size(); i != e; ++i)
5170     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5171 #endif
5172 
5173   if (Decls.empty())
5174     return;
5175 
5176   auto [ExternalFirst, ExternalLast] =
5177       BuildDeclChain(Decls,
5178                      /*FieldsAlreadyLoaded=*/false);
5179   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5180   FirstDecl = ExternalFirst;
5181   if (!LastDecl)
5182     LastDecl = ExternalLast;
5183 }
5184 
5185 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5186   ASTContext &Context = getASTContext();
5187   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5188       (SanitizerKind::Address | SanitizerKind::KernelAddress);
5189   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5190     return false;
5191   const auto &NoSanitizeList = Context.getNoSanitizeList();
5192   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
5193   // We may be able to relax some of these requirements.
5194   int ReasonToReject = -1;
5195   if (!CXXRD || CXXRD->isExternCContext())
5196     ReasonToReject = 0;  // is not C++.
5197   else if (CXXRD->hasAttr<PackedAttr>())
5198     ReasonToReject = 1;  // is packed.
5199   else if (CXXRD->isUnion())
5200     ReasonToReject = 2;  // is a union.
5201   else if (CXXRD->isTriviallyCopyable())
5202     ReasonToReject = 3;  // is trivially copyable.
5203   else if (CXXRD->hasTrivialDestructor())
5204     ReasonToReject = 4;  // has trivial destructor.
5205   else if (CXXRD->isStandardLayout())
5206     ReasonToReject = 5;  // is standard layout.
5207   else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
5208                                            "field-padding"))
5209     ReasonToReject = 6;  // is in an excluded file.
5210   else if (NoSanitizeList.containsType(
5211                EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
5212     ReasonToReject = 7;  // The type is excluded.
5213 
5214   if (EmitRemark) {
5215     if (ReasonToReject >= 0)
5216       Context.getDiagnostics().Report(
5217           getLocation(),
5218           diag::remark_sanitize_address_insert_extra_padding_rejected)
5219           << getQualifiedNameAsString() << ReasonToReject;
5220     else
5221       Context.getDiagnostics().Report(
5222           getLocation(),
5223           diag::remark_sanitize_address_insert_extra_padding_accepted)
5224           << getQualifiedNameAsString();
5225   }
5226   return ReasonToReject < 0;
5227 }
5228 
5229 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
5230   for (const auto *I : fields()) {
5231     if (I->getIdentifier())
5232       return I;
5233 
5234     if (const auto *RT = I->getType()->getAs<RecordType>())
5235       if (const FieldDecl *NamedDataMember =
5236               RT->getDecl()->findFirstNamedDataMember())
5237         return NamedDataMember;
5238   }
5239 
5240   // We didn't find a named data member.
5241   return nullptr;
5242 }
5243 
5244 unsigned RecordDecl::getODRHash() {
5245   if (hasODRHash())
5246     return RecordDeclBits.ODRHash;
5247 
5248   // Only calculate hash on first call of getODRHash per record.
5249   ODRHash Hash;
5250   Hash.AddRecordDecl(this);
5251   // For RecordDecl the ODRHash is stored in the remaining
5252   // bits of RecordDeclBits, adjust the hash to accommodate.
5253   static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32);
5254   setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits));
5255   return RecordDeclBits.ODRHash;
5256 }
5257 
5258 //===----------------------------------------------------------------------===//
5259 // BlockDecl Implementation
5260 //===----------------------------------------------------------------------===//
5261 
5262 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
5263     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5264   setIsVariadic(false);
5265   setCapturesCXXThis(false);
5266   setBlockMissingReturnType(true);
5267   setIsConversionFromLambda(false);
5268   setDoesNotEscape(false);
5269   setCanAvoidCopyToHeap(false);
5270 }
5271 
5272 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
5273   assert(!ParamInfo && "Already has param info!");
5274 
5275   // Zero params -> null pointer.
5276   if (!NewParamInfo.empty()) {
5277     NumParams = NewParamInfo.size();
5278     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5279     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
5280   }
5281 }
5282 
5283 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
5284                             bool CapturesCXXThis) {
5285   this->setCapturesCXXThis(CapturesCXXThis);
5286   this->NumCaptures = Captures.size();
5287 
5288   if (Captures.empty()) {
5289     this->Captures = nullptr;
5290     return;
5291   }
5292 
5293   this->Captures = Captures.copy(Context).data();
5294 }
5295 
5296 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5297   for (const auto &I : captures())
5298     // Only auto vars can be captured, so no redeclaration worries.
5299     if (I.getVariable() == variable)
5300       return true;
5301 
5302   return false;
5303 }
5304 
5305 SourceRange BlockDecl::getSourceRange() const {
5306   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5307 }
5308 
5309 //===----------------------------------------------------------------------===//
5310 // Other Decl Allocation/Deallocation Method Implementations
5311 //===----------------------------------------------------------------------===//
5312 
5313 void TranslationUnitDecl::anchor() {}
5314 
5315 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
5316   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5317 }
5318 
5319 void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) {
5320   AnonymousNamespace = D;
5321 
5322   if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5323     Listener->AddedAnonymousNamespace(this, D);
5324 }
5325 
5326 void PragmaCommentDecl::anchor() {}
5327 
5328 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
5329                                              TranslationUnitDecl *DC,
5330                                              SourceLocation CommentLoc,
5331                                              PragmaMSCommentKind CommentKind,
5332                                              StringRef Arg) {
5333   PragmaCommentDecl *PCD =
5334       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
5335           PragmaCommentDecl(DC, CommentLoc, CommentKind);
5336   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
5337   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
5338   return PCD;
5339 }
5340 
5341 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
5342                                                          GlobalDeclID ID,
5343                                                          unsigned ArgSize) {
5344   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
5345       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
5346 }
5347 
5348 void PragmaDetectMismatchDecl::anchor() {}
5349 
5350 PragmaDetectMismatchDecl *
5351 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
5352                                  SourceLocation Loc, StringRef Name,
5353                                  StringRef Value) {
5354   size_t ValueStart = Name.size() + 1;
5355   PragmaDetectMismatchDecl *PDMD =
5356       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
5357           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5358   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
5359   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
5360   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
5361          Value.size());
5362   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
5363   return PDMD;
5364 }
5365 
5366 PragmaDetectMismatchDecl *
5367 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5368                                              unsigned NameValueSize) {
5369   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5370       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
5371 }
5372 
5373 void ExternCContextDecl::anchor() {}
5374 
5375 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
5376                                                TranslationUnitDecl *DC) {
5377   return new (C, DC) ExternCContextDecl(DC);
5378 }
5379 
5380 void LabelDecl::anchor() {}
5381 
5382 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5383                              SourceLocation IdentL, IdentifierInfo *II) {
5384   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5385 }
5386 
5387 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5388                              SourceLocation IdentL, IdentifierInfo *II,
5389                              SourceLocation GnuLabelL) {
5390   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5391   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5392 }
5393 
5394 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5395   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5396                                SourceLocation());
5397 }
5398 
5399 void LabelDecl::setMSAsmLabel(StringRef Name) {
5400 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5401   memcpy(Buffer, Name.data(), Name.size());
5402   Buffer[Name.size()] = '\0';
5403   MSAsmName = Buffer;
5404 }
5405 
5406 void ValueDecl::anchor() {}
5407 
5408 bool ValueDecl::isWeak() const {
5409   auto *MostRecent = getMostRecentDecl();
5410   return MostRecent->hasAttr<WeakAttr>() ||
5411          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5412 }
5413 
5414 bool ValueDecl::isInitCapture() const {
5415   if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5416     return Var->isInitCapture();
5417   return false;
5418 }
5419 
5420 bool ValueDecl::isParameterPack() const {
5421   if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
5422     return NTTP->isParameterPack();
5423 
5424   return isa_and_nonnull<PackExpansionType>(getType().getTypePtrOrNull());
5425 }
5426 
5427 void ImplicitParamDecl::anchor() {}
5428 
5429 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
5430                                              SourceLocation IdLoc,
5431                                              IdentifierInfo *Id, QualType Type,
5432                                              ImplicitParamKind ParamKind) {
5433   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5434 }
5435 
5436 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
5437                                              ImplicitParamKind ParamKind) {
5438   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5439 }
5440 
5441 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
5442                                                          GlobalDeclID ID) {
5443   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
5444 }
5445 
5446 FunctionDecl *
5447 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5448                      const DeclarationNameInfo &NameInfo, QualType T,
5449                      TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5450                      bool isInlineSpecified, bool hasWrittenPrototype,
5451                      ConstexprSpecKind ConstexprKind,
5452                      Expr *TrailingRequiresClause) {
5453   FunctionDecl *New = new (C, DC) FunctionDecl(
5454       Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5455       isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5456   New->setHasWrittenPrototype(hasWrittenPrototype);
5457   return New;
5458 }
5459 
5460 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5461   return new (C, ID) FunctionDecl(
5462       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
5463       nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
5464 }
5465 
5466 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5467   return new (C, DC) BlockDecl(DC, L);
5468 }
5469 
5470 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5471   return new (C, ID) BlockDecl(nullptr, SourceLocation());
5472 }
5473 
5474 OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams)
5475     : Decl(OutlinedFunction, DC, SourceLocation()),
5476       DeclContext(OutlinedFunction), NumParams(NumParams),
5477       BodyAndNothrow(nullptr, false) {}
5478 
5479 OutlinedFunctionDecl *OutlinedFunctionDecl::Create(ASTContext &C,
5480                                                    DeclContext *DC,
5481                                                    unsigned NumParams) {
5482   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5483       OutlinedFunctionDecl(DC, NumParams);
5484 }
5485 
5486 OutlinedFunctionDecl *
5487 OutlinedFunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5488                                          unsigned NumParams) {
5489   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5490       OutlinedFunctionDecl(nullptr, NumParams);
5491 }
5492 
5493 Stmt *OutlinedFunctionDecl::getBody() const {
5494   return BodyAndNothrow.getPointer();
5495 }
5496 void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5497 
5498 bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5499 void OutlinedFunctionDecl::setNothrow(bool Nothrow) {
5500   BodyAndNothrow.setInt(Nothrow);
5501 }
5502 
5503 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5504     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5505       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5506 
5507 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
5508                                    unsigned NumParams) {
5509   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5510       CapturedDecl(DC, NumParams);
5511 }
5512 
5513 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5514                                                unsigned NumParams) {
5515   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5516       CapturedDecl(nullptr, NumParams);
5517 }
5518 
5519 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5520 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5521 
5522 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5523 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5524 
5525 EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC,
5526                                    SourceLocation L, IdentifierInfo *Id,
5527                                    QualType T, Expr *E, const llvm::APSInt &V)
5528     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5529   setInitVal(C, V);
5530 }
5531 
5532 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
5533                                            SourceLocation L,
5534                                            IdentifierInfo *Id, QualType T,
5535                                            Expr *E, const llvm::APSInt &V) {
5536   return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5537 }
5538 
5539 EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C,
5540                                                        GlobalDeclID ID) {
5541   return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5542                                       QualType(), nullptr, llvm::APSInt());
5543 }
5544 
5545 void IndirectFieldDecl::anchor() {}
5546 
5547 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5548                                      SourceLocation L, DeclarationName N,
5549                                      QualType T,
5550                                      MutableArrayRef<NamedDecl *> CH)
5551     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5552       ChainingSize(CH.size()) {
5553   // In C++, indirect field declarations conflict with tag declarations in the
5554   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5555   if (C.getLangOpts().CPlusPlus)
5556     IdentifierNamespace |= IDNS_Tag;
5557 }
5558 
5559 IndirectFieldDecl *
5560 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
5561                           const IdentifierInfo *Id, QualType T,
5562                           llvm::MutableArrayRef<NamedDecl *> CH) {
5563   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5564 }
5565 
5566 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
5567                                                          GlobalDeclID ID) {
5568   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
5569                                        DeclarationName(), QualType(), {});
5570 }
5571 
5572 SourceRange EnumConstantDecl::getSourceRange() const {
5573   SourceLocation End = getLocation();
5574   if (Init)
5575     End = Init->getEndLoc();
5576   return SourceRange(getLocation(), End);
5577 }
5578 
5579 void TypeDecl::anchor() {}
5580 
5581 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
5582                                  SourceLocation StartLoc, SourceLocation IdLoc,
5583                                  const IdentifierInfo *Id,
5584                                  TypeSourceInfo *TInfo) {
5585   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5586 }
5587 
5588 void TypedefNameDecl::anchor() {}
5589 
5590 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
5591   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5592     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5593     auto *ThisTypedef = this;
5594     if (AnyRedecl && OwningTypedef) {
5595       OwningTypedef = OwningTypedef->getCanonicalDecl();
5596       ThisTypedef = ThisTypedef->getCanonicalDecl();
5597     }
5598     if (OwningTypedef == ThisTypedef)
5599       return TT->getDecl();
5600   }
5601 
5602   return nullptr;
5603 }
5604 
5605 bool TypedefNameDecl::isTransparentTagSlow() const {
5606   auto determineIsTransparent = [&]() {
5607     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5608       if (auto *TD = TT->getDecl()) {
5609         if (TD->getName() != getName())
5610           return false;
5611         SourceLocation TTLoc = getLocation();
5612         SourceLocation TDLoc = TD->getLocation();
5613         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5614           return false;
5615         SourceManager &SM = getASTContext().getSourceManager();
5616         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5617       }
5618     }
5619     return false;
5620   };
5621 
5622   bool isTransparent = determineIsTransparent();
5623   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5624   return isTransparent;
5625 }
5626 
5627 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5628   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5629                                  nullptr, nullptr);
5630 }
5631 
5632 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
5633                                      SourceLocation StartLoc,
5634                                      SourceLocation IdLoc,
5635                                      const IdentifierInfo *Id,
5636                                      TypeSourceInfo *TInfo) {
5637   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5638 }
5639 
5640 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C,
5641                                                  GlobalDeclID ID) {
5642   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5643                                    SourceLocation(), nullptr, nullptr);
5644 }
5645 
5646 SourceRange TypedefDecl::getSourceRange() const {
5647   SourceLocation RangeEnd = getLocation();
5648   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5649     if (typeIsPostfix(TInfo->getType()))
5650       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5651   }
5652   return SourceRange(getBeginLoc(), RangeEnd);
5653 }
5654 
5655 SourceRange TypeAliasDecl::getSourceRange() const {
5656   SourceLocation RangeEnd = getBeginLoc();
5657   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5658     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5659   return SourceRange(getBeginLoc(), RangeEnd);
5660 }
5661 
5662 void FileScopeAsmDecl::anchor() {}
5663 
5664 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5665                                            StringLiteral *Str,
5666                                            SourceLocation AsmLoc,
5667                                            SourceLocation RParenLoc) {
5668   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5669 }
5670 
5671 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5672                                                        GlobalDeclID ID) {
5673   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5674                                       SourceLocation());
5675 }
5676 
5677 void TopLevelStmtDecl::anchor() {}
5678 
5679 TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {
5680   assert(C.getLangOpts().IncrementalExtensions &&
5681          "Must be used only in incremental mode");
5682 
5683   SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5684   DeclContext *DC = C.getTranslationUnitDecl();
5685 
5686   return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5687 }
5688 
5689 TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,
5690                                                        GlobalDeclID ID) {
5691   return new (C, ID)
5692       TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5693 }
5694 
5695 SourceRange TopLevelStmtDecl::getSourceRange() const {
5696   return SourceRange(getLocation(), Statement->getEndLoc());
5697 }
5698 
5699 void TopLevelStmtDecl::setStmt(Stmt *S) {
5700   assert(S);
5701   Statement = S;
5702   setLocation(Statement->getBeginLoc());
5703 }
5704 
5705 void EmptyDecl::anchor() {}
5706 
5707 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5708   return new (C, DC) EmptyDecl(DC, L);
5709 }
5710 
5711 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5712   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5713 }
5714 
5715 HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5716                                SourceLocation KwLoc, IdentifierInfo *ID,
5717                                SourceLocation IDLoc, SourceLocation LBrace)
5718     : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5719       DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5720       IsCBuffer(CBuffer) {}
5721 
5722 HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,
5723                                        DeclContext *LexicalParent, bool CBuffer,
5724                                        SourceLocation KwLoc, IdentifierInfo *ID,
5725                                        SourceLocation IDLoc,
5726                                        SourceLocation LBrace) {
5727   // For hlsl like this
5728   // cbuffer A {
5729   //     cbuffer B {
5730   //     }
5731   // }
5732   // compiler should treat it as
5733   // cbuffer A {
5734   // }
5735   // cbuffer B {
5736   // }
5737   // FIXME: support nested buffers if required for back-compat.
5738   DeclContext *DC = LexicalParent;
5739   HLSLBufferDecl *Result =
5740       new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5741   return Result;
5742 }
5743 
5744 HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,
5745                                                    GlobalDeclID ID) {
5746   return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
5747                                     SourceLocation(), SourceLocation());
5748 }
5749 
5750 //===----------------------------------------------------------------------===//
5751 // ImportDecl Implementation
5752 //===----------------------------------------------------------------------===//
5753 
5754 /// Retrieve the number of module identifiers needed to name the given
5755 /// module.
5756 static unsigned getNumModuleIdentifiers(Module *Mod) {
5757   unsigned Result = 1;
5758   while (Mod->Parent) {
5759     Mod = Mod->Parent;
5760     ++Result;
5761   }
5762   return Result;
5763 }
5764 
5765 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5766                        Module *Imported,
5767                        ArrayRef<SourceLocation> IdentifierLocs)
5768     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5769       NextLocalImportAndComplete(nullptr, true) {
5770   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5771   auto *StoredLocs = getTrailingObjects<SourceLocation>();
5772   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5773                           StoredLocs);
5774 }
5775 
5776 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5777                        Module *Imported, SourceLocation EndLoc)
5778     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5779       NextLocalImportAndComplete(nullptr, false) {
5780   *getTrailingObjects<SourceLocation>() = EndLoc;
5781 }
5782 
5783 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5784                                SourceLocation StartLoc, Module *Imported,
5785                                ArrayRef<SourceLocation> IdentifierLocs) {
5786   return new (C, DC,
5787               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5788       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5789 }
5790 
5791 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5792                                        SourceLocation StartLoc,
5793                                        Module *Imported,
5794                                        SourceLocation EndLoc) {
5795   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5796       ImportDecl(DC, StartLoc, Imported, EndLoc);
5797   Import->setImplicit();
5798   return Import;
5799 }
5800 
5801 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5802                                            unsigned NumLocations) {
5803   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5804       ImportDecl(EmptyShell());
5805 }
5806 
5807 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5808   if (!isImportComplete())
5809     return {};
5810 
5811   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5812   return llvm::ArrayRef(StoredLocs,
5813                         getNumModuleIdentifiers(getImportedModule()));
5814 }
5815 
5816 SourceRange ImportDecl::getSourceRange() const {
5817   if (!isImportComplete())
5818     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5819 
5820   return SourceRange(getLocation(), getIdentifierLocs().back());
5821 }
5822 
5823 //===----------------------------------------------------------------------===//
5824 // ExportDecl Implementation
5825 //===----------------------------------------------------------------------===//
5826 
5827 void ExportDecl::anchor() {}
5828 
5829 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5830                                SourceLocation ExportLoc) {
5831   return new (C, DC) ExportDecl(DC, ExportLoc);
5832 }
5833 
5834 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5835   return new (C, ID) ExportDecl(nullptr, SourceLocation());
5836 }
5837 
5838 bool clang::IsArmStreamingFunction(const FunctionDecl *FD,
5839                                    bool IncludeLocallyStreaming) {
5840   if (IncludeLocallyStreaming)
5841     if (FD->hasAttr<ArmLocallyStreamingAttr>())
5842       return true;
5843 
5844   if (const Type *Ty = FD->getType().getTypePtrOrNull())
5845     if (const auto *FPT = Ty->getAs<FunctionProtoType>())
5846       if (FPT->getAArch64SMEAttributes() &
5847           FunctionType::SME_PStateSMEnabledMask)
5848         return true;
5849 
5850   return false;
5851 }
5852 
5853 bool clang::hasArmZAState(const FunctionDecl *FD) {
5854   const auto *T = FD->getType()->getAs<FunctionProtoType>();
5855   return (T && FunctionType::getArmZAState(T->getAArch64SMEAttributes()) !=
5856                    FunctionType::ARM_None) ||
5857          (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
5858 }
5859 
5860 bool clang::hasArmZT0State(const FunctionDecl *FD) {
5861   const auto *T = FD->getType()->getAs<FunctionProtoType>();
5862   return (T && FunctionType::getArmZT0State(T->getAArch64SMEAttributes()) !=
5863                    FunctionType::ARM_None) ||
5864          (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
5865 }
5866