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