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