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