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