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