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