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