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