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