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