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