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