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