• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1304       assert(cast<VarDecl>(D)->isStaticLocal());
1305       // If this was an implicitly hidden inline method, check again for
1306       // explicit visibility on the parent class, and use that for static locals
1307       // if present.
1308       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1309         LV = getLVForDecl(MD->getParent(), computation);
1310       if (!LV.isVisibilityExplicit()) {
1311         Visibility globalVisibility =
1312             computation.isValueVisibility()
1313                 ? Context.getLangOpts().getValueVisibilityMode()
1314                 : Context.getLangOpts().getTypeVisibilityMode();
1315         return LinkageInfo(VisibleNoLinkage, globalVisibility,
1316                            /*visibilityExplicit=*/false);
1317       }
1318     }
1319   }
1320   if (!isExternallyVisible(LV.getLinkage()))
1321     return LinkageInfo::none();
1322   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1323                      LV.isVisibilityExplicit());
1324 }
1325 
computeLVForDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)1326 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1327                                               LVComputationKind computation,
1328                                               bool IgnoreVarTypeLinkage) {
1329   // Internal_linkage attribute overrides other considerations.
1330   if (D->hasAttr<InternalLinkageAttr>())
1331     return getInternalLinkageFor(D);
1332 
1333   // Objective-C: treat all Objective-C declarations as having external
1334   // linkage.
1335   switch (D->getKind()) {
1336     default:
1337       break;
1338 
1339     // Per C++ [basic.link]p2, only the names of objects, references,
1340     // functions, types, templates, namespaces, and values ever have linkage.
1341     //
1342     // Note that the name of a typedef, namespace alias, using declaration,
1343     // and so on are not the name of the corresponding type, namespace, or
1344     // declaration, so they do *not* have linkage.
1345     case Decl::ImplicitParam:
1346     case Decl::Label:
1347     case Decl::NamespaceAlias:
1348     case Decl::ParmVar:
1349     case Decl::Using:
1350     case Decl::UsingShadow:
1351     case Decl::UsingDirective:
1352       return LinkageInfo::none();
1353 
1354     case Decl::EnumConstant:
1355       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1356       if (D->getASTContext().getLangOpts().CPlusPlus)
1357         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1358       return LinkageInfo::visible_none();
1359 
1360     case Decl::Typedef:
1361     case Decl::TypeAlias:
1362       // A typedef declaration has linkage if it gives a type a name for
1363       // linkage purposes.
1364       if (!cast<TypedefNameDecl>(D)
1365                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1366         return LinkageInfo::none();
1367       break;
1368 
1369     case Decl::TemplateTemplateParm: // count these as external
1370     case Decl::NonTypeTemplateParm:
1371     case Decl::ObjCAtDefsField:
1372     case Decl::ObjCCategory:
1373     case Decl::ObjCCategoryImpl:
1374     case Decl::ObjCCompatibleAlias:
1375     case Decl::ObjCImplementation:
1376     case Decl::ObjCMethod:
1377     case Decl::ObjCProperty:
1378     case Decl::ObjCPropertyImpl:
1379     case Decl::ObjCProtocol:
1380       return getExternalLinkageFor(D);
1381 
1382     case Decl::CXXRecord: {
1383       const auto *Record = cast<CXXRecordDecl>(D);
1384       if (Record->isLambda()) {
1385         if (Record->hasKnownLambdaInternalLinkage() ||
1386             !Record->getLambdaManglingNumber()) {
1387           // This lambda has no mangling number, so it's internal.
1388           return getInternalLinkageFor(D);
1389         }
1390 
1391         return getLVForClosure(
1392                   Record->getDeclContext()->getRedeclContext(),
1393                   Record->getLambdaContextDecl(), computation);
1394       }
1395 
1396       break;
1397     }
1398 
1399     case Decl::TemplateParamObject: {
1400       // The template parameter object can be referenced from anywhere its type
1401       // and value can be referenced.
1402       auto *TPO = cast<TemplateParamObjectDecl>(D);
1403       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1404       LV.merge(getLVForValue(TPO->getValue(), computation));
1405       return LV;
1406     }
1407   }
1408 
1409   // Handle linkage for namespace-scope names.
1410   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1411     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1412 
1413   // C++ [basic.link]p5:
1414   //   In addition, a member function, static data member, a named
1415   //   class or enumeration of class scope, or an unnamed class or
1416   //   enumeration defined in a class-scope typedef declaration such
1417   //   that the class or enumeration has the typedef name for linkage
1418   //   purposes (7.1.3), has external linkage if the name of the class
1419   //   has external linkage.
1420   if (D->getDeclContext()->isRecord())
1421     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1422 
1423   // C++ [basic.link]p6:
1424   //   The name of a function declared in block scope and the name of
1425   //   an object declared by a block scope extern declaration have
1426   //   linkage. If there is a visible declaration of an entity with
1427   //   linkage having the same name and type, ignoring entities
1428   //   declared outside the innermost enclosing namespace scope, the
1429   //   block scope declaration declares that same entity and receives
1430   //   the linkage of the previous declaration. If there is more than
1431   //   one such matching entity, the program is ill-formed. Otherwise,
1432   //   if no matching entity is found, the block scope entity receives
1433   //   external linkage.
1434   if (D->getDeclContext()->isFunctionOrMethod())
1435     return getLVForLocalDecl(D, computation);
1436 
1437   // C++ [basic.link]p6:
1438   //   Names not covered by these rules have no linkage.
1439   return LinkageInfo::none();
1440 }
1441 
1442 /// getLVForDecl - Get the linkage and visibility for the given declaration.
getLVForDecl(const NamedDecl * D,LVComputationKind computation)1443 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1444                                           LVComputationKind computation) {
1445   // Internal_linkage attribute overrides other considerations.
1446   if (D->hasAttr<InternalLinkageAttr>())
1447     return getInternalLinkageFor(D);
1448 
1449   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1450     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1451 
1452   if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1453     return *LI;
1454 
1455   LinkageInfo LV = computeLVForDecl(D, computation);
1456   if (D->hasCachedLinkage())
1457     assert(D->getCachedLinkage() == LV.getLinkage());
1458 
1459   D->setCachedLinkage(LV.getLinkage());
1460   cache(D, computation, LV);
1461 
1462 #ifndef NDEBUG
1463   // In C (because of gnu inline) and in c++ with microsoft extensions an
1464   // static can follow an extern, so we can have two decls with different
1465   // linkages.
1466   const LangOptions &Opts = D->getASTContext().getLangOpts();
1467   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1468     return LV;
1469 
1470   // We have just computed the linkage for this decl. By induction we know
1471   // that all other computed linkages match, check that the one we just
1472   // computed also does.
1473   NamedDecl *Old = nullptr;
1474   for (auto I : D->redecls()) {
1475     auto *T = cast<NamedDecl>(I);
1476     if (T == D)
1477       continue;
1478     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1479       Old = T;
1480       break;
1481     }
1482   }
1483   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1484 #endif
1485 
1486   return LV;
1487 }
1488 
getDeclLinkageAndVisibility(const NamedDecl * D)1489 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1490   return getLVForDecl(D,
1491                       LVComputationKind(usesTypeVisibility(D)
1492                                             ? NamedDecl::VisibilityForType
1493                                             : NamedDecl::VisibilityForValue));
1494 }
1495 
getOwningModuleForLinkage(bool IgnoreLinkage) const1496 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1497   Module *M = getOwningModule();
1498   if (!M)
1499     return nullptr;
1500 
1501   switch (M->Kind) {
1502   case Module::ModuleMapModule:
1503     // Module map modules have no special linkage semantics.
1504     return nullptr;
1505 
1506   case Module::ModuleInterfaceUnit:
1507     return M;
1508 
1509   case Module::GlobalModuleFragment: {
1510     // External linkage declarations in the global module have no owning module
1511     // for linkage purposes. But internal linkage declarations in the global
1512     // module fragment of a particular module are owned by that module for
1513     // linkage purposes.
1514     if (IgnoreLinkage)
1515       return nullptr;
1516     bool InternalLinkage;
1517     if (auto *ND = dyn_cast<NamedDecl>(this))
1518       InternalLinkage = !ND->hasExternalFormalLinkage();
1519     else {
1520       auto *NSD = dyn_cast<NamespaceDecl>(this);
1521       InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1522                         isInAnonymousNamespace();
1523     }
1524     return InternalLinkage ? M->Parent : nullptr;
1525   }
1526 
1527   case Module::PrivateModuleFragment:
1528     // The private module fragment is part of its containing module for linkage
1529     // purposes.
1530     return M->Parent;
1531   }
1532 
1533   llvm_unreachable("unknown module kind");
1534 }
1535 
printName(raw_ostream & os) const1536 void NamedDecl::printName(raw_ostream &os) const {
1537   os << Name;
1538 }
1539 
getQualifiedNameAsString() const1540 std::string NamedDecl::getQualifiedNameAsString() const {
1541   std::string QualName;
1542   llvm::raw_string_ostream OS(QualName);
1543   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1544   return OS.str();
1545 }
1546 
printQualifiedName(raw_ostream & OS) const1547 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1548   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1549 }
1550 
printQualifiedName(raw_ostream & OS,const PrintingPolicy & P) const1551 void NamedDecl::printQualifiedName(raw_ostream &OS,
1552                                    const PrintingPolicy &P) const {
1553   if (getDeclContext()->isFunctionOrMethod()) {
1554     // We do not print '(anonymous)' for function parameters without name.
1555     printName(OS);
1556     return;
1557   }
1558   printNestedNameSpecifier(OS, P);
1559   if (getDeclName())
1560     OS << *this;
1561   else {
1562     // Give the printName override a chance to pick a different name before we
1563     // fall back to "(anonymous)".
1564     SmallString<64> NameBuffer;
1565     llvm::raw_svector_ostream NameOS(NameBuffer);
1566     printName(NameOS);
1567     if (NameBuffer.empty())
1568       OS << "(anonymous)";
1569     else
1570       OS << NameBuffer;
1571   }
1572 }
1573 
printNestedNameSpecifier(raw_ostream & OS) const1574 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1575   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1576 }
1577 
printNestedNameSpecifier(raw_ostream & OS,const PrintingPolicy & P) const1578 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1579                                          const PrintingPolicy &P) const {
1580   const DeclContext *Ctx = getDeclContext();
1581 
1582   // For ObjC methods and properties, look through categories and use the
1583   // interface as context.
1584   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1585     if (auto *ID = MD->getClassInterface())
1586       Ctx = ID;
1587   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1588     if (auto *MD = PD->getGetterMethodDecl())
1589       if (auto *ID = MD->getClassInterface())
1590         Ctx = ID;
1591   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1592     if (auto *CI = ID->getContainingInterface())
1593       Ctx = CI;
1594   }
1595 
1596   if (Ctx->isFunctionOrMethod())
1597     return;
1598 
1599   using ContextsTy = SmallVector<const DeclContext *, 8>;
1600   ContextsTy Contexts;
1601 
1602   // Collect named contexts.
1603   DeclarationName NameInScope = getDeclName();
1604   for (; Ctx; Ctx = Ctx->getParent()) {
1605     // Suppress anonymous namespace if requested.
1606     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1607         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1608       continue;
1609 
1610     // Suppress inline namespace if it doesn't make the result ambiguous.
1611     if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1612         Ctx->lookup(NameInScope).size() ==
1613             Ctx->getParent()->lookup(NameInScope).size())
1614       continue;
1615 
1616     // Skip non-named contexts such as linkage specifications and ExportDecls.
1617     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1618     if (!ND)
1619       continue;
1620 
1621     Contexts.push_back(Ctx);
1622     NameInScope = ND->getDeclName();
1623   }
1624 
1625   for (unsigned I = Contexts.size(); I != 0; --I) {
1626     const DeclContext *DC = Contexts[I - 1];
1627     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1628       OS << Spec->getName();
1629       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1630       printTemplateArgumentList(
1631           OS, TemplateArgs.asArray(), P,
1632           Spec->getSpecializedTemplate()->getTemplateParameters());
1633     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1634       if (ND->isAnonymousNamespace()) {
1635         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1636                                 : "(anonymous namespace)");
1637       }
1638       else
1639         OS << *ND;
1640     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1641       if (!RD->getIdentifier())
1642         OS << "(anonymous " << RD->getKindName() << ')';
1643       else
1644         OS << *RD;
1645     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1646       const FunctionProtoType *FT = nullptr;
1647       if (FD->hasWrittenPrototype())
1648         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1649 
1650       OS << *FD << '(';
1651       if (FT) {
1652         unsigned NumParams = FD->getNumParams();
1653         for (unsigned i = 0; i < NumParams; ++i) {
1654           if (i)
1655             OS << ", ";
1656           OS << FD->getParamDecl(i)->getType().stream(P);
1657         }
1658 
1659         if (FT->isVariadic()) {
1660           if (NumParams > 0)
1661             OS << ", ";
1662           OS << "...";
1663         }
1664       }
1665       OS << ')';
1666     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1667       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1668       // enumerator is declared in the scope that immediately contains
1669       // the enum-specifier. Each scoped enumerator is declared in the
1670       // scope of the enumeration.
1671       // For the case of unscoped enumerator, do not include in the qualified
1672       // name any information about its enum enclosing scope, as its visibility
1673       // is global.
1674       if (ED->isScoped())
1675         OS << *ED;
1676       else
1677         continue;
1678     } else {
1679       OS << *cast<NamedDecl>(DC);
1680     }
1681     OS << "::";
1682   }
1683 }
1684 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const1685 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1686                                      const PrintingPolicy &Policy,
1687                                      bool Qualified) const {
1688   if (Qualified)
1689     printQualifiedName(OS, Policy);
1690   else
1691     printName(OS);
1692 }
1693 
isRedeclarableImpl(Redeclarable<T> *)1694 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1695   return true;
1696 }
isRedeclarableImpl(...)1697 static bool isRedeclarableImpl(...) { return false; }
isRedeclarable(Decl::Kind K)1698 static bool isRedeclarable(Decl::Kind K) {
1699   switch (K) {
1700 #define DECL(Type, Base) \
1701   case Decl::Type: \
1702     return isRedeclarableImpl((Type##Decl *)nullptr);
1703 #define ABSTRACT_DECL(DECL)
1704 #include "clang/AST/DeclNodes.inc"
1705   }
1706   llvm_unreachable("unknown decl kind");
1707 }
1708 
declarationReplaces(NamedDecl * OldD,bool IsKnownNewer) const1709 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1710   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1711 
1712   // Never replace one imported declaration with another; we need both results
1713   // when re-exporting.
1714   if (OldD->isFromASTFile() && isFromASTFile())
1715     return false;
1716 
1717   // A kind mismatch implies that the declaration is not replaced.
1718   if (OldD->getKind() != getKind())
1719     return false;
1720 
1721   // For method declarations, we never replace. (Why?)
1722   if (isa<ObjCMethodDecl>(this))
1723     return false;
1724 
1725   // For parameters, pick the newer one. This is either an error or (in
1726   // Objective-C) permitted as an extension.
1727   if (isa<ParmVarDecl>(this))
1728     return true;
1729 
1730   // Inline namespaces can give us two declarations with the same
1731   // name and kind in the same scope but different contexts; we should
1732   // keep both declarations in this case.
1733   if (!this->getDeclContext()->getRedeclContext()->Equals(
1734           OldD->getDeclContext()->getRedeclContext()))
1735     return false;
1736 
1737   // Using declarations can be replaced if they import the same name from the
1738   // same context.
1739   if (auto *UD = dyn_cast<UsingDecl>(this)) {
1740     ASTContext &Context = getASTContext();
1741     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1742            Context.getCanonicalNestedNameSpecifier(
1743                cast<UsingDecl>(OldD)->getQualifier());
1744   }
1745   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1746     ASTContext &Context = getASTContext();
1747     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1748            Context.getCanonicalNestedNameSpecifier(
1749                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1750   }
1751 
1752   if (isRedeclarable(getKind())) {
1753     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1754       return false;
1755 
1756     if (IsKnownNewer)
1757       return true;
1758 
1759     // Check whether this is actually newer than OldD. We want to keep the
1760     // newer declaration. This loop will usually only iterate once, because
1761     // OldD is usually the previous declaration.
1762     for (auto D : redecls()) {
1763       if (D == OldD)
1764         break;
1765 
1766       // If we reach the canonical declaration, then OldD is not actually older
1767       // than this one.
1768       //
1769       // FIXME: In this case, we should not add this decl to the lookup table.
1770       if (D->isCanonicalDecl())
1771         return false;
1772     }
1773 
1774     // It's a newer declaration of the same kind of declaration in the same
1775     // scope: we want this decl instead of the existing one.
1776     return true;
1777   }
1778 
1779   // In all other cases, we need to keep both declarations in case they have
1780   // different visibility. Any attempt to use the name will result in an
1781   // ambiguity if more than one is visible.
1782   return false;
1783 }
1784 
hasLinkage() const1785 bool NamedDecl::hasLinkage() const {
1786   return getFormalLinkage() != NoLinkage;
1787 }
1788 
getUnderlyingDeclImpl()1789 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1790   NamedDecl *ND = this;
1791   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1792     ND = UD->getTargetDecl();
1793 
1794   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1795     return AD->getClassInterface();
1796 
1797   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1798     return AD->getNamespace();
1799 
1800   return ND;
1801 }
1802 
isCXXInstanceMember() const1803 bool NamedDecl::isCXXInstanceMember() const {
1804   if (!isCXXClassMember())
1805     return false;
1806 
1807   const NamedDecl *D = this;
1808   if (isa<UsingShadowDecl>(D))
1809     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1810 
1811   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1812     return true;
1813   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1814     return MD->isInstance();
1815   return false;
1816 }
1817 
1818 //===----------------------------------------------------------------------===//
1819 // DeclaratorDecl Implementation
1820 //===----------------------------------------------------------------------===//
1821 
1822 template <typename DeclT>
getTemplateOrInnerLocStart(const DeclT * decl)1823 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1824   if (decl->getNumTemplateParameterLists() > 0)
1825     return decl->getTemplateParameterList(0)->getTemplateLoc();
1826   else
1827     return decl->getInnerLocStart();
1828 }
1829 
getTypeSpecStartLoc() const1830 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1831   TypeSourceInfo *TSI = getTypeSourceInfo();
1832   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1833   return SourceLocation();
1834 }
1835 
getTypeSpecEndLoc() const1836 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1837   TypeSourceInfo *TSI = getTypeSourceInfo();
1838   if (TSI) return TSI->getTypeLoc().getEndLoc();
1839   return SourceLocation();
1840 }
1841 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)1842 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1843   if (QualifierLoc) {
1844     // Make sure the extended decl info is allocated.
1845     if (!hasExtInfo()) {
1846       // Save (non-extended) type source info pointer.
1847       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1848       // Allocate external info struct.
1849       DeclInfo = new (getASTContext()) ExtInfo;
1850       // Restore savedTInfo into (extended) decl info.
1851       getExtInfo()->TInfo = savedTInfo;
1852     }
1853     // Set qualifier info.
1854     getExtInfo()->QualifierLoc = QualifierLoc;
1855   } else if (hasExtInfo()) {
1856     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1857     getExtInfo()->QualifierLoc = QualifierLoc;
1858   }
1859 }
1860 
setTrailingRequiresClause(Expr * TrailingRequiresClause)1861 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1862   assert(TrailingRequiresClause);
1863   // Make sure the extended decl info is allocated.
1864   if (!hasExtInfo()) {
1865     // Save (non-extended) type source info pointer.
1866     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1867     // Allocate external info struct.
1868     DeclInfo = new (getASTContext()) ExtInfo;
1869     // Restore savedTInfo into (extended) decl info.
1870     getExtInfo()->TInfo = savedTInfo;
1871   }
1872   // Set requires clause info.
1873   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1874 }
1875 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)1876 void DeclaratorDecl::setTemplateParameterListsInfo(
1877     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1878   assert(!TPLists.empty());
1879   // Make sure the extended decl info is allocated.
1880   if (!hasExtInfo()) {
1881     // Save (non-extended) type source info pointer.
1882     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1883     // Allocate external info struct.
1884     DeclInfo = new (getASTContext()) ExtInfo;
1885     // Restore savedTInfo into (extended) decl info.
1886     getExtInfo()->TInfo = savedTInfo;
1887   }
1888   // Set the template parameter lists info.
1889   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1890 }
1891 
getOuterLocStart() const1892 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1893   return getTemplateOrInnerLocStart(this);
1894 }
1895 
1896 // Helper function: returns true if QT is or contains a type
1897 // having a postfix component.
typeIsPostfix(QualType QT)1898 static bool typeIsPostfix(QualType QT) {
1899   while (true) {
1900     const Type* T = QT.getTypePtr();
1901     switch (T->getTypeClass()) {
1902     default:
1903       return false;
1904     case Type::Pointer:
1905       QT = cast<PointerType>(T)->getPointeeType();
1906       break;
1907     case Type::BlockPointer:
1908       QT = cast<BlockPointerType>(T)->getPointeeType();
1909       break;
1910     case Type::MemberPointer:
1911       QT = cast<MemberPointerType>(T)->getPointeeType();
1912       break;
1913     case Type::LValueReference:
1914     case Type::RValueReference:
1915       QT = cast<ReferenceType>(T)->getPointeeType();
1916       break;
1917     case Type::PackExpansion:
1918       QT = cast<PackExpansionType>(T)->getPattern();
1919       break;
1920     case Type::Paren:
1921     case Type::ConstantArray:
1922     case Type::DependentSizedArray:
1923     case Type::IncompleteArray:
1924     case Type::VariableArray:
1925     case Type::FunctionProto:
1926     case Type::FunctionNoProto:
1927       return true;
1928     }
1929   }
1930 }
1931 
getSourceRange() const1932 SourceRange DeclaratorDecl::getSourceRange() const {
1933   SourceLocation RangeEnd = getLocation();
1934   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1935     // If the declaration has no name or the type extends past the name take the
1936     // end location of the type.
1937     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1938       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1939   }
1940   return SourceRange(getOuterLocStart(), RangeEnd);
1941 }
1942 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)1943 void QualifierInfo::setTemplateParameterListsInfo(
1944     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1945   // Free previous template parameters (if any).
1946   if (NumTemplParamLists > 0) {
1947     Context.Deallocate(TemplParamLists);
1948     TemplParamLists = nullptr;
1949     NumTemplParamLists = 0;
1950   }
1951   // Set info on matched template parameter lists (if any).
1952   if (!TPLists.empty()) {
1953     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1954     NumTemplParamLists = TPLists.size();
1955     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1956   }
1957 }
1958 
1959 //===----------------------------------------------------------------------===//
1960 // VarDecl Implementation
1961 //===----------------------------------------------------------------------===//
1962 
getStorageClassSpecifierString(StorageClass SC)1963 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1964   switch (SC) {
1965   case SC_None:                 break;
1966   case SC_Auto:                 return "auto";
1967   case SC_Extern:               return "extern";
1968   case SC_PrivateExtern:        return "__private_extern__";
1969   case SC_Register:             return "register";
1970   case SC_Static:               return "static";
1971   }
1972 
1973   llvm_unreachable("Invalid storage class");
1974 }
1975 
VarDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass SC)1976 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1977                  SourceLocation StartLoc, SourceLocation IdLoc,
1978                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1979                  StorageClass SC)
1980     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1981       redeclarable_base(C) {
1982   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1983                 "VarDeclBitfields too large!");
1984   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1985                 "ParmVarDeclBitfields too large!");
1986   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1987                 "NonParmVarDeclBitfields too large!");
1988   AllBits = 0;
1989   VarDeclBits.SClass = SC;
1990   // Everything else is implicitly initialized to false.
1991 }
1992 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartL,SourceLocation IdL,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S)1993 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1994                          SourceLocation StartL, SourceLocation IdL,
1995                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1996                          StorageClass S) {
1997   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1998 }
1999 
CreateDeserialized(ASTContext & C,unsigned ID)2000 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2001   return new (C, ID)
2002       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2003               QualType(), nullptr, SC_None);
2004 }
2005 
setStorageClass(StorageClass SC)2006 void VarDecl::setStorageClass(StorageClass SC) {
2007   assert(isLegalForVariable(SC));
2008   VarDeclBits.SClass = SC;
2009 }
2010 
getTLSKind() const2011 VarDecl::TLSKind VarDecl::getTLSKind() const {
2012   switch (VarDeclBits.TSCSpec) {
2013   case TSCS_unspecified:
2014     if (!hasAttr<ThreadAttr>() &&
2015         !(getASTContext().getLangOpts().OpenMPUseTLS &&
2016           getASTContext().getTargetInfo().isTLSSupported() &&
2017           hasAttr<OMPThreadPrivateDeclAttr>()))
2018       return TLS_None;
2019     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2020                 LangOptions::MSVC2015)) ||
2021             hasAttr<OMPThreadPrivateDeclAttr>())
2022                ? TLS_Dynamic
2023                : TLS_Static;
2024   case TSCS___thread: // Fall through.
2025   case TSCS__Thread_local:
2026     return TLS_Static;
2027   case TSCS_thread_local:
2028     return TLS_Dynamic;
2029   }
2030   llvm_unreachable("Unknown thread storage class specifier!");
2031 }
2032 
getSourceRange() const2033 SourceRange VarDecl::getSourceRange() const {
2034   if (const Expr *Init = getInit()) {
2035     SourceLocation InitEnd = Init->getEndLoc();
2036     // If Init is implicit, ignore its source range and fallback on
2037     // DeclaratorDecl::getSourceRange() to handle postfix elements.
2038     if (InitEnd.isValid() && InitEnd != getLocation())
2039       return SourceRange(getOuterLocStart(), InitEnd);
2040   }
2041   return DeclaratorDecl::getSourceRange();
2042 }
2043 
2044 template<typename T>
getDeclLanguageLinkage(const T & D)2045 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2046   // C++ [dcl.link]p1: All function types, function names with external linkage,
2047   // and variable names with external linkage have a language linkage.
2048   if (!D.hasExternalFormalLinkage())
2049     return NoLanguageLinkage;
2050 
2051   // Language linkage is a C++ concept, but saying that everything else in C has
2052   // C language linkage fits the implementation nicely.
2053   ASTContext &Context = D.getASTContext();
2054   if (!Context.getLangOpts().CPlusPlus)
2055     return CLanguageLinkage;
2056 
2057   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2058   // language linkage of the names of class members and the function type of
2059   // class member functions.
2060   const DeclContext *DC = D.getDeclContext();
2061   if (DC->isRecord())
2062     return CXXLanguageLinkage;
2063 
2064   // If the first decl is in an extern "C" context, any other redeclaration
2065   // will have C language linkage. If the first one is not in an extern "C"
2066   // context, we would have reported an error for any other decl being in one.
2067   if (isFirstInExternCContext(&D))
2068     return CLanguageLinkage;
2069   return CXXLanguageLinkage;
2070 }
2071 
2072 template<typename T>
isDeclExternC(const T & D)2073 static bool isDeclExternC(const T &D) {
2074   // Since the context is ignored for class members, they can only have C++
2075   // language linkage or no language linkage.
2076   const DeclContext *DC = D.getDeclContext();
2077   if (DC->isRecord()) {
2078     assert(D.getASTContext().getLangOpts().CPlusPlus);
2079     return false;
2080   }
2081 
2082   return D.getLanguageLinkage() == CLanguageLinkage;
2083 }
2084 
getLanguageLinkage() const2085 LanguageLinkage VarDecl::getLanguageLinkage() const {
2086   return getDeclLanguageLinkage(*this);
2087 }
2088 
isExternC() const2089 bool VarDecl::isExternC() const {
2090   return isDeclExternC(*this);
2091 }
2092 
isInExternCContext() const2093 bool VarDecl::isInExternCContext() const {
2094   return getLexicalDeclContext()->isExternCContext();
2095 }
2096 
isInExternCXXContext() const2097 bool VarDecl::isInExternCXXContext() const {
2098   return getLexicalDeclContext()->isExternCXXContext();
2099 }
2100 
getCanonicalDecl()2101 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2102 
2103 VarDecl::DefinitionKind
isThisDeclarationADefinition(ASTContext & C) const2104 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2105   if (isThisDeclarationADemotedDefinition())
2106     return DeclarationOnly;
2107 
2108   // C++ [basic.def]p2:
2109   //   A declaration is a definition unless [...] it contains the 'extern'
2110   //   specifier or a linkage-specification and neither an initializer [...],
2111   //   it declares a non-inline static data member in a class declaration [...],
2112   //   it declares a static data member outside a class definition and the variable
2113   //   was defined within the class with the constexpr specifier [...],
2114   // C++1y [temp.expl.spec]p15:
2115   //   An explicit specialization of a static data member or an explicit
2116   //   specialization of a static data member template is a definition if the
2117   //   declaration includes an initializer; otherwise, it is a declaration.
2118   //
2119   // FIXME: How do you declare (but not define) a partial specialization of
2120   // a static data member template outside the containing class?
2121   if (isStaticDataMember()) {
2122     if (isOutOfLine() &&
2123         !(getCanonicalDecl()->isInline() &&
2124           getCanonicalDecl()->isConstexpr()) &&
2125         (hasInit() ||
2126          // If the first declaration is out-of-line, this may be an
2127          // instantiation of an out-of-line partial specialization of a variable
2128          // template for which we have not yet instantiated the initializer.
2129          (getFirstDecl()->isOutOfLine()
2130               ? getTemplateSpecializationKind() == TSK_Undeclared
2131               : getTemplateSpecializationKind() !=
2132                     TSK_ExplicitSpecialization) ||
2133          isa<VarTemplatePartialSpecializationDecl>(this)))
2134       return Definition;
2135     else if (!isOutOfLine() && isInline())
2136       return Definition;
2137     else
2138       return DeclarationOnly;
2139   }
2140   // C99 6.7p5:
2141   //   A definition of an identifier is a declaration for that identifier that
2142   //   [...] causes storage to be reserved for that object.
2143   // Note: that applies for all non-file-scope objects.
2144   // C99 6.9.2p1:
2145   //   If the declaration of an identifier for an object has file scope and an
2146   //   initializer, the declaration is an external definition for the identifier
2147   if (hasInit())
2148     return Definition;
2149 
2150   if (hasDefiningAttr())
2151     return Definition;
2152 
2153   if (const auto *SAA = getAttr<SelectAnyAttr>())
2154     if (!SAA->isInherited())
2155       return Definition;
2156 
2157   // A variable template specialization (other than a static data member
2158   // template or an explicit specialization) is a declaration until we
2159   // instantiate its initializer.
2160   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2161     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2162         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2163         !VTSD->IsCompleteDefinition)
2164       return DeclarationOnly;
2165   }
2166 
2167   if (hasExternalStorage())
2168     return DeclarationOnly;
2169 
2170   // [dcl.link] p7:
2171   //   A declaration directly contained in a linkage-specification is treated
2172   //   as if it contains the extern specifier for the purpose of determining
2173   //   the linkage of the declared name and whether it is a definition.
2174   if (isSingleLineLanguageLinkage(*this))
2175     return DeclarationOnly;
2176 
2177   // C99 6.9.2p2:
2178   //   A declaration of an object that has file scope without an initializer,
2179   //   and without a storage class specifier or the scs 'static', constitutes
2180   //   a tentative definition.
2181   // No such thing in C++.
2182   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2183     return TentativeDefinition;
2184 
2185   // What's left is (in C, block-scope) declarations without initializers or
2186   // external storage. These are definitions.
2187   return Definition;
2188 }
2189 
getActingDefinition()2190 VarDecl *VarDecl::getActingDefinition() {
2191   DefinitionKind Kind = isThisDeclarationADefinition();
2192   if (Kind != TentativeDefinition)
2193     return nullptr;
2194 
2195   VarDecl *LastTentative = nullptr;
2196   VarDecl *First = getFirstDecl();
2197   for (auto I : First->redecls()) {
2198     Kind = I->isThisDeclarationADefinition();
2199     if (Kind == Definition)
2200       return nullptr;
2201     else if (Kind == TentativeDefinition)
2202       LastTentative = I;
2203   }
2204   return LastTentative;
2205 }
2206 
getDefinition(ASTContext & C)2207 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2208   VarDecl *First = getFirstDecl();
2209   for (auto I : First->redecls()) {
2210     if (I->isThisDeclarationADefinition(C) == Definition)
2211       return I;
2212   }
2213   return nullptr;
2214 }
2215 
hasDefinition(ASTContext & C) const2216 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2217   DefinitionKind Kind = DeclarationOnly;
2218 
2219   const VarDecl *First = getFirstDecl();
2220   for (auto I : First->redecls()) {
2221     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2222     if (Kind == Definition)
2223       break;
2224   }
2225 
2226   return Kind;
2227 }
2228 
getAnyInitializer(const VarDecl * & D) const2229 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2230   for (auto I : redecls()) {
2231     if (auto Expr = I->getInit()) {
2232       D = I;
2233       return Expr;
2234     }
2235   }
2236   return nullptr;
2237 }
2238 
hasInit() const2239 bool VarDecl::hasInit() const {
2240   if (auto *P = dyn_cast<ParmVarDecl>(this))
2241     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2242       return false;
2243 
2244   return !Init.isNull();
2245 }
2246 
getInit()2247 Expr *VarDecl::getInit() {
2248   if (!hasInit())
2249     return nullptr;
2250 
2251   if (auto *S = Init.dyn_cast<Stmt *>())
2252     return cast<Expr>(S);
2253 
2254   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2255 }
2256 
getInitAddress()2257 Stmt **VarDecl::getInitAddress() {
2258   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2259     return &ES->Value;
2260 
2261   return Init.getAddrOfPtr1();
2262 }
2263 
getInitializingDeclaration()2264 VarDecl *VarDecl::getInitializingDeclaration() {
2265   VarDecl *Def = nullptr;
2266   for (auto I : redecls()) {
2267     if (I->hasInit())
2268       return I;
2269 
2270     if (I->isThisDeclarationADefinition()) {
2271       if (isStaticDataMember())
2272         return I;
2273       else
2274         Def = I;
2275     }
2276   }
2277   return Def;
2278 }
2279 
isOutOfLine() const2280 bool VarDecl::isOutOfLine() const {
2281   if (Decl::isOutOfLine())
2282     return true;
2283 
2284   if (!isStaticDataMember())
2285     return false;
2286 
2287   // If this static data member was instantiated from a static data member of
2288   // a class template, check whether that static data member was defined
2289   // out-of-line.
2290   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2291     return VD->isOutOfLine();
2292 
2293   return false;
2294 }
2295 
setInit(Expr * I)2296 void VarDecl::setInit(Expr *I) {
2297   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2298     Eval->~EvaluatedStmt();
2299     getASTContext().Deallocate(Eval);
2300   }
2301 
2302   Init = I;
2303 }
2304 
mightBeUsableInConstantExpressions(const ASTContext & C) const2305 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2306   const LangOptions &Lang = C.getLangOpts();
2307 
2308   // OpenCL permits const integral variables to be used in constant
2309   // expressions, like in C++98.
2310   if (!Lang.CPlusPlus && !Lang.OpenCL)
2311     return false;
2312 
2313   // Function parameters are never usable in constant expressions.
2314   if (isa<ParmVarDecl>(this))
2315     return false;
2316 
2317   // The values of weak variables are never usable in constant expressions.
2318   if (isWeak())
2319     return false;
2320 
2321   // In C++11, any variable of reference type can be used in a constant
2322   // expression if it is initialized by a constant expression.
2323   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2324     return true;
2325 
2326   // Only const objects can be used in constant expressions in C++. C++98 does
2327   // not require the variable to be non-volatile, but we consider this to be a
2328   // defect.
2329   if (!getType().isConstant(C) || getType().isVolatileQualified())
2330     return false;
2331 
2332   // In C++, const, non-volatile variables of integral or enumeration types
2333   // can be used in constant expressions.
2334   if (getType()->isIntegralOrEnumerationType())
2335     return true;
2336 
2337   // Additionally, in C++11, non-volatile constexpr variables can be used in
2338   // constant expressions.
2339   return Lang.CPlusPlus11 && isConstexpr();
2340 }
2341 
isUsableInConstantExpressions(const ASTContext & Context) const2342 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2343   // C++2a [expr.const]p3:
2344   //   A variable is usable in constant expressions after its initializing
2345   //   declaration is encountered...
2346   const VarDecl *DefVD = nullptr;
2347   const Expr *Init = getAnyInitializer(DefVD);
2348   if (!Init || Init->isValueDependent() || getType()->isDependentType())
2349     return false;
2350   //   ... if it is a constexpr variable, or it is of reference type or of
2351   //   const-qualified integral or enumeration type, ...
2352   if (!DefVD->mightBeUsableInConstantExpressions(Context))
2353     return false;
2354   //   ... and its initializer is a constant initializer.
2355   if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2356     return false;
2357   // C++98 [expr.const]p1:
2358   //   An integral constant-expression can involve only [...] const variables
2359   //   or static data members of integral or enumeration types initialized with
2360   //   [integer] constant expressions (dcl.init)
2361   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2362       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2363     return false;
2364   return true;
2365 }
2366 
2367 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2368 /// form, which contains extra information on the evaluated value of the
2369 /// initializer.
ensureEvaluatedStmt() const2370 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2371   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2372   if (!Eval) {
2373     // Note: EvaluatedStmt contains an APValue, which usually holds
2374     // resources not allocated from the ASTContext.  We need to do some
2375     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2376     // where we can detect whether there's anything to clean up or not.
2377     Eval = new (getASTContext()) EvaluatedStmt;
2378     Eval->Value = Init.get<Stmt *>();
2379     Init = Eval;
2380   }
2381   return Eval;
2382 }
2383 
getEvaluatedStmt() const2384 EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2385   return Init.dyn_cast<EvaluatedStmt *>();
2386 }
2387 
evaluateValue() const2388 APValue *VarDecl::evaluateValue() const {
2389   SmallVector<PartialDiagnosticAt, 8> Notes;
2390   return evaluateValueImpl(Notes, hasConstantInitialization());
2391 }
2392 
evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const2393 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2394                                     bool IsConstantInitialization) const {
2395   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2396 
2397   const auto *Init = cast<Expr>(Eval->Value);
2398   assert(!Init->isValueDependent());
2399 
2400   // We only produce notes indicating why an initializer is non-constant the
2401   // first time it is evaluated. FIXME: The notes won't always be emitted the
2402   // first time we try evaluation, so might not be produced at all.
2403   if (Eval->WasEvaluated)
2404     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2405 
2406   if (Eval->IsEvaluating) {
2407     // FIXME: Produce a diagnostic for self-initialization.
2408     return nullptr;
2409   }
2410 
2411   Eval->IsEvaluating = true;
2412 
2413   ASTContext &Ctx = getASTContext();
2414   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2415                                             IsConstantInitialization);
2416 
2417   // In C++11, this isn't a constant initializer if we produced notes. In that
2418   // case, we can't keep the result, because it may only be correct under the
2419   // assumption that the initializer is a constant context.
2420   if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2421       !Notes.empty())
2422     Result = false;
2423 
2424   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2425   // or that it's empty (so that there's nothing to clean up) if evaluation
2426   // failed.
2427   if (!Result)
2428     Eval->Evaluated = APValue();
2429   else if (Eval->Evaluated.needsCleanup())
2430     Ctx.addDestruction(&Eval->Evaluated);
2431 
2432   Eval->IsEvaluating = false;
2433   Eval->WasEvaluated = true;
2434 
2435   return Result ? &Eval->Evaluated : nullptr;
2436 }
2437 
getEvaluatedValue() const2438 APValue *VarDecl::getEvaluatedValue() const {
2439   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2440     if (Eval->WasEvaluated)
2441       return &Eval->Evaluated;
2442 
2443   return nullptr;
2444 }
2445 
hasICEInitializer(const ASTContext & Context) const2446 bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2447   const Expr *Init = getInit();
2448   assert(Init && "no initializer");
2449 
2450   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2451   if (!Eval->CheckedForICEInit) {
2452     Eval->CheckedForICEInit = true;
2453     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2454   }
2455   return Eval->HasICEInit;
2456 }
2457 
hasConstantInitialization() const2458 bool VarDecl::hasConstantInitialization() const {
2459   // In C, all globals (and only globals) have constant initialization.
2460   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2461     return true;
2462 
2463   // In C++, it depends on whether the evaluation at the point of definition
2464   // was evaluatable as a constant initializer.
2465   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2466     return Eval->HasConstantInitialization;
2467 
2468   return false;
2469 }
2470 
checkForConstantInitialization(SmallVectorImpl<PartialDiagnosticAt> & Notes) const2471 bool VarDecl::checkForConstantInitialization(
2472     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2473   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2474   // If we ask for the value before we know whether we have a constant
2475   // initializer, we can compute the wrong value (for example, due to
2476   // std::is_constant_evaluated()).
2477   assert(!Eval->WasEvaluated &&
2478          "already evaluated var value before checking for constant init");
2479   assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2480 
2481   assert(!cast<Expr>(Eval->Value)->isValueDependent());
2482 
2483   // Evaluate the initializer to check whether it's a constant expression.
2484   Eval->HasConstantInitialization =
2485       evaluateValueImpl(Notes, true) && Notes.empty();
2486 
2487   // If evaluation as a constant initializer failed, allow re-evaluation as a
2488   // non-constant initializer if we later find we want the value.
2489   if (!Eval->HasConstantInitialization)
2490     Eval->WasEvaluated = false;
2491 
2492   return Eval->HasConstantInitialization;
2493 }
2494 
isParameterPack() const2495 bool VarDecl::isParameterPack() const {
2496   return isa<PackExpansionType>(getType());
2497 }
2498 
2499 template<typename DeclT>
getDefinitionOrSelf(DeclT * D)2500 static DeclT *getDefinitionOrSelf(DeclT *D) {
2501   assert(D);
2502   if (auto *Def = D->getDefinition())
2503     return Def;
2504   return D;
2505 }
2506 
isEscapingByref() const2507 bool VarDecl::isEscapingByref() const {
2508   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2509 }
2510 
isNonEscapingByref() const2511 bool VarDecl::isNonEscapingByref() const {
2512   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2513 }
2514 
getTemplateInstantiationPattern() const2515 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2516   const VarDecl *VD = this;
2517 
2518   // If this is an instantiated member, walk back to the template from which
2519   // it was instantiated.
2520   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2521     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2522       VD = VD->getInstantiatedFromStaticDataMember();
2523       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2524         VD = NewVD;
2525     }
2526   }
2527 
2528   // If it's an instantiated variable template specialization, find the
2529   // template or partial specialization from which it was instantiated.
2530   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2531     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2532       auto From = VDTemplSpec->getInstantiatedFrom();
2533       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2534         while (!VTD->isMemberSpecialization()) {
2535           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2536           if (!NewVTD)
2537             break;
2538           VTD = NewVTD;
2539         }
2540         return getDefinitionOrSelf(VTD->getTemplatedDecl());
2541       }
2542       if (auto *VTPSD =
2543               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2544         while (!VTPSD->isMemberSpecialization()) {
2545           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2546           if (!NewVTPSD)
2547             break;
2548           VTPSD = NewVTPSD;
2549         }
2550         return getDefinitionOrSelf<VarDecl>(VTPSD);
2551       }
2552     }
2553   }
2554 
2555   // If this is the pattern of a variable template, find where it was
2556   // instantiated from. FIXME: Is this necessary?
2557   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2558     while (!VarTemplate->isMemberSpecialization()) {
2559       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2560       if (!NewVT)
2561         break;
2562       VarTemplate = NewVT;
2563     }
2564 
2565     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2566   }
2567 
2568   if (VD == this)
2569     return nullptr;
2570   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2571 }
2572 
getInstantiatedFromStaticDataMember() const2573 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2574   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2575     return cast<VarDecl>(MSI->getInstantiatedFrom());
2576 
2577   return nullptr;
2578 }
2579 
getTemplateSpecializationKind() const2580 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2581   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2582     return Spec->getSpecializationKind();
2583 
2584   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2585     return MSI->getTemplateSpecializationKind();
2586 
2587   return TSK_Undeclared;
2588 }
2589 
2590 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const2591 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2592   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2593     return MSI->getTemplateSpecializationKind();
2594 
2595   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2596     return Spec->getSpecializationKind();
2597 
2598   return TSK_Undeclared;
2599 }
2600 
getPointOfInstantiation() const2601 SourceLocation VarDecl::getPointOfInstantiation() const {
2602   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2603     return Spec->getPointOfInstantiation();
2604 
2605   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2606     return MSI->getPointOfInstantiation();
2607 
2608   return SourceLocation();
2609 }
2610 
getDescribedVarTemplate() const2611 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2612   return getASTContext().getTemplateOrSpecializationInfo(this)
2613       .dyn_cast<VarTemplateDecl *>();
2614 }
2615 
setDescribedVarTemplate(VarTemplateDecl * Template)2616 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2617   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2618 }
2619 
isKnownToBeDefined() const2620 bool VarDecl::isKnownToBeDefined() const {
2621   const auto &LangOpts = getASTContext().getLangOpts();
2622   // In CUDA mode without relocatable device code, variables of form 'extern
2623   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2624   // memory pool.  These are never undefined variables, even if they appear
2625   // inside of an anon namespace or static function.
2626   //
2627   // With CUDA relocatable device code enabled, these variables don't get
2628   // special handling; they're treated like regular extern variables.
2629   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2630       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2631       isa<IncompleteArrayType>(getType()))
2632     return true;
2633 
2634   return hasDefinition();
2635 }
2636 
isNoDestroy(const ASTContext & Ctx) const2637 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2638   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2639                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2640                                  !hasAttr<AlwaysDestroyAttr>()));
2641 }
2642 
2643 QualType::DestructionKind
needsDestruction(const ASTContext & Ctx) const2644 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2645   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2646     if (Eval->HasConstantDestruction)
2647       return QualType::DK_none;
2648 
2649   if (isNoDestroy(Ctx))
2650     return QualType::DK_none;
2651 
2652   return getType().isDestructedType();
2653 }
2654 
getMemberSpecializationInfo() const2655 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2656   if (isStaticDataMember())
2657     // FIXME: Remove ?
2658     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2659     return getASTContext().getTemplateOrSpecializationInfo(this)
2660         .dyn_cast<MemberSpecializationInfo *>();
2661   return nullptr;
2662 }
2663 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)2664 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2665                                          SourceLocation PointOfInstantiation) {
2666   assert((isa<VarTemplateSpecializationDecl>(this) ||
2667           getMemberSpecializationInfo()) &&
2668          "not a variable or static data member template specialization");
2669 
2670   if (VarTemplateSpecializationDecl *Spec =
2671           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2672     Spec->setSpecializationKind(TSK);
2673     if (TSK != TSK_ExplicitSpecialization &&
2674         PointOfInstantiation.isValid() &&
2675         Spec->getPointOfInstantiation().isInvalid()) {
2676       Spec->setPointOfInstantiation(PointOfInstantiation);
2677       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2678         L->InstantiationRequested(this);
2679     }
2680   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2681     MSI->setTemplateSpecializationKind(TSK);
2682     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2683         MSI->getPointOfInstantiation().isInvalid()) {
2684       MSI->setPointOfInstantiation(PointOfInstantiation);
2685       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2686         L->InstantiationRequested(this);
2687     }
2688   }
2689 }
2690 
2691 void
setInstantiationOfStaticDataMember(VarDecl * VD,TemplateSpecializationKind TSK)2692 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2693                                             TemplateSpecializationKind TSK) {
2694   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2695          "Previous template or instantiation?");
2696   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2697 }
2698 
2699 //===----------------------------------------------------------------------===//
2700 // ParmVarDecl Implementation
2701 //===----------------------------------------------------------------------===//
2702 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S,Expr * DefArg)2703 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2704                                  SourceLocation StartLoc,
2705                                  SourceLocation IdLoc, IdentifierInfo *Id,
2706                                  QualType T, TypeSourceInfo *TInfo,
2707                                  StorageClass S, Expr *DefArg) {
2708   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2709                                  S, DefArg);
2710 }
2711 
getOriginalType() const2712 QualType ParmVarDecl::getOriginalType() const {
2713   TypeSourceInfo *TSI = getTypeSourceInfo();
2714   QualType T = TSI ? TSI->getType() : getType();
2715   if (const auto *DT = dyn_cast<DecayedType>(T))
2716     return DT->getOriginalType();
2717   return T;
2718 }
2719 
CreateDeserialized(ASTContext & C,unsigned ID)2720 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2721   return new (C, ID)
2722       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2723                   nullptr, QualType(), nullptr, SC_None, nullptr);
2724 }
2725 
getSourceRange() const2726 SourceRange ParmVarDecl::getSourceRange() const {
2727   if (!hasInheritedDefaultArg()) {
2728     SourceRange ArgRange = getDefaultArgRange();
2729     if (ArgRange.isValid())
2730       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2731   }
2732 
2733   // DeclaratorDecl considers the range of postfix types as overlapping with the
2734   // declaration name, but this is not the case with parameters in ObjC methods.
2735   if (isa<ObjCMethodDecl>(getDeclContext()))
2736     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2737 
2738   return DeclaratorDecl::getSourceRange();
2739 }
2740 
getDefaultArg()2741 Expr *ParmVarDecl::getDefaultArg() {
2742   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2743   assert(!hasUninstantiatedDefaultArg() &&
2744          "Default argument is not yet instantiated!");
2745 
2746   Expr *Arg = getInit();
2747   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2748     return E->getSubExpr();
2749 
2750   return Arg;
2751 }
2752 
setDefaultArg(Expr * defarg)2753 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2754   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2755   Init = defarg;
2756 }
2757 
getDefaultArgRange() const2758 SourceRange ParmVarDecl::getDefaultArgRange() const {
2759   switch (ParmVarDeclBits.DefaultArgKind) {
2760   case DAK_None:
2761   case DAK_Unparsed:
2762     // Nothing we can do here.
2763     return SourceRange();
2764 
2765   case DAK_Uninstantiated:
2766     return getUninstantiatedDefaultArg()->getSourceRange();
2767 
2768   case DAK_Normal:
2769     if (const Expr *E = getInit())
2770       return E->getSourceRange();
2771 
2772     // Missing an actual expression, may be invalid.
2773     return SourceRange();
2774   }
2775   llvm_unreachable("Invalid default argument kind.");
2776 }
2777 
setUninstantiatedDefaultArg(Expr * arg)2778 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2779   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2780   Init = arg;
2781 }
2782 
getUninstantiatedDefaultArg()2783 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2784   assert(hasUninstantiatedDefaultArg() &&
2785          "Wrong kind of initialization expression!");
2786   return cast_or_null<Expr>(Init.get<Stmt *>());
2787 }
2788 
hasDefaultArg() const2789 bool ParmVarDecl::hasDefaultArg() const {
2790   // FIXME: We should just return false for DAK_None here once callers are
2791   // prepared for the case that we encountered an invalid default argument and
2792   // were unable to even build an invalid expression.
2793   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2794          !Init.isNull();
2795 }
2796 
setParameterIndexLarge(unsigned parameterIndex)2797 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2798   getASTContext().setParameterIndex(this, parameterIndex);
2799   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2800 }
2801 
getParameterIndexLarge() const2802 unsigned ParmVarDecl::getParameterIndexLarge() const {
2803   return getASTContext().getParameterIndex(this);
2804 }
2805 
2806 //===----------------------------------------------------------------------===//
2807 // FunctionDecl Implementation
2808 //===----------------------------------------------------------------------===//
2809 
FunctionDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass S,bool isInlineSpecified,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)2810 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2811                            SourceLocation StartLoc,
2812                            const DeclarationNameInfo &NameInfo, QualType T,
2813                            TypeSourceInfo *TInfo, StorageClass S,
2814                            bool isInlineSpecified,
2815                            ConstexprSpecKind ConstexprKind,
2816                            Expr *TrailingRequiresClause)
2817     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2818                      StartLoc),
2819       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2820       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2821   assert(T.isNull() || T->isFunctionType());
2822   FunctionDeclBits.SClass = S;
2823   FunctionDeclBits.IsInline = isInlineSpecified;
2824   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2825   FunctionDeclBits.IsVirtualAsWritten = false;
2826   FunctionDeclBits.IsPure = false;
2827   FunctionDeclBits.HasInheritedPrototype = false;
2828   FunctionDeclBits.HasWrittenPrototype = true;
2829   FunctionDeclBits.IsDeleted = false;
2830   FunctionDeclBits.IsTrivial = false;
2831   FunctionDeclBits.IsTrivialForCall = false;
2832   FunctionDeclBits.IsDefaulted = false;
2833   FunctionDeclBits.IsExplicitlyDefaulted = false;
2834   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2835   FunctionDeclBits.HasImplicitReturnZero = false;
2836   FunctionDeclBits.IsLateTemplateParsed = false;
2837   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
2838   FunctionDeclBits.InstantiationIsPending = false;
2839   FunctionDeclBits.UsesSEHTry = false;
2840   FunctionDeclBits.UsesFPIntrin = false;
2841   FunctionDeclBits.HasSkippedBody = false;
2842   FunctionDeclBits.WillHaveBody = false;
2843   FunctionDeclBits.IsMultiVersion = false;
2844   FunctionDeclBits.IsCopyDeductionCandidate = false;
2845   FunctionDeclBits.HasODRHash = false;
2846   if (TrailingRequiresClause)
2847     setTrailingRequiresClause(TrailingRequiresClause);
2848 }
2849 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const2850 void FunctionDecl::getNameForDiagnostic(
2851     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2852   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2853   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2854   if (TemplateArgs)
2855     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2856 }
2857 
isVariadic() const2858 bool FunctionDecl::isVariadic() const {
2859   if (const auto *FT = getType()->getAs<FunctionProtoType>())
2860     return FT->isVariadic();
2861   return false;
2862 }
2863 
2864 FunctionDecl::DefaultedFunctionInfo *
Create(ASTContext & Context,ArrayRef<DeclAccessPair> Lookups)2865 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2866                                             ArrayRef<DeclAccessPair> Lookups) {
2867   DefaultedFunctionInfo *Info = new (Context.Allocate(
2868       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2869       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2870       DefaultedFunctionInfo;
2871   Info->NumLookups = Lookups.size();
2872   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2873                           Info->getTrailingObjects<DeclAccessPair>());
2874   return Info;
2875 }
2876 
setDefaultedFunctionInfo(DefaultedFunctionInfo * Info)2877 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2878   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2879   assert(!Body && "can't replace function body with defaulted function info");
2880 
2881   FunctionDeclBits.HasDefaultedFunctionInfo = true;
2882   DefaultedInfo = Info;
2883 }
2884 
2885 FunctionDecl::DefaultedFunctionInfo *
getDefaultedFunctionInfo() const2886 FunctionDecl::getDefaultedFunctionInfo() const {
2887   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2888 }
2889 
hasBody(const FunctionDecl * & Definition) const2890 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2891   for (auto I : redecls()) {
2892     if (I->doesThisDeclarationHaveABody()) {
2893       Definition = I;
2894       return true;
2895     }
2896   }
2897 
2898   return false;
2899 }
2900 
hasTrivialBody() const2901 bool FunctionDecl::hasTrivialBody() const {
2902   Stmt *S = getBody();
2903   if (!S) {
2904     // Since we don't have a body for this function, we don't know if it's
2905     // trivial or not.
2906     return false;
2907   }
2908 
2909   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2910     return true;
2911   return false;
2912 }
2913 
isThisDeclarationInstantiatedFromAFriendDefinition() const2914 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
2915   if (!getFriendObjectKind())
2916     return false;
2917 
2918   // Check for a friend function instantiated from a friend function
2919   // definition in a templated class.
2920   if (const FunctionDecl *InstantiatedFrom =
2921           getInstantiatedFromMemberFunction())
2922     return InstantiatedFrom->getFriendObjectKind() &&
2923            InstantiatedFrom->isThisDeclarationADefinition();
2924 
2925   // Check for a friend function template instantiated from a friend
2926   // function template definition in a templated class.
2927   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
2928     if (const FunctionTemplateDecl *InstantiatedFrom =
2929             Template->getInstantiatedFromMemberTemplate())
2930       return InstantiatedFrom->getFriendObjectKind() &&
2931              InstantiatedFrom->isThisDeclarationADefinition();
2932   }
2933 
2934   return false;
2935 }
2936 
isDefined(const FunctionDecl * & Definition,bool CheckForPendingFriendDefinition) const2937 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
2938                              bool CheckForPendingFriendDefinition) const {
2939   for (const FunctionDecl *FD : redecls()) {
2940     if (FD->isThisDeclarationADefinition()) {
2941       Definition = FD;
2942       return true;
2943     }
2944 
2945     // If this is a friend function defined in a class template, it does not
2946     // have a body until it is used, nevertheless it is a definition, see
2947     // [temp.inst]p2:
2948     //
2949     // ... for the purpose of determining whether an instantiated redeclaration
2950     // is valid according to [basic.def.odr] and [class.mem], a declaration that
2951     // corresponds to a definition in the template is considered to be a
2952     // definition.
2953     //
2954     // The following code must produce redefinition error:
2955     //
2956     //     template<typename T> struct C20 { friend void func_20() {} };
2957     //     C20<int> c20i;
2958     //     void func_20() {}
2959     //
2960     if (CheckForPendingFriendDefinition &&
2961         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
2962       Definition = FD;
2963       return true;
2964     }
2965   }
2966 
2967   return false;
2968 }
2969 
getBody(const FunctionDecl * & Definition) const2970 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2971   if (!hasBody(Definition))
2972     return nullptr;
2973 
2974   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
2975          "definition should not have a body");
2976   if (Definition->Body)
2977     return Definition->Body.get(getASTContext().getExternalSource());
2978 
2979   return nullptr;
2980 }
2981 
setBody(Stmt * B)2982 void FunctionDecl::setBody(Stmt *B) {
2983   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2984   Body = LazyDeclStmtPtr(B);
2985   if (B)
2986     EndRangeLoc = B->getEndLoc();
2987 }
2988 
setPure(bool P)2989 void FunctionDecl::setPure(bool P) {
2990   FunctionDeclBits.IsPure = P;
2991   if (P)
2992     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2993       Parent->markedVirtualFunctionPure();
2994 }
2995 
2996 template<std::size_t Len>
isNamed(const NamedDecl * ND,const char (& Str)[Len])2997 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2998   IdentifierInfo *II = ND->getIdentifier();
2999   return II && II->isStr(Str);
3000 }
3001 
isMain() const3002 bool FunctionDecl::isMain() const {
3003   const TranslationUnitDecl *tunit =
3004     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3005   return tunit &&
3006          !tunit->getASTContext().getLangOpts().Freestanding &&
3007          isNamed(this, "main");
3008 }
3009 
isMSVCRTEntryPoint() const3010 bool FunctionDecl::isMSVCRTEntryPoint() const {
3011   const TranslationUnitDecl *TUnit =
3012       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3013   if (!TUnit)
3014     return false;
3015 
3016   // Even though we aren't really targeting MSVCRT if we are freestanding,
3017   // semantic analysis for these functions remains the same.
3018 
3019   // MSVCRT entry points only exist on MSVCRT targets.
3020   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3021     return false;
3022 
3023   // Nameless functions like constructors cannot be entry points.
3024   if (!getIdentifier())
3025     return false;
3026 
3027   return llvm::StringSwitch<bool>(getName())
3028       .Cases("main",     // an ANSI console app
3029              "wmain",    // a Unicode console App
3030              "WinMain",  // an ANSI GUI app
3031              "wWinMain", // a Unicode GUI app
3032              "DllMain",  // a DLL
3033              true)
3034       .Default(false);
3035 }
3036 
isReservedGlobalPlacementOperator() const3037 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3038   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
3039   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
3040          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3041          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
3042          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
3043 
3044   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3045     return false;
3046 
3047   const auto *proto = getType()->castAs<FunctionProtoType>();
3048   if (proto->getNumParams() != 2 || proto->isVariadic())
3049     return false;
3050 
3051   ASTContext &Context =
3052     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3053       ->getASTContext();
3054 
3055   // The result type and first argument type are constant across all
3056   // these operators.  The second argument must be exactly void*.
3057   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3058 }
3059 
isReplaceableGlobalAllocationFunction(Optional<unsigned> * AlignmentParam,bool * IsNothrow) const3060 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3061     Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3062   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3063     return false;
3064   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3065       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3066       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3067       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3068     return false;
3069 
3070   if (isa<CXXRecordDecl>(getDeclContext()))
3071     return false;
3072 
3073   // This can only fail for an invalid 'operator new' declaration.
3074   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3075     return false;
3076 
3077   const auto *FPT = getType()->castAs<FunctionProtoType>();
3078   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
3079     return false;
3080 
3081   // If this is a single-parameter function, it must be a replaceable global
3082   // allocation or deallocation function.
3083   if (FPT->getNumParams() == 1)
3084     return true;
3085 
3086   unsigned Params = 1;
3087   QualType Ty = FPT->getParamType(Params);
3088   ASTContext &Ctx = getASTContext();
3089 
3090   auto Consume = [&] {
3091     ++Params;
3092     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3093   };
3094 
3095   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3096   bool IsSizedDelete = false;
3097   if (Ctx.getLangOpts().SizedDeallocation &&
3098       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3099        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3100       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3101     IsSizedDelete = true;
3102     Consume();
3103   }
3104 
3105   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3106   // new/delete.
3107   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3108     Consume();
3109     if (AlignmentParam)
3110       *AlignmentParam = Params;
3111   }
3112 
3113   // Finally, if this is not a sized delete, the final parameter can
3114   // be a 'const std::nothrow_t&'.
3115   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3116     Ty = Ty->getPointeeType();
3117     if (Ty.getCVRQualifiers() != Qualifiers::Const)
3118       return false;
3119     if (Ty->isNothrowT()) {
3120       if (IsNothrow)
3121         *IsNothrow = true;
3122       Consume();
3123     }
3124   }
3125 
3126   return Params == FPT->getNumParams();
3127 }
3128 
isInlineBuiltinDeclaration() const3129 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3130   if (!getBuiltinID())
3131     return false;
3132 
3133   const FunctionDecl *Definition;
3134   return hasBody(Definition) && Definition->isInlineSpecified();
3135 }
3136 
isDestroyingOperatorDelete() const3137 bool FunctionDecl::isDestroyingOperatorDelete() const {
3138   // C++ P0722:
3139   //   Within a class C, a single object deallocation function with signature
3140   //     (T, std::destroying_delete_t, <more params>)
3141   //   is a destroying operator delete.
3142   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3143       getNumParams() < 2)
3144     return false;
3145 
3146   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3147   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3148          RD->getIdentifier()->isStr("destroying_delete_t");
3149 }
3150 
getLanguageLinkage() const3151 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3152   return getDeclLanguageLinkage(*this);
3153 }
3154 
isExternC() const3155 bool FunctionDecl::isExternC() const {
3156   return isDeclExternC(*this);
3157 }
3158 
isInExternCContext() const3159 bool FunctionDecl::isInExternCContext() const {
3160   if (hasAttr<OpenCLKernelAttr>())
3161     return true;
3162   return getLexicalDeclContext()->isExternCContext();
3163 }
3164 
isInExternCXXContext() const3165 bool FunctionDecl::isInExternCXXContext() const {
3166   return getLexicalDeclContext()->isExternCXXContext();
3167 }
3168 
isGlobal() const3169 bool FunctionDecl::isGlobal() const {
3170   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3171     return Method->isStatic();
3172 
3173   if (getCanonicalDecl()->getStorageClass() == SC_Static)
3174     return false;
3175 
3176   for (const DeclContext *DC = getDeclContext();
3177        DC->isNamespace();
3178        DC = DC->getParent()) {
3179     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3180       if (!Namespace->getDeclName())
3181         return false;
3182       break;
3183     }
3184   }
3185 
3186   return true;
3187 }
3188 
isNoReturn() const3189 bool FunctionDecl::isNoReturn() const {
3190   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3191       hasAttr<C11NoReturnAttr>())
3192     return true;
3193 
3194   if (auto *FnTy = getType()->getAs<FunctionType>())
3195     return FnTy->getNoReturnAttr();
3196 
3197   return false;
3198 }
3199 
3200 
getMultiVersionKind() const3201 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3202   if (hasAttr<TargetAttr>())
3203     return MultiVersionKind::Target;
3204   if (hasAttr<CPUDispatchAttr>())
3205     return MultiVersionKind::CPUDispatch;
3206   if (hasAttr<CPUSpecificAttr>())
3207     return MultiVersionKind::CPUSpecific;
3208   return MultiVersionKind::None;
3209 }
3210 
isCPUDispatchMultiVersion() const3211 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3212   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3213 }
3214 
isCPUSpecificMultiVersion() const3215 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3216   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3217 }
3218 
isTargetMultiVersion() const3219 bool FunctionDecl::isTargetMultiVersion() const {
3220   return isMultiVersion() && hasAttr<TargetAttr>();
3221 }
3222 
3223 void
setPreviousDeclaration(FunctionDecl * PrevDecl)3224 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3225   redeclarable_base::setPreviousDecl(PrevDecl);
3226 
3227   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3228     FunctionTemplateDecl *PrevFunTmpl
3229       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3230     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3231     FunTmpl->setPreviousDecl(PrevFunTmpl);
3232   }
3233 
3234   if (PrevDecl && PrevDecl->isInlined())
3235     setImplicitlyInline(true);
3236 }
3237 
getCanonicalDecl()3238 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3239 
3240 /// Returns a value indicating whether this function corresponds to a builtin
3241 /// function.
3242 ///
3243 /// The function corresponds to a built-in function if it is declared at
3244 /// translation scope or within an extern "C" block and its name matches with
3245 /// the name of a builtin. The returned value will be 0 for functions that do
3246 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3247 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3248 /// value.
3249 ///
3250 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3251 /// functions as their wrapped builtins. This shouldn't be done in general, but
3252 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
getBuiltinID(bool ConsiderWrapperFunctions) const3253 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3254   unsigned BuiltinID = 0;
3255 
3256   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3257     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3258   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3259     BuiltinID = A->getID();
3260   }
3261 
3262   if (!BuiltinID)
3263     return 0;
3264 
3265   // If the function is marked "overloadable", it has a different mangled name
3266   // and is not the C library function.
3267   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3268       !hasAttr<ArmBuiltinAliasAttr>())
3269     return 0;
3270 
3271   ASTContext &Context = getASTContext();
3272   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3273     return BuiltinID;
3274 
3275   // This function has the name of a known C library
3276   // function. Determine whether it actually refers to the C library
3277   // function or whether it just has the same name.
3278 
3279   // If this is a static function, it's not a builtin.
3280   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3281     return 0;
3282 
3283   // OpenCL v1.2 s6.9.f - The library functions defined in
3284   // the C99 standard headers are not available.
3285   if (Context.getLangOpts().OpenCL &&
3286       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3287     return 0;
3288 
3289   // CUDA does not have device-side standard library. printf and malloc are the
3290   // only special cases that are supported by device-side runtime.
3291   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3292       !hasAttr<CUDAHostAttr>() &&
3293       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3294     return 0;
3295 
3296   // As AMDGCN implementation of OpenMP does not have a device-side standard
3297   // library, none of the predefined library functions except printf and malloc
3298   // should be treated as a builtin i.e. 0 should be returned for them.
3299   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3300       Context.getLangOpts().OpenMPIsDevice &&
3301       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3302       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3303     return 0;
3304 
3305   return BuiltinID;
3306 }
3307 
3308 /// getNumParams - Return the number of parameters this function must have
3309 /// based on its FunctionType.  This is the length of the ParamInfo array
3310 /// after it has been created.
getNumParams() const3311 unsigned FunctionDecl::getNumParams() const {
3312   const auto *FPT = getType()->getAs<FunctionProtoType>();
3313   return FPT ? FPT->getNumParams() : 0;
3314 }
3315 
setParams(ASTContext & C,ArrayRef<ParmVarDecl * > NewParamInfo)3316 void FunctionDecl::setParams(ASTContext &C,
3317                              ArrayRef<ParmVarDecl *> NewParamInfo) {
3318   assert(!ParamInfo && "Already has param info!");
3319   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3320 
3321   // Zero params -> null pointer.
3322   if (!NewParamInfo.empty()) {
3323     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3324     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3325   }
3326 }
3327 
3328 /// getMinRequiredArguments - Returns the minimum number of arguments
3329 /// needed to call this function. This may be fewer than the number of
3330 /// function parameters, if some of the parameters have default
3331 /// arguments (in C++) or are parameter packs (C++11).
getMinRequiredArguments() const3332 unsigned FunctionDecl::getMinRequiredArguments() const {
3333   if (!getASTContext().getLangOpts().CPlusPlus)
3334     return getNumParams();
3335 
3336   // Note that it is possible for a parameter with no default argument to
3337   // follow a parameter with a default argument.
3338   unsigned NumRequiredArgs = 0;
3339   unsigned MinParamsSoFar = 0;
3340   for (auto *Param : parameters()) {
3341     if (!Param->isParameterPack()) {
3342       ++MinParamsSoFar;
3343       if (!Param->hasDefaultArg())
3344         NumRequiredArgs = MinParamsSoFar;
3345     }
3346   }
3347   return NumRequiredArgs;
3348 }
3349 
hasOneParamOrDefaultArgs() const3350 bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3351   return getNumParams() == 1 ||
3352          (getNumParams() > 1 &&
3353           std::all_of(param_begin() + 1, param_end(),
3354                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3355 }
3356 
3357 /// The combination of the extern and inline keywords under MSVC forces
3358 /// the function to be required.
3359 ///
3360 /// Note: This function assumes that we will only get called when isInlined()
3361 /// would return true for this FunctionDecl.
isMSExternInline() const3362 bool FunctionDecl::isMSExternInline() const {
3363   assert(isInlined() && "expected to get called on an inlined function!");
3364 
3365   const ASTContext &Context = getASTContext();
3366   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3367       !hasAttr<DLLExportAttr>())
3368     return false;
3369 
3370   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3371        FD = FD->getPreviousDecl())
3372     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3373       return true;
3374 
3375   return false;
3376 }
3377 
redeclForcesDefMSVC(const FunctionDecl * Redecl)3378 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3379   if (Redecl->getStorageClass() != SC_Extern)
3380     return false;
3381 
3382   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3383        FD = FD->getPreviousDecl())
3384     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3385       return false;
3386 
3387   return true;
3388 }
3389 
RedeclForcesDefC99(const FunctionDecl * Redecl)3390 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3391   // Only consider file-scope declarations in this test.
3392   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3393     return false;
3394 
3395   // Only consider explicit declarations; the presence of a builtin for a
3396   // libcall shouldn't affect whether a definition is externally visible.
3397   if (Redecl->isImplicit())
3398     return false;
3399 
3400   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3401     return true; // Not an inline definition
3402 
3403   return false;
3404 }
3405 
3406 /// For a function declaration in C or C++, determine whether this
3407 /// declaration causes the definition to be externally visible.
3408 ///
3409 /// For instance, this determines if adding the current declaration to the set
3410 /// of redeclarations of the given functions causes
3411 /// isInlineDefinitionExternallyVisible to change from false to true.
doesDeclarationForceExternallyVisibleDefinition() const3412 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3413   assert(!doesThisDeclarationHaveABody() &&
3414          "Must have a declaration without a body.");
3415 
3416   ASTContext &Context = getASTContext();
3417 
3418   if (Context.getLangOpts().MSVCCompat) {
3419     const FunctionDecl *Definition;
3420     if (hasBody(Definition) && Definition->isInlined() &&
3421         redeclForcesDefMSVC(this))
3422       return true;
3423   }
3424 
3425   if (Context.getLangOpts().CPlusPlus)
3426     return false;
3427 
3428   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3429     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3430     // an externally visible definition.
3431     //
3432     // FIXME: What happens if gnu_inline gets added on after the first
3433     // declaration?
3434     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3435       return false;
3436 
3437     const FunctionDecl *Prev = this;
3438     bool FoundBody = false;
3439     while ((Prev = Prev->getPreviousDecl())) {
3440       FoundBody |= Prev->doesThisDeclarationHaveABody();
3441 
3442       if (Prev->doesThisDeclarationHaveABody()) {
3443         // If it's not the case that both 'inline' and 'extern' are
3444         // specified on the definition, then it is always externally visible.
3445         if (!Prev->isInlineSpecified() ||
3446             Prev->getStorageClass() != SC_Extern)
3447           return false;
3448       } else if (Prev->isInlineSpecified() &&
3449                  Prev->getStorageClass() != SC_Extern) {
3450         return false;
3451       }
3452     }
3453     return FoundBody;
3454   }
3455 
3456   // C99 6.7.4p6:
3457   //   [...] If all of the file scope declarations for a function in a
3458   //   translation unit include the inline function specifier without extern,
3459   //   then the definition in that translation unit is an inline definition.
3460   if (isInlineSpecified() && getStorageClass() != SC_Extern)
3461     return false;
3462   const FunctionDecl *Prev = this;
3463   bool FoundBody = false;
3464   while ((Prev = Prev->getPreviousDecl())) {
3465     FoundBody |= Prev->doesThisDeclarationHaveABody();
3466     if (RedeclForcesDefC99(Prev))
3467       return false;
3468   }
3469   return FoundBody;
3470 }
3471 
getFunctionTypeLoc() const3472 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3473   const TypeSourceInfo *TSI = getTypeSourceInfo();
3474   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3475              : FunctionTypeLoc();
3476 }
3477 
getReturnTypeSourceRange() const3478 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3479   FunctionTypeLoc FTL = getFunctionTypeLoc();
3480   if (!FTL)
3481     return SourceRange();
3482 
3483   // Skip self-referential return types.
3484   const SourceManager &SM = getASTContext().getSourceManager();
3485   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3486   SourceLocation Boundary = getNameInfo().getBeginLoc();
3487   if (RTRange.isInvalid() || Boundary.isInvalid() ||
3488       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3489     return SourceRange();
3490 
3491   return RTRange;
3492 }
3493 
getParametersSourceRange() const3494 SourceRange FunctionDecl::getParametersSourceRange() const {
3495   unsigned NP = getNumParams();
3496   SourceLocation EllipsisLoc = getEllipsisLoc();
3497 
3498   if (NP == 0 && EllipsisLoc.isInvalid())
3499     return SourceRange();
3500 
3501   SourceLocation Begin =
3502       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3503   SourceLocation End = EllipsisLoc.isValid()
3504                            ? EllipsisLoc
3505                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3506 
3507   return SourceRange(Begin, End);
3508 }
3509 
getExceptionSpecSourceRange() const3510 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3511   FunctionTypeLoc FTL = getFunctionTypeLoc();
3512   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3513 }
3514 
3515 /// For an inline function definition in C, or for a gnu_inline function
3516 /// in C++, determine whether the definition will be externally visible.
3517 ///
3518 /// Inline function definitions are always available for inlining optimizations.
3519 /// However, depending on the language dialect, declaration specifiers, and
3520 /// attributes, the definition of an inline function may or may not be
3521 /// "externally" visible to other translation units in the program.
3522 ///
3523 /// In C99, inline definitions are not externally visible by default. However,
3524 /// if even one of the global-scope declarations is marked "extern inline", the
3525 /// inline definition becomes externally visible (C99 6.7.4p6).
3526 ///
3527 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3528 /// definition, we use the GNU semantics for inline, which are nearly the
3529 /// opposite of C99 semantics. In particular, "inline" by itself will create
3530 /// an externally visible symbol, but "extern inline" will not create an
3531 /// externally visible symbol.
isInlineDefinitionExternallyVisible() const3532 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3533   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3534           hasAttr<AliasAttr>()) &&
3535          "Must be a function definition");
3536   assert(isInlined() && "Function must be inline");
3537   ASTContext &Context = getASTContext();
3538 
3539   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3540     // Note: If you change the logic here, please change
3541     // doesDeclarationForceExternallyVisibleDefinition as well.
3542     //
3543     // If it's not the case that both 'inline' and 'extern' are
3544     // specified on the definition, then this inline definition is
3545     // externally visible.
3546     if (Context.getLangOpts().CPlusPlus)
3547       return false;
3548     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3549       return true;
3550 
3551     // If any declaration is 'inline' but not 'extern', then this definition
3552     // is externally visible.
3553     for (auto Redecl : redecls()) {
3554       if (Redecl->isInlineSpecified() &&
3555           Redecl->getStorageClass() != SC_Extern)
3556         return true;
3557     }
3558 
3559     return false;
3560   }
3561 
3562   // The rest of this function is C-only.
3563   assert(!Context.getLangOpts().CPlusPlus &&
3564          "should not use C inline rules in C++");
3565 
3566   // C99 6.7.4p6:
3567   //   [...] If all of the file scope declarations for a function in a
3568   //   translation unit include the inline function specifier without extern,
3569   //   then the definition in that translation unit is an inline definition.
3570   for (auto Redecl : redecls()) {
3571     if (RedeclForcesDefC99(Redecl))
3572       return true;
3573   }
3574 
3575   // C99 6.7.4p6:
3576   //   An inline definition does not provide an external definition for the
3577   //   function, and does not forbid an external definition in another
3578   //   translation unit.
3579   return false;
3580 }
3581 
3582 /// getOverloadedOperator - Which C++ overloaded operator this
3583 /// function represents, if any.
getOverloadedOperator() const3584 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3585   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3586     return getDeclName().getCXXOverloadedOperator();
3587   else
3588     return OO_None;
3589 }
3590 
3591 /// getLiteralIdentifier - The literal suffix identifier this function
3592 /// represents, if any.
getLiteralIdentifier() const3593 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3594   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3595     return getDeclName().getCXXLiteralIdentifier();
3596   else
3597     return nullptr;
3598 }
3599 
getTemplatedKind() const3600 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3601   if (TemplateOrSpecialization.isNull())
3602     return TK_NonTemplate;
3603   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3604     return TK_FunctionTemplate;
3605   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3606     return TK_MemberSpecialization;
3607   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3608     return TK_FunctionTemplateSpecialization;
3609   if (TemplateOrSpecialization.is
3610                                <DependentFunctionTemplateSpecializationInfo*>())
3611     return TK_DependentFunctionTemplateSpecialization;
3612 
3613   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3614 }
3615 
getInstantiatedFromMemberFunction() const3616 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3617   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3618     return cast<FunctionDecl>(Info->getInstantiatedFrom());
3619 
3620   return nullptr;
3621 }
3622 
getMemberSpecializationInfo() const3623 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3624   if (auto *MSI =
3625           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3626     return MSI;
3627   if (auto *FTSI = TemplateOrSpecialization
3628                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
3629     return FTSI->getMemberSpecializationInfo();
3630   return nullptr;
3631 }
3632 
3633 void
setInstantiationOfMemberFunction(ASTContext & C,FunctionDecl * FD,TemplateSpecializationKind TSK)3634 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3635                                                FunctionDecl *FD,
3636                                                TemplateSpecializationKind TSK) {
3637   assert(TemplateOrSpecialization.isNull() &&
3638          "Member function is already a specialization");
3639   MemberSpecializationInfo *Info
3640     = new (C) MemberSpecializationInfo(FD, TSK);
3641   TemplateOrSpecialization = Info;
3642 }
3643 
getDescribedFunctionTemplate() const3644 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3645   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3646 }
3647 
setDescribedFunctionTemplate(FunctionTemplateDecl * Template)3648 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3649   assert(TemplateOrSpecialization.isNull() &&
3650          "Member function is already a specialization");
3651   TemplateOrSpecialization = Template;
3652 }
3653 
isImplicitlyInstantiable() const3654 bool FunctionDecl::isImplicitlyInstantiable() const {
3655   // If the function is invalid, it can't be implicitly instantiated.
3656   if (isInvalidDecl())
3657     return false;
3658 
3659   switch (getTemplateSpecializationKindForInstantiation()) {
3660   case TSK_Undeclared:
3661   case TSK_ExplicitInstantiationDefinition:
3662   case TSK_ExplicitSpecialization:
3663     return false;
3664 
3665   case TSK_ImplicitInstantiation:
3666     return true;
3667 
3668   case TSK_ExplicitInstantiationDeclaration:
3669     // Handled below.
3670     break;
3671   }
3672 
3673   // Find the actual template from which we will instantiate.
3674   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3675   bool HasPattern = false;
3676   if (PatternDecl)
3677     HasPattern = PatternDecl->hasBody(PatternDecl);
3678 
3679   // C++0x [temp.explicit]p9:
3680   //   Except for inline functions, other explicit instantiation declarations
3681   //   have the effect of suppressing the implicit instantiation of the entity
3682   //   to which they refer.
3683   if (!HasPattern || !PatternDecl)
3684     return true;
3685 
3686   return PatternDecl->isInlined();
3687 }
3688 
isTemplateInstantiation() const3689 bool FunctionDecl::isTemplateInstantiation() const {
3690   // FIXME: Remove this, it's not clear what it means. (Which template
3691   // specialization kind?)
3692   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3693 }
3694 
3695 FunctionDecl *
getTemplateInstantiationPattern(bool ForDefinition) const3696 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3697   // If this is a generic lambda call operator specialization, its
3698   // instantiation pattern is always its primary template's pattern
3699   // even if its primary template was instantiated from another
3700   // member template (which happens with nested generic lambdas).
3701   // Since a lambda's call operator's body is transformed eagerly,
3702   // we don't have to go hunting for a prototype definition template
3703   // (i.e. instantiated-from-member-template) to use as an instantiation
3704   // pattern.
3705 
3706   if (isGenericLambdaCallOperatorSpecialization(
3707           dyn_cast<CXXMethodDecl>(this))) {
3708     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3709     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3710   }
3711 
3712   // Check for a declaration of this function that was instantiated from a
3713   // friend definition.
3714   const FunctionDecl *FD = nullptr;
3715   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3716     FD = this;
3717 
3718   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3719     if (ForDefinition &&
3720         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3721       return nullptr;
3722     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3723   }
3724 
3725   if (ForDefinition &&
3726       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3727     return nullptr;
3728 
3729   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3730     // If we hit a point where the user provided a specialization of this
3731     // template, we're done looking.
3732     while (!ForDefinition || !Primary->isMemberSpecialization()) {
3733       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3734       if (!NewPrimary)
3735         break;
3736       Primary = NewPrimary;
3737     }
3738 
3739     return getDefinitionOrSelf(Primary->getTemplatedDecl());
3740   }
3741 
3742   return nullptr;
3743 }
3744 
getPrimaryTemplate() const3745 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3746   if (FunctionTemplateSpecializationInfo *Info
3747         = TemplateOrSpecialization
3748             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3749     return Info->getTemplate();
3750   }
3751   return nullptr;
3752 }
3753 
3754 FunctionTemplateSpecializationInfo *
getTemplateSpecializationInfo() const3755 FunctionDecl::getTemplateSpecializationInfo() const {
3756   return TemplateOrSpecialization
3757       .dyn_cast<FunctionTemplateSpecializationInfo *>();
3758 }
3759 
3760 const TemplateArgumentList *
getTemplateSpecializationArgs() const3761 FunctionDecl::getTemplateSpecializationArgs() const {
3762   if (FunctionTemplateSpecializationInfo *Info
3763         = TemplateOrSpecialization
3764             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3765     return Info->TemplateArguments;
3766   }
3767   return nullptr;
3768 }
3769 
3770 const ASTTemplateArgumentListInfo *
getTemplateSpecializationArgsAsWritten() const3771 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3772   if (FunctionTemplateSpecializationInfo *Info
3773         = TemplateOrSpecialization
3774             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3775     return Info->TemplateArgumentsAsWritten;
3776   }
3777   return nullptr;
3778 }
3779 
3780 void
setFunctionTemplateSpecialization(ASTContext & C,FunctionTemplateDecl * Template,const TemplateArgumentList * TemplateArgs,void * InsertPos,TemplateSpecializationKind TSK,const TemplateArgumentListInfo * TemplateArgsAsWritten,SourceLocation PointOfInstantiation)3781 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3782                                                 FunctionTemplateDecl *Template,
3783                                      const TemplateArgumentList *TemplateArgs,
3784                                                 void *InsertPos,
3785                                                 TemplateSpecializationKind TSK,
3786                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
3787                                           SourceLocation PointOfInstantiation) {
3788   assert((TemplateOrSpecialization.isNull() ||
3789           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3790          "Member function is already a specialization");
3791   assert(TSK != TSK_Undeclared &&
3792          "Must specify the type of function template specialization");
3793   assert((TemplateOrSpecialization.isNull() ||
3794           TSK == TSK_ExplicitSpecialization) &&
3795          "Member specialization must be an explicit specialization");
3796   FunctionTemplateSpecializationInfo *Info =
3797       FunctionTemplateSpecializationInfo::Create(
3798           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3799           PointOfInstantiation,
3800           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3801   TemplateOrSpecialization = Info;
3802   Template->addSpecialization(Info, InsertPos);
3803 }
3804 
3805 void
setDependentTemplateSpecialization(ASTContext & Context,const UnresolvedSetImpl & Templates,const TemplateArgumentListInfo & TemplateArgs)3806 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3807                                     const UnresolvedSetImpl &Templates,
3808                              const TemplateArgumentListInfo &TemplateArgs) {
3809   assert(TemplateOrSpecialization.isNull());
3810   DependentFunctionTemplateSpecializationInfo *Info =
3811       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3812                                                           TemplateArgs);
3813   TemplateOrSpecialization = Info;
3814 }
3815 
3816 DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo() const3817 FunctionDecl::getDependentSpecializationInfo() const {
3818   return TemplateOrSpecialization
3819       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3820 }
3821 
3822 DependentFunctionTemplateSpecializationInfo *
Create(ASTContext & Context,const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)3823 DependentFunctionTemplateSpecializationInfo::Create(
3824     ASTContext &Context, const UnresolvedSetImpl &Ts,
3825     const TemplateArgumentListInfo &TArgs) {
3826   void *Buffer = Context.Allocate(
3827       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3828           TArgs.size(), Ts.size()));
3829   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3830 }
3831 
3832 DependentFunctionTemplateSpecializationInfo::
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)3833 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3834                                       const TemplateArgumentListInfo &TArgs)
3835   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3836   NumTemplates = Ts.size();
3837   NumArgs = TArgs.size();
3838 
3839   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3840   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3841     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3842 
3843   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3844   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3845     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3846 }
3847 
getTemplateSpecializationKind() const3848 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3849   // For a function template specialization, query the specialization
3850   // information object.
3851   if (FunctionTemplateSpecializationInfo *FTSInfo =
3852           TemplateOrSpecialization
3853               .dyn_cast<FunctionTemplateSpecializationInfo *>())
3854     return FTSInfo->getTemplateSpecializationKind();
3855 
3856   if (MemberSpecializationInfo *MSInfo =
3857           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3858     return MSInfo->getTemplateSpecializationKind();
3859 
3860   return TSK_Undeclared;
3861 }
3862 
3863 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const3864 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3865   // This is the same as getTemplateSpecializationKind(), except that for a
3866   // function that is both a function template specialization and a member
3867   // specialization, we prefer the member specialization information. Eg:
3868   //
3869   // template<typename T> struct A {
3870   //   template<typename U> void f() {}
3871   //   template<> void f<int>() {}
3872   // };
3873   //
3874   // For A<int>::f<int>():
3875   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3876   // * getTemplateSpecializationKindForInstantiation() will return
3877   //       TSK_ImplicitInstantiation
3878   //
3879   // This reflects the facts that A<int>::f<int> is an explicit specialization
3880   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3881   // from A::f<int> if a definition is needed.
3882   if (FunctionTemplateSpecializationInfo *FTSInfo =
3883           TemplateOrSpecialization
3884               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3885     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3886       return MSInfo->getTemplateSpecializationKind();
3887     return FTSInfo->getTemplateSpecializationKind();
3888   }
3889 
3890   if (MemberSpecializationInfo *MSInfo =
3891           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3892     return MSInfo->getTemplateSpecializationKind();
3893 
3894   return TSK_Undeclared;
3895 }
3896 
3897 void
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)3898 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3899                                           SourceLocation PointOfInstantiation) {
3900   if (FunctionTemplateSpecializationInfo *FTSInfo
3901         = TemplateOrSpecialization.dyn_cast<
3902                                     FunctionTemplateSpecializationInfo*>()) {
3903     FTSInfo->setTemplateSpecializationKind(TSK);
3904     if (TSK != TSK_ExplicitSpecialization &&
3905         PointOfInstantiation.isValid() &&
3906         FTSInfo->getPointOfInstantiation().isInvalid()) {
3907       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3908       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3909         L->InstantiationRequested(this);
3910     }
3911   } else if (MemberSpecializationInfo *MSInfo
3912              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3913     MSInfo->setTemplateSpecializationKind(TSK);
3914     if (TSK != TSK_ExplicitSpecialization &&
3915         PointOfInstantiation.isValid() &&
3916         MSInfo->getPointOfInstantiation().isInvalid()) {
3917       MSInfo->setPointOfInstantiation(PointOfInstantiation);
3918       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3919         L->InstantiationRequested(this);
3920     }
3921   } else
3922     llvm_unreachable("Function cannot have a template specialization kind");
3923 }
3924 
getPointOfInstantiation() const3925 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3926   if (FunctionTemplateSpecializationInfo *FTSInfo
3927         = TemplateOrSpecialization.dyn_cast<
3928                                         FunctionTemplateSpecializationInfo*>())
3929     return FTSInfo->getPointOfInstantiation();
3930   else if (MemberSpecializationInfo *MSInfo
3931              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3932     return MSInfo->getPointOfInstantiation();
3933 
3934   return SourceLocation();
3935 }
3936 
isOutOfLine() const3937 bool FunctionDecl::isOutOfLine() const {
3938   if (Decl::isOutOfLine())
3939     return true;
3940 
3941   // If this function was instantiated from a member function of a
3942   // class template, check whether that member function was defined out-of-line.
3943   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3944     const FunctionDecl *Definition;
3945     if (FD->hasBody(Definition))
3946       return Definition->isOutOfLine();
3947   }
3948 
3949   // If this function was instantiated from a function template,
3950   // check whether that function template was defined out-of-line.
3951   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3952     const FunctionDecl *Definition;
3953     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3954       return Definition->isOutOfLine();
3955   }
3956 
3957   return false;
3958 }
3959 
getSourceRange() const3960 SourceRange FunctionDecl::getSourceRange() const {
3961   return SourceRange(getOuterLocStart(), EndRangeLoc);
3962 }
3963 
getMemoryFunctionKind() const3964 unsigned FunctionDecl::getMemoryFunctionKind() const {
3965   IdentifierInfo *FnInfo = getIdentifier();
3966 
3967   if (!FnInfo)
3968     return 0;
3969 
3970   // Builtin handling.
3971   switch (getBuiltinID()) {
3972   case Builtin::BI__builtin_memset:
3973   case Builtin::BI__builtin___memset_chk:
3974   case Builtin::BImemset:
3975     return Builtin::BImemset;
3976 
3977   case Builtin::BI__builtin_memcpy:
3978   case Builtin::BI__builtin___memcpy_chk:
3979   case Builtin::BImemcpy:
3980     return Builtin::BImemcpy;
3981 
3982   case Builtin::BI__builtin_mempcpy:
3983   case Builtin::BI__builtin___mempcpy_chk:
3984   case Builtin::BImempcpy:
3985     return Builtin::BImempcpy;
3986 
3987   case Builtin::BI__builtin_memmove:
3988   case Builtin::BI__builtin___memmove_chk:
3989   case Builtin::BImemmove:
3990     return Builtin::BImemmove;
3991 
3992   case Builtin::BIstrlcpy:
3993   case Builtin::BI__builtin___strlcpy_chk:
3994     return Builtin::BIstrlcpy;
3995 
3996   case Builtin::BIstrlcat:
3997   case Builtin::BI__builtin___strlcat_chk:
3998     return Builtin::BIstrlcat;
3999 
4000   case Builtin::BI__builtin_memcmp:
4001   case Builtin::BImemcmp:
4002     return Builtin::BImemcmp;
4003 
4004   case Builtin::BI__builtin_bcmp:
4005   case Builtin::BIbcmp:
4006     return Builtin::BIbcmp;
4007 
4008   case Builtin::BI__builtin_strncpy:
4009   case Builtin::BI__builtin___strncpy_chk:
4010   case Builtin::BIstrncpy:
4011     return Builtin::BIstrncpy;
4012 
4013   case Builtin::BI__builtin_strncmp:
4014   case Builtin::BIstrncmp:
4015     return Builtin::BIstrncmp;
4016 
4017   case Builtin::BI__builtin_strncasecmp:
4018   case Builtin::BIstrncasecmp:
4019     return Builtin::BIstrncasecmp;
4020 
4021   case Builtin::BI__builtin_strncat:
4022   case Builtin::BI__builtin___strncat_chk:
4023   case Builtin::BIstrncat:
4024     return Builtin::BIstrncat;
4025 
4026   case Builtin::BI__builtin_strndup:
4027   case Builtin::BIstrndup:
4028     return Builtin::BIstrndup;
4029 
4030   case Builtin::BI__builtin_strlen:
4031   case Builtin::BIstrlen:
4032     return Builtin::BIstrlen;
4033 
4034   case Builtin::BI__builtin_bzero:
4035   case Builtin::BIbzero:
4036     return Builtin::BIbzero;
4037 
4038   case Builtin::BIfree:
4039     return Builtin::BIfree;
4040 
4041   default:
4042     if (isExternC()) {
4043       if (FnInfo->isStr("memset"))
4044         return Builtin::BImemset;
4045       else if (FnInfo->isStr("memcpy"))
4046         return Builtin::BImemcpy;
4047       else if (FnInfo->isStr("mempcpy"))
4048         return Builtin::BImempcpy;
4049       else if (FnInfo->isStr("memmove"))
4050         return Builtin::BImemmove;
4051       else if (FnInfo->isStr("memcmp"))
4052         return Builtin::BImemcmp;
4053       else if (FnInfo->isStr("bcmp"))
4054         return Builtin::BIbcmp;
4055       else if (FnInfo->isStr("strncpy"))
4056         return Builtin::BIstrncpy;
4057       else if (FnInfo->isStr("strncmp"))
4058         return Builtin::BIstrncmp;
4059       else if (FnInfo->isStr("strncasecmp"))
4060         return Builtin::BIstrncasecmp;
4061       else if (FnInfo->isStr("strncat"))
4062         return Builtin::BIstrncat;
4063       else if (FnInfo->isStr("strndup"))
4064         return Builtin::BIstrndup;
4065       else if (FnInfo->isStr("strlen"))
4066         return Builtin::BIstrlen;
4067       else if (FnInfo->isStr("bzero"))
4068         return Builtin::BIbzero;
4069     } else if (isInStdNamespace()) {
4070       if (FnInfo->isStr("free"))
4071         return Builtin::BIfree;
4072     }
4073     break;
4074   }
4075   return 0;
4076 }
4077 
getODRHash() const4078 unsigned FunctionDecl::getODRHash() const {
4079   assert(hasODRHash());
4080   return ODRHash;
4081 }
4082 
getODRHash()4083 unsigned FunctionDecl::getODRHash() {
4084   if (hasODRHash())
4085     return ODRHash;
4086 
4087   if (auto *FT = getInstantiatedFromMemberFunction()) {
4088     setHasODRHash(true);
4089     ODRHash = FT->getODRHash();
4090     return ODRHash;
4091   }
4092 
4093   class ODRHash Hash;
4094   Hash.AddFunctionDecl(this);
4095   setHasODRHash(true);
4096   ODRHash = Hash.CalculateHash();
4097   return ODRHash;
4098 }
4099 
4100 //===----------------------------------------------------------------------===//
4101 // FieldDecl Implementation
4102 //===----------------------------------------------------------------------===//
4103 
Create(const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,Expr * BW,bool Mutable,InClassInitStyle InitStyle)4104 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4105                              SourceLocation StartLoc, SourceLocation IdLoc,
4106                              IdentifierInfo *Id, QualType T,
4107                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4108                              InClassInitStyle InitStyle) {
4109   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4110                                BW, Mutable, InitStyle);
4111 }
4112 
CreateDeserialized(ASTContext & C,unsigned ID)4113 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4114   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4115                                SourceLocation(), nullptr, QualType(), nullptr,
4116                                nullptr, false, ICIS_NoInit);
4117 }
4118 
isAnonymousStructOrUnion() const4119 bool FieldDecl::isAnonymousStructOrUnion() const {
4120   if (!isImplicit() || getDeclName())
4121     return false;
4122 
4123   if (const auto *Record = getType()->getAs<RecordType>())
4124     return Record->getDecl()->isAnonymousStructOrUnion();
4125 
4126   return false;
4127 }
4128 
getBitWidthValue(const ASTContext & Ctx) const4129 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4130   assert(isBitField() && "not a bitfield");
4131   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4132 }
4133 
isZeroLengthBitField(const ASTContext & Ctx) const4134 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4135   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4136          getBitWidthValue(Ctx) == 0;
4137 }
4138 
isZeroSize(const ASTContext & Ctx) const4139 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4140   if (isZeroLengthBitField(Ctx))
4141     return true;
4142 
4143   // C++2a [intro.object]p7:
4144   //   An object has nonzero size if it
4145   //     -- is not a potentially-overlapping subobject, or
4146   if (!hasAttr<NoUniqueAddressAttr>())
4147     return false;
4148 
4149   //     -- is not of class type, or
4150   const auto *RT = getType()->getAs<RecordType>();
4151   if (!RT)
4152     return false;
4153   const RecordDecl *RD = RT->getDecl()->getDefinition();
4154   if (!RD) {
4155     assert(isInvalidDecl() && "valid field has incomplete type");
4156     return false;
4157   }
4158 
4159   //     -- [has] virtual member functions or virtual base classes, or
4160   //     -- has subobjects of nonzero size or bit-fields of nonzero length
4161   const auto *CXXRD = cast<CXXRecordDecl>(RD);
4162   if (!CXXRD->isEmpty())
4163     return false;
4164 
4165   // Otherwise, [...] the circumstances under which the object has zero size
4166   // are implementation-defined.
4167   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4168   // ABI will do.
4169   return true;
4170 }
4171 
getFieldIndex() const4172 unsigned FieldDecl::getFieldIndex() const {
4173   const FieldDecl *Canonical = getCanonicalDecl();
4174   if (Canonical != this)
4175     return Canonical->getFieldIndex();
4176 
4177   if (CachedFieldIndex) return CachedFieldIndex - 1;
4178 
4179   unsigned Index = 0;
4180   const RecordDecl *RD = getParent()->getDefinition();
4181   assert(RD && "requested index for field of struct with no definition");
4182 
4183   for (auto *Field : RD->fields()) {
4184     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4185     ++Index;
4186   }
4187 
4188   assert(CachedFieldIndex && "failed to find field in parent");
4189   return CachedFieldIndex - 1;
4190 }
4191 
getSourceRange() const4192 SourceRange FieldDecl::getSourceRange() const {
4193   const Expr *FinalExpr = getInClassInitializer();
4194   if (!FinalExpr)
4195     FinalExpr = getBitWidth();
4196   if (FinalExpr)
4197     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4198   return DeclaratorDecl::getSourceRange();
4199 }
4200 
setCapturedVLAType(const VariableArrayType * VLAType)4201 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4202   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4203          "capturing type in non-lambda or captured record.");
4204   assert(InitStorage.getInt() == ISK_NoInit &&
4205          InitStorage.getPointer() == nullptr &&
4206          "bit width, initializer or captured type already set");
4207   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4208                                ISK_CapturedVLAType);
4209 }
4210 
4211 //===----------------------------------------------------------------------===//
4212 // TagDecl Implementation
4213 //===----------------------------------------------------------------------===//
4214 
TagDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,TagDecl * PrevDecl,SourceLocation StartL)4215 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4216                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4217                  SourceLocation StartL)
4218     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4219       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4220   assert((DK != Enum || TK == TTK_Enum) &&
4221          "EnumDecl not matched with TTK_Enum");
4222   setPreviousDecl(PrevDecl);
4223   setTagKind(TK);
4224   setCompleteDefinition(false);
4225   setBeingDefined(false);
4226   setEmbeddedInDeclarator(false);
4227   setFreeStanding(false);
4228   setCompleteDefinitionRequired(false);
4229 }
4230 
getOuterLocStart() const4231 SourceLocation TagDecl::getOuterLocStart() const {
4232   return getTemplateOrInnerLocStart(this);
4233 }
4234 
getSourceRange() const4235 SourceRange TagDecl::getSourceRange() const {
4236   SourceLocation RBraceLoc = BraceRange.getEnd();
4237   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4238   return SourceRange(getOuterLocStart(), E);
4239 }
4240 
getCanonicalDecl()4241 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4242 
setTypedefNameForAnonDecl(TypedefNameDecl * TDD)4243 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4244   TypedefNameDeclOrQualifier = TDD;
4245   if (const Type *T = getTypeForDecl()) {
4246     (void)T;
4247     assert(T->isLinkageValid());
4248   }
4249   assert(isLinkageValid());
4250 }
4251 
startDefinition()4252 void TagDecl::startDefinition() {
4253   setBeingDefined(true);
4254 
4255   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4256     struct CXXRecordDecl::DefinitionData *Data =
4257       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4258     for (auto I : redecls())
4259       cast<CXXRecordDecl>(I)->DefinitionData = Data;
4260   }
4261 }
4262 
completeDefinition()4263 void TagDecl::completeDefinition() {
4264   assert((!isa<CXXRecordDecl>(this) ||
4265           cast<CXXRecordDecl>(this)->hasDefinition()) &&
4266          "definition completed but not started");
4267 
4268   setCompleteDefinition(true);
4269   setBeingDefined(false);
4270 
4271   if (ASTMutationListener *L = getASTMutationListener())
4272     L->CompletedTagDefinition(this);
4273 }
4274 
getDefinition() const4275 TagDecl *TagDecl::getDefinition() const {
4276   if (isCompleteDefinition())
4277     return const_cast<TagDecl *>(this);
4278 
4279   // If it's possible for us to have an out-of-date definition, check now.
4280   if (mayHaveOutOfDateDef()) {
4281     if (IdentifierInfo *II = getIdentifier()) {
4282       if (II->isOutOfDate()) {
4283         updateOutOfDate(*II);
4284       }
4285     }
4286   }
4287 
4288   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4289     return CXXRD->getDefinition();
4290 
4291   for (auto R : redecls())
4292     if (R->isCompleteDefinition())
4293       return R;
4294 
4295   return nullptr;
4296 }
4297 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)4298 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4299   if (QualifierLoc) {
4300     // Make sure the extended qualifier info is allocated.
4301     if (!hasExtInfo())
4302       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4303     // Set qualifier info.
4304     getExtInfo()->QualifierLoc = QualifierLoc;
4305   } else {
4306     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4307     if (hasExtInfo()) {
4308       if (getExtInfo()->NumTemplParamLists == 0) {
4309         getASTContext().Deallocate(getExtInfo());
4310         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4311       }
4312       else
4313         getExtInfo()->QualifierLoc = QualifierLoc;
4314     }
4315   }
4316 }
4317 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)4318 void TagDecl::setTemplateParameterListsInfo(
4319     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4320   assert(!TPLists.empty());
4321   // Make sure the extended decl info is allocated.
4322   if (!hasExtInfo())
4323     // Allocate external info struct.
4324     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4325   // Set the template parameter lists info.
4326   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4327 }
4328 
4329 //===----------------------------------------------------------------------===//
4330 // EnumDecl Implementation
4331 //===----------------------------------------------------------------------===//
4332 
EnumDecl(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool Scoped,bool ScopedUsingClassTag,bool Fixed)4333 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4334                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4335                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4336     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4337   assert(Scoped || !ScopedUsingClassTag);
4338   IntegerType = nullptr;
4339   setNumPositiveBits(0);
4340   setNumNegativeBits(0);
4341   setScoped(Scoped);
4342   setScopedUsingClassTag(ScopedUsingClassTag);
4343   setFixed(Fixed);
4344   setHasODRHash(false);
4345   ODRHash = 0;
4346 }
4347 
anchor()4348 void EnumDecl::anchor() {}
4349 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool IsScoped,bool IsScopedUsingClassTag,bool IsFixed)4350 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4351                            SourceLocation StartLoc, SourceLocation IdLoc,
4352                            IdentifierInfo *Id,
4353                            EnumDecl *PrevDecl, bool IsScoped,
4354                            bool IsScopedUsingClassTag, bool IsFixed) {
4355   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4356                                     IsScoped, IsScopedUsingClassTag, IsFixed);
4357   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4358   C.getTypeDeclType(Enum, PrevDecl);
4359   return Enum;
4360 }
4361 
CreateDeserialized(ASTContext & C,unsigned ID)4362 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4363   EnumDecl *Enum =
4364       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4365                            nullptr, nullptr, false, false, false);
4366   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4367   return Enum;
4368 }
4369 
getIntegerTypeRange() const4370 SourceRange EnumDecl::getIntegerTypeRange() const {
4371   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4372     return TI->getTypeLoc().getSourceRange();
4373   return SourceRange();
4374 }
4375 
completeDefinition(QualType NewType,QualType NewPromotionType,unsigned NumPositiveBits,unsigned NumNegativeBits)4376 void EnumDecl::completeDefinition(QualType NewType,
4377                                   QualType NewPromotionType,
4378                                   unsigned NumPositiveBits,
4379                                   unsigned NumNegativeBits) {
4380   assert(!isCompleteDefinition() && "Cannot redefine enums!");
4381   if (!IntegerType)
4382     IntegerType = NewType.getTypePtr();
4383   PromotionType = NewPromotionType;
4384   setNumPositiveBits(NumPositiveBits);
4385   setNumNegativeBits(NumNegativeBits);
4386   TagDecl::completeDefinition();
4387 }
4388 
isClosed() const4389 bool EnumDecl::isClosed() const {
4390   if (const auto *A = getAttr<EnumExtensibilityAttr>())
4391     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4392   return true;
4393 }
4394 
isClosedFlag() const4395 bool EnumDecl::isClosedFlag() const {
4396   return isClosed() && hasAttr<FlagEnumAttr>();
4397 }
4398 
isClosedNonFlag() const4399 bool EnumDecl::isClosedNonFlag() const {
4400   return isClosed() && !hasAttr<FlagEnumAttr>();
4401 }
4402 
getTemplateSpecializationKind() const4403 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4404   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4405     return MSI->getTemplateSpecializationKind();
4406 
4407   return TSK_Undeclared;
4408 }
4409 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)4410 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4411                                          SourceLocation PointOfInstantiation) {
4412   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4413   assert(MSI && "Not an instantiated member enumeration?");
4414   MSI->setTemplateSpecializationKind(TSK);
4415   if (TSK != TSK_ExplicitSpecialization &&
4416       PointOfInstantiation.isValid() &&
4417       MSI->getPointOfInstantiation().isInvalid())
4418     MSI->setPointOfInstantiation(PointOfInstantiation);
4419 }
4420 
getTemplateInstantiationPattern() const4421 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4422   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4423     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4424       EnumDecl *ED = getInstantiatedFromMemberEnum();
4425       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4426         ED = NewED;
4427       return getDefinitionOrSelf(ED);
4428     }
4429   }
4430 
4431   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4432          "couldn't find pattern for enum instantiation");
4433   return nullptr;
4434 }
4435 
getInstantiatedFromMemberEnum() const4436 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4437   if (SpecializationInfo)
4438     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4439 
4440   return nullptr;
4441 }
4442 
setInstantiationOfMemberEnum(ASTContext & C,EnumDecl * ED,TemplateSpecializationKind TSK)4443 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4444                                             TemplateSpecializationKind TSK) {
4445   assert(!SpecializationInfo && "Member enum is already a specialization");
4446   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4447 }
4448 
getODRHash()4449 unsigned EnumDecl::getODRHash() {
4450   if (hasODRHash())
4451     return ODRHash;
4452 
4453   class ODRHash Hash;
4454   Hash.AddEnumDecl(this);
4455   setHasODRHash(true);
4456   ODRHash = Hash.CalculateHash();
4457   return ODRHash;
4458 }
4459 
4460 //===----------------------------------------------------------------------===//
4461 // RecordDecl Implementation
4462 //===----------------------------------------------------------------------===//
4463 
RecordDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4464 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4465                        DeclContext *DC, SourceLocation StartLoc,
4466                        SourceLocation IdLoc, IdentifierInfo *Id,
4467                        RecordDecl *PrevDecl)
4468     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4469   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4470   setHasFlexibleArrayMember(false);
4471   setAnonymousStructOrUnion(false);
4472   setHasObjectMember(false);
4473   setHasVolatileMember(false);
4474   setHasLoadedFieldsFromExternalStorage(false);
4475   setNonTrivialToPrimitiveDefaultInitialize(false);
4476   setNonTrivialToPrimitiveCopy(false);
4477   setNonTrivialToPrimitiveDestroy(false);
4478   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4479   setHasNonTrivialToPrimitiveDestructCUnion(false);
4480   setHasNonTrivialToPrimitiveCopyCUnion(false);
4481   setParamDestroyedInCallee(false);
4482   setArgPassingRestrictions(APK_CanPassInRegs);
4483 }
4484 
Create(const ASTContext & C,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4485 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4486                                SourceLocation StartLoc, SourceLocation IdLoc,
4487                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
4488   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4489                                          StartLoc, IdLoc, Id, PrevDecl);
4490   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4491 
4492   C.getTypeDeclType(R, PrevDecl);
4493   return R;
4494 }
4495 
CreateDeserialized(const ASTContext & C,unsigned ID)4496 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4497   RecordDecl *R =
4498       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4499                              SourceLocation(), nullptr, nullptr);
4500   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4501   return R;
4502 }
4503 
isInjectedClassName() const4504 bool RecordDecl::isInjectedClassName() const {
4505   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4506     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4507 }
4508 
isLambda() const4509 bool RecordDecl::isLambda() const {
4510   if (auto RD = dyn_cast<CXXRecordDecl>(this))
4511     return RD->isLambda();
4512   return false;
4513 }
4514 
isCapturedRecord() const4515 bool RecordDecl::isCapturedRecord() const {
4516   return hasAttr<CapturedRecordAttr>();
4517 }
4518 
setCapturedRecord()4519 void RecordDecl::setCapturedRecord() {
4520   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4521 }
4522 
isOrContainsUnion() const4523 bool RecordDecl::isOrContainsUnion() const {
4524   if (isUnion())
4525     return true;
4526 
4527   if (const RecordDecl *Def = getDefinition()) {
4528     for (const FieldDecl *FD : Def->fields()) {
4529       const RecordType *RT = FD->getType()->getAs<RecordType>();
4530       if (RT && RT->getDecl()->isOrContainsUnion())
4531         return true;
4532     }
4533   }
4534 
4535   return false;
4536 }
4537 
field_begin() const4538 RecordDecl::field_iterator RecordDecl::field_begin() const {
4539   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4540     LoadFieldsFromExternalStorage();
4541 
4542   return field_iterator(decl_iterator(FirstDecl));
4543 }
4544 
4545 /// completeDefinition - Notes that the definition of this type is now
4546 /// complete.
completeDefinition()4547 void RecordDecl::completeDefinition() {
4548   assert(!isCompleteDefinition() && "Cannot redefine record!");
4549   TagDecl::completeDefinition();
4550 }
4551 
4552 /// isMsStruct - Get whether or not this record uses ms_struct layout.
4553 /// This which can be turned on with an attribute, pragma, or the
4554 /// -mms-bitfields command-line option.
isMsStruct(const ASTContext & C) const4555 bool RecordDecl::isMsStruct(const ASTContext &C) const {
4556   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4557 }
4558 
LoadFieldsFromExternalStorage() const4559 void RecordDecl::LoadFieldsFromExternalStorage() const {
4560   ExternalASTSource *Source = getASTContext().getExternalSource();
4561   assert(hasExternalLexicalStorage() && Source && "No external storage?");
4562 
4563   // Notify that we have a RecordDecl doing some initialization.
4564   ExternalASTSource::Deserializing TheFields(Source);
4565 
4566   SmallVector<Decl*, 64> Decls;
4567   setHasLoadedFieldsFromExternalStorage(true);
4568   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4569     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4570   }, Decls);
4571 
4572 #ifndef NDEBUG
4573   // Check that all decls we got were FieldDecls.
4574   for (unsigned i=0, e=Decls.size(); i != e; ++i)
4575     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4576 #endif
4577 
4578   if (Decls.empty())
4579     return;
4580 
4581   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4582                                                  /*FieldsAlreadyLoaded=*/false);
4583 }
4584 
mayInsertExtraPadding(bool EmitRemark) const4585 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4586   ASTContext &Context = getASTContext();
4587   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4588       (SanitizerKind::Address | SanitizerKind::KernelAddress);
4589   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4590     return false;
4591   const auto &Blacklist = Context.getSanitizerBlacklist();
4592   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4593   // We may be able to relax some of these requirements.
4594   int ReasonToReject = -1;
4595   if (!CXXRD || CXXRD->isExternCContext())
4596     ReasonToReject = 0;  // is not C++.
4597   else if (CXXRD->hasAttr<PackedAttr>())
4598     ReasonToReject = 1;  // is packed.
4599   else if (CXXRD->isUnion())
4600     ReasonToReject = 2;  // is a union.
4601   else if (CXXRD->isTriviallyCopyable())
4602     ReasonToReject = 3;  // is trivially copyable.
4603   else if (CXXRD->hasTrivialDestructor())
4604     ReasonToReject = 4;  // has trivial destructor.
4605   else if (CXXRD->isStandardLayout())
4606     ReasonToReject = 5;  // is standard layout.
4607   else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4608                                            "field-padding"))
4609     ReasonToReject = 6;  // is in an excluded file.
4610   else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4611                                        getQualifiedNameAsString(),
4612                                        "field-padding"))
4613     ReasonToReject = 7;  // The type is excluded.
4614 
4615   if (EmitRemark) {
4616     if (ReasonToReject >= 0)
4617       Context.getDiagnostics().Report(
4618           getLocation(),
4619           diag::remark_sanitize_address_insert_extra_padding_rejected)
4620           << getQualifiedNameAsString() << ReasonToReject;
4621     else
4622       Context.getDiagnostics().Report(
4623           getLocation(),
4624           diag::remark_sanitize_address_insert_extra_padding_accepted)
4625           << getQualifiedNameAsString();
4626   }
4627   return ReasonToReject < 0;
4628 }
4629 
findFirstNamedDataMember() const4630 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4631   for (const auto *I : fields()) {
4632     if (I->getIdentifier())
4633       return I;
4634 
4635     if (const auto *RT = I->getType()->getAs<RecordType>())
4636       if (const FieldDecl *NamedDataMember =
4637               RT->getDecl()->findFirstNamedDataMember())
4638         return NamedDataMember;
4639   }
4640 
4641   // We didn't find a named data member.
4642   return nullptr;
4643 }
4644 
4645 //===----------------------------------------------------------------------===//
4646 // BlockDecl Implementation
4647 //===----------------------------------------------------------------------===//
4648 
BlockDecl(DeclContext * DC,SourceLocation CaretLoc)4649 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4650     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4651   setIsVariadic(false);
4652   setCapturesCXXThis(false);
4653   setBlockMissingReturnType(true);
4654   setIsConversionFromLambda(false);
4655   setDoesNotEscape(false);
4656   setCanAvoidCopyToHeap(false);
4657 }
4658 
setParams(ArrayRef<ParmVarDecl * > NewParamInfo)4659 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4660   assert(!ParamInfo && "Already has param info!");
4661 
4662   // Zero params -> null pointer.
4663   if (!NewParamInfo.empty()) {
4664     NumParams = NewParamInfo.size();
4665     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4666     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4667   }
4668 }
4669 
setCaptures(ASTContext & Context,ArrayRef<Capture> Captures,bool CapturesCXXThis)4670 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4671                             bool CapturesCXXThis) {
4672   this->setCapturesCXXThis(CapturesCXXThis);
4673   this->NumCaptures = Captures.size();
4674 
4675   if (Captures.empty()) {
4676     this->Captures = nullptr;
4677     return;
4678   }
4679 
4680   this->Captures = Captures.copy(Context).data();
4681 }
4682 
capturesVariable(const VarDecl * variable) const4683 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4684   for (const auto &I : captures())
4685     // Only auto vars can be captured, so no redeclaration worries.
4686     if (I.getVariable() == variable)
4687       return true;
4688 
4689   return false;
4690 }
4691 
getSourceRange() const4692 SourceRange BlockDecl::getSourceRange() const {
4693   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4694 }
4695 
4696 //===----------------------------------------------------------------------===//
4697 // Other Decl Allocation/Deallocation Method Implementations
4698 //===----------------------------------------------------------------------===//
4699 
anchor()4700 void TranslationUnitDecl::anchor() {}
4701 
Create(ASTContext & C)4702 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4703   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4704 }
4705 
anchor()4706 void PragmaCommentDecl::anchor() {}
4707 
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation CommentLoc,PragmaMSCommentKind CommentKind,StringRef Arg)4708 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4709                                              TranslationUnitDecl *DC,
4710                                              SourceLocation CommentLoc,
4711                                              PragmaMSCommentKind CommentKind,
4712                                              StringRef Arg) {
4713   PragmaCommentDecl *PCD =
4714       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4715           PragmaCommentDecl(DC, CommentLoc, CommentKind);
4716   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4717   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4718   return PCD;
4719 }
4720 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned ArgSize)4721 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4722                                                          unsigned ID,
4723                                                          unsigned ArgSize) {
4724   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4725       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4726 }
4727 
anchor()4728 void PragmaDetectMismatchDecl::anchor() {}
4729 
4730 PragmaDetectMismatchDecl *
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation Loc,StringRef Name,StringRef Value)4731 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4732                                  SourceLocation Loc, StringRef Name,
4733                                  StringRef Value) {
4734   size_t ValueStart = Name.size() + 1;
4735   PragmaDetectMismatchDecl *PDMD =
4736       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4737           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4738   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4739   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4740   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4741          Value.size());
4742   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4743   return PDMD;
4744 }
4745 
4746 PragmaDetectMismatchDecl *
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NameValueSize)4747 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4748                                              unsigned NameValueSize) {
4749   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4750       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4751 }
4752 
anchor()4753 void ExternCContextDecl::anchor() {}
4754 
Create(const ASTContext & C,TranslationUnitDecl * DC)4755 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4756                                                TranslationUnitDecl *DC) {
4757   return new (C, DC) ExternCContextDecl(DC);
4758 }
4759 
anchor()4760 void LabelDecl::anchor() {}
4761 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II)4762 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4763                              SourceLocation IdentL, IdentifierInfo *II) {
4764   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4765 }
4766 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II,SourceLocation GnuLabelL)4767 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4768                              SourceLocation IdentL, IdentifierInfo *II,
4769                              SourceLocation GnuLabelL) {
4770   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4771   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4772 }
4773 
CreateDeserialized(ASTContext & C,unsigned ID)4774 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4775   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4776                                SourceLocation());
4777 }
4778 
setMSAsmLabel(StringRef Name)4779 void LabelDecl::setMSAsmLabel(StringRef Name) {
4780 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4781   memcpy(Buffer, Name.data(), Name.size());
4782   Buffer[Name.size()] = '\0';
4783   MSAsmName = Buffer;
4784 }
4785 
anchor()4786 void ValueDecl::anchor() {}
4787 
isWeak() const4788 bool ValueDecl::isWeak() const {
4789   auto *MostRecent = getMostRecentDecl();
4790   return MostRecent->hasAttr<WeakAttr>() ||
4791          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
4792 }
4793 
anchor()4794 void ImplicitParamDecl::anchor() {}
4795 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdLoc,IdentifierInfo * Id,QualType Type,ImplicitParamKind ParamKind)4796 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4797                                              SourceLocation IdLoc,
4798                                              IdentifierInfo *Id, QualType Type,
4799                                              ImplicitParamKind ParamKind) {
4800   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4801 }
4802 
Create(ASTContext & C,QualType Type,ImplicitParamKind ParamKind)4803 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4804                                              ImplicitParamKind ParamKind) {
4805   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4806 }
4807 
CreateDeserialized(ASTContext & C,unsigned ID)4808 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4809                                                          unsigned ID) {
4810   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4811 }
4812 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass SC,bool isInlineSpecified,bool hasWrittenPrototype,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)4813 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4814                                    SourceLocation StartLoc,
4815                                    const DeclarationNameInfo &NameInfo,
4816                                    QualType T, TypeSourceInfo *TInfo,
4817                                    StorageClass SC, bool isInlineSpecified,
4818                                    bool hasWrittenPrototype,
4819                                    ConstexprSpecKind ConstexprKind,
4820                                    Expr *TrailingRequiresClause) {
4821   FunctionDecl *New =
4822       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4823                                SC, isInlineSpecified, ConstexprKind,
4824                                TrailingRequiresClause);
4825   New->setHasWrittenPrototype(hasWrittenPrototype);
4826   return New;
4827 }
4828 
CreateDeserialized(ASTContext & C,unsigned ID)4829 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4830   return new (C, ID) FunctionDecl(
4831       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
4832       nullptr, SC_None, false, ConstexprSpecKind::Unspecified, nullptr);
4833 }
4834 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)4835 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4836   return new (C, DC) BlockDecl(DC, L);
4837 }
4838 
CreateDeserialized(ASTContext & C,unsigned ID)4839 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4840   return new (C, ID) BlockDecl(nullptr, SourceLocation());
4841 }
4842 
CapturedDecl(DeclContext * DC,unsigned NumParams)4843 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4844     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4845       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4846 
Create(ASTContext & C,DeclContext * DC,unsigned NumParams)4847 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4848                                    unsigned NumParams) {
4849   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4850       CapturedDecl(DC, NumParams);
4851 }
4852 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumParams)4853 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4854                                                unsigned NumParams) {
4855   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4856       CapturedDecl(nullptr, NumParams);
4857 }
4858 
getBody() const4859 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
setBody(Stmt * B)4860 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4861 
isNothrow() const4862 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
setNothrow(bool Nothrow)4863 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4864 
Create(ASTContext & C,EnumDecl * CD,SourceLocation L,IdentifierInfo * Id,QualType T,Expr * E,const llvm::APSInt & V)4865 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4866                                            SourceLocation L,
4867                                            IdentifierInfo *Id, QualType T,
4868                                            Expr *E, const llvm::APSInt &V) {
4869   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4870 }
4871 
4872 EnumConstantDecl *
CreateDeserialized(ASTContext & C,unsigned ID)4873 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4874   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4875                                       QualType(), nullptr, llvm::APSInt());
4876 }
4877 
anchor()4878 void IndirectFieldDecl::anchor() {}
4879 
IndirectFieldDecl(ASTContext & C,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,MutableArrayRef<NamedDecl * > CH)4880 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4881                                      SourceLocation L, DeclarationName N,
4882                                      QualType T,
4883                                      MutableArrayRef<NamedDecl *> CH)
4884     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4885       ChainingSize(CH.size()) {
4886   // In C++, indirect field declarations conflict with tag declarations in the
4887   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4888   if (C.getLangOpts().CPlusPlus)
4889     IdentifierNamespace |= IDNS_Tag;
4890 }
4891 
4892 IndirectFieldDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,QualType T,llvm::MutableArrayRef<NamedDecl * > CH)4893 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4894                           IdentifierInfo *Id, QualType T,
4895                           llvm::MutableArrayRef<NamedDecl *> CH) {
4896   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4897 }
4898 
CreateDeserialized(ASTContext & C,unsigned ID)4899 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4900                                                          unsigned ID) {
4901   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4902                                        DeclarationName(), QualType(), None);
4903 }
4904 
getSourceRange() const4905 SourceRange EnumConstantDecl::getSourceRange() const {
4906   SourceLocation End = getLocation();
4907   if (Init)
4908     End = Init->getEndLoc();
4909   return SourceRange(getLocation(), End);
4910 }
4911 
anchor()4912 void TypeDecl::anchor() {}
4913 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)4914 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4915                                  SourceLocation StartLoc, SourceLocation IdLoc,
4916                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4917   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4918 }
4919 
anchor()4920 void TypedefNameDecl::anchor() {}
4921 
getAnonDeclWithTypedefName(bool AnyRedecl) const4922 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4923   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4924     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4925     auto *ThisTypedef = this;
4926     if (AnyRedecl && OwningTypedef) {
4927       OwningTypedef = OwningTypedef->getCanonicalDecl();
4928       ThisTypedef = ThisTypedef->getCanonicalDecl();
4929     }
4930     if (OwningTypedef == ThisTypedef)
4931       return TT->getDecl();
4932   }
4933 
4934   return nullptr;
4935 }
4936 
isTransparentTagSlow() const4937 bool TypedefNameDecl::isTransparentTagSlow() const {
4938   auto determineIsTransparent = [&]() {
4939     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4940       if (auto *TD = TT->getDecl()) {
4941         if (TD->getName() != getName())
4942           return false;
4943         SourceLocation TTLoc = getLocation();
4944         SourceLocation TDLoc = TD->getLocation();
4945         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4946           return false;
4947         SourceManager &SM = getASTContext().getSourceManager();
4948         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4949       }
4950     }
4951     return false;
4952   };
4953 
4954   bool isTransparent = determineIsTransparent();
4955   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
4956   return isTransparent;
4957 }
4958 
CreateDeserialized(ASTContext & C,unsigned ID)4959 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4960   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4961                                  nullptr, nullptr);
4962 }
4963 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)4964 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4965                                      SourceLocation StartLoc,
4966                                      SourceLocation IdLoc, IdentifierInfo *Id,
4967                                      TypeSourceInfo *TInfo) {
4968   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4969 }
4970 
CreateDeserialized(ASTContext & C,unsigned ID)4971 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4972   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4973                                    SourceLocation(), nullptr, nullptr);
4974 }
4975 
getSourceRange() const4976 SourceRange TypedefDecl::getSourceRange() const {
4977   SourceLocation RangeEnd = getLocation();
4978   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4979     if (typeIsPostfix(TInfo->getType()))
4980       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4981   }
4982   return SourceRange(getBeginLoc(), RangeEnd);
4983 }
4984 
getSourceRange() const4985 SourceRange TypeAliasDecl::getSourceRange() const {
4986   SourceLocation RangeEnd = getBeginLoc();
4987   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4988     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4989   return SourceRange(getBeginLoc(), RangeEnd);
4990 }
4991 
anchor()4992 void FileScopeAsmDecl::anchor() {}
4993 
Create(ASTContext & C,DeclContext * DC,StringLiteral * Str,SourceLocation AsmLoc,SourceLocation RParenLoc)4994 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4995                                            StringLiteral *Str,
4996                                            SourceLocation AsmLoc,
4997                                            SourceLocation RParenLoc) {
4998   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4999 }
5000 
CreateDeserialized(ASTContext & C,unsigned ID)5001 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5002                                                        unsigned ID) {
5003   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5004                                       SourceLocation());
5005 }
5006 
anchor()5007 void EmptyDecl::anchor() {}
5008 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)5009 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5010   return new (C, DC) EmptyDecl(DC, L);
5011 }
5012 
CreateDeserialized(ASTContext & C,unsigned ID)5013 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5014   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5015 }
5016 
5017 //===----------------------------------------------------------------------===//
5018 // ImportDecl Implementation
5019 //===----------------------------------------------------------------------===//
5020 
5021 /// Retrieve the number of module identifiers needed to name the given
5022 /// module.
getNumModuleIdentifiers(Module * Mod)5023 static unsigned getNumModuleIdentifiers(Module *Mod) {
5024   unsigned Result = 1;
5025   while (Mod->Parent) {
5026     Mod = Mod->Parent;
5027     ++Result;
5028   }
5029   return Result;
5030 }
5031 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5032 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5033                        Module *Imported,
5034                        ArrayRef<SourceLocation> IdentifierLocs)
5035     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5036       NextLocalImportAndComplete(nullptr, true) {
5037   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5038   auto *StoredLocs = getTrailingObjects<SourceLocation>();
5039   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5040                           StoredLocs);
5041 }
5042 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5043 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5044                        Module *Imported, SourceLocation EndLoc)
5045     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5046       NextLocalImportAndComplete(nullptr, false) {
5047   *getTrailingObjects<SourceLocation>() = EndLoc;
5048 }
5049 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5050 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5051                                SourceLocation StartLoc, Module *Imported,
5052                                ArrayRef<SourceLocation> IdentifierLocs) {
5053   return new (C, DC,
5054               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5055       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5056 }
5057 
CreateImplicit(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5058 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5059                                        SourceLocation StartLoc,
5060                                        Module *Imported,
5061                                        SourceLocation EndLoc) {
5062   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5063       ImportDecl(DC, StartLoc, Imported, EndLoc);
5064   Import->setImplicit();
5065   return Import;
5066 }
5067 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumLocations)5068 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5069                                            unsigned NumLocations) {
5070   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5071       ImportDecl(EmptyShell());
5072 }
5073 
getIdentifierLocs() const5074 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5075   if (!isImportComplete())
5076     return None;
5077 
5078   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5079   return llvm::makeArrayRef(StoredLocs,
5080                             getNumModuleIdentifiers(getImportedModule()));
5081 }
5082 
getSourceRange() const5083 SourceRange ImportDecl::getSourceRange() const {
5084   if (!isImportComplete())
5085     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5086 
5087   return SourceRange(getLocation(), getIdentifierLocs().back());
5088 }
5089 
5090 //===----------------------------------------------------------------------===//
5091 // ExportDecl Implementation
5092 //===----------------------------------------------------------------------===//
5093 
anchor()5094 void ExportDecl::anchor() {}
5095 
Create(ASTContext & C,DeclContext * DC,SourceLocation ExportLoc)5096 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5097                                SourceLocation ExportLoc) {
5098   return new (C, DC) ExportDecl(DC, ExportLoc);
5099 }
5100 
CreateDeserialized(ASTContext & C,unsigned ID)5101 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5102   return new (C, ID) ExportDecl(nullptr, SourceLocation());
5103 }
5104