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