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