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