clang  16.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
39 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/Lookup.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/Triple.h"
50 #include <algorithm>
51 #include <cstring>
52 #include <functional>
53 #include <unordered_map>
54 
55 using namespace clang;
56 using namespace sema;
57 
59  if (OwnedType) {
60  Decl *Group[2] = { OwnedType, Ptr };
61  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
62  }
63 
64  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 }
66 
67 namespace {
68 
69 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
70  public:
71  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
72  bool AllowTemplates = false,
73  bool AllowNonTemplates = true)
74  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
75  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
76  WantExpressionKeywords = false;
77  WantCXXNamedCasts = false;
78  WantRemainingKeywords = false;
79  }
80 
81  bool ValidateCandidate(const TypoCorrection &candidate) override {
82  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
83  if (!AllowInvalidDecl && ND->isInvalidDecl())
84  return false;
85 
86  if (getAsTypeTemplateDecl(ND))
87  return AllowTemplates;
88 
89  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
90  if (!IsType)
91  return false;
92 
93  if (AllowNonTemplates)
94  return true;
95 
96  // An injected-class-name of a class template (specialization) is valid
97  // as a template or as a non-template.
98  if (AllowTemplates) {
99  auto *RD = dyn_cast<CXXRecordDecl>(ND);
100  if (!RD || !RD->isInjectedClassName())
101  return false;
102  RD = cast<CXXRecordDecl>(RD->getDeclContext());
103  return RD->getDescribedClassTemplate() ||
104  isa<ClassTemplateSpecializationDecl>(RD);
105  }
106 
107  return false;
108  }
109 
110  return !WantClassName && candidate.isKeyword();
111  }
112 
113  std::unique_ptr<CorrectionCandidateCallback> clone() override {
114  return std::make_unique<TypeNameValidatorCCC>(*this);
115  }
116 
117  private:
118  bool AllowInvalidDecl;
119  bool WantClassName;
120  bool AllowTemplates;
121  bool AllowNonTemplates;
122 };
123 
124 } // end anonymous namespace
125 
126 /// Determine whether the token kind starts a simple-type-specifier.
128  switch (Kind) {
129  // FIXME: Take into account the current language when deciding whether a
130  // token kind is a valid type specifier
131  case tok::kw_short:
132  case tok::kw_long:
133  case tok::kw___int64:
134  case tok::kw___int128:
135  case tok::kw_signed:
136  case tok::kw_unsigned:
137  case tok::kw_void:
138  case tok::kw_char:
139  case tok::kw_int:
140  case tok::kw_half:
141  case tok::kw_float:
142  case tok::kw_double:
143  case tok::kw___bf16:
144  case tok::kw__Float16:
145  case tok::kw___float128:
146  case tok::kw___ibm128:
147  case tok::kw_wchar_t:
148  case tok::kw_bool:
149 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
150 #include "clang/Basic/TransformTypeTraits.def"
151  case tok::kw___auto_type:
152  return true;
153 
154  case tok::annot_typename:
155  case tok::kw_char16_t:
156  case tok::kw_char32_t:
157  case tok::kw_typeof:
158  case tok::annot_decltype:
159  case tok::kw_decltype:
160  return getLangOpts().CPlusPlus;
161 
162  case tok::kw_char8_t:
163  return getLangOpts().Char8;
164 
165  default:
166  break;
167  }
168 
169  return false;
170 }
171 
172 namespace {
173 enum class UnqualifiedTypeNameLookupResult {
174  NotFound,
175  FoundNonType,
176  FoundType
177 };
178 } // end anonymous namespace
179 
180 /// Tries to perform unqualified lookup of the type decls in bases for
181 /// dependent class.
182 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
183 /// type decl, \a FoundType if only type decls are found.
184 static UnqualifiedTypeNameLookupResult
186  SourceLocation NameLoc,
187  const CXXRecordDecl *RD) {
188  if (!RD->hasDefinition())
189  return UnqualifiedTypeNameLookupResult::NotFound;
190  // Look for type decls in base classes.
191  UnqualifiedTypeNameLookupResult FoundTypeDecl =
192  UnqualifiedTypeNameLookupResult::NotFound;
193  for (const auto &Base : RD->bases()) {
194  const CXXRecordDecl *BaseRD = nullptr;
195  if (auto *BaseTT = Base.getType()->getAs<TagType>())
196  BaseRD = BaseTT->getAsCXXRecordDecl();
197  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
198  // Look for type decls in dependent base classes that have known primary
199  // templates.
200  if (!TST || !TST->isDependentType())
201  continue;
202  auto *TD = TST->getTemplateName().getAsTemplateDecl();
203  if (!TD)
204  continue;
205  if (auto *BasePrimaryTemplate =
206  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
207  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
208  BaseRD = BasePrimaryTemplate;
209  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
211  CTD->findPartialSpecialization(Base.getType()))
212  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
213  BaseRD = PS;
214  }
215  }
216  }
217  if (BaseRD) {
218  for (NamedDecl *ND : BaseRD->lookup(&II)) {
219  if (!isa<TypeDecl>(ND))
220  return UnqualifiedTypeNameLookupResult::FoundNonType;
221  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222  }
223  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
224  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
225  case UnqualifiedTypeNameLookupResult::FoundNonType:
226  return UnqualifiedTypeNameLookupResult::FoundNonType;
227  case UnqualifiedTypeNameLookupResult::FoundType:
228  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
229  break;
230  case UnqualifiedTypeNameLookupResult::NotFound:
231  break;
232  }
233  }
234  }
235  }
236 
237  return FoundTypeDecl;
238 }
239 
241  const IdentifierInfo &II,
242  SourceLocation NameLoc) {
243  // Lookup in the parent class template context, if any.
244  const CXXRecordDecl *RD = nullptr;
245  UnqualifiedTypeNameLookupResult FoundTypeDecl =
246  UnqualifiedTypeNameLookupResult::NotFound;
247  for (DeclContext *DC = S.CurContext;
248  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
249  DC = DC->getParent()) {
250  // Look for type decls in dependent base classes that have known primary
251  // templates.
252  RD = dyn_cast<CXXRecordDecl>(DC);
253  if (RD && RD->getDescribedClassTemplate())
254  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
255  }
256  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
257  return nullptr;
258 
259  // We found some types in dependent base classes. Recover as if the user
260  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
261  // lookup during template instantiation.
262  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
263 
264  ASTContext &Context = S.Context;
265  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
266  cast<Type>(Context.getRecordType(RD)));
267  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
268 
269  CXXScopeSpec SS;
270  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
271 
272  TypeLocBuilder Builder;
273  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
274  DepTL.setNameLoc(NameLoc);
276  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
277  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
278 }
279 
280 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
282  SourceLocation NameLoc,
283  bool WantNontrivialTypeSourceInfo = true) {
284  switch (T->getTypeClass()) {
285  case Type::DeducedTemplateSpecialization:
286  case Type::Enum:
287  case Type::InjectedClassName:
288  case Type::Record:
289  case Type::Typedef:
290  case Type::UnresolvedUsing:
291  case Type::Using:
292  break;
293  // These can never be qualified so an ElaboratedType node
294  // would carry no additional meaning.
295  case Type::ObjCInterface:
296  case Type::ObjCTypeParam:
297  case Type::TemplateTypeParm:
298  return ParsedType::make(T);
299  default:
300  llvm_unreachable("Unexpected Type Class");
301  }
302 
303  if (!SS || SS->isEmpty())
304  return ParsedType::make(
305  S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
306 
307  QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
308  if (!WantNontrivialTypeSourceInfo)
309  return ParsedType::make(ElTy);
310 
311  TypeLocBuilder Builder;
312  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
313  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
316  return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
317 }
318 
319 /// If the identifier refers to a type name within this scope,
320 /// return the declaration of that type.
321 ///
322 /// This routine performs ordinary name lookup of the identifier II
323 /// within the given scope, with optional C++ scope specifier SS, to
324 /// determine whether the name refers to a type. If so, returns an
325 /// opaque pointer (actually a QualType) corresponding to that
326 /// type. Otherwise, returns NULL.
328  Scope *S, CXXScopeSpec *SS, bool isClassName,
329  bool HasTrailingDot, ParsedType ObjectTypePtr,
330  bool IsCtorOrDtorName,
331  bool WantNontrivialTypeSourceInfo,
332  bool IsClassTemplateDeductionContext,
333  ImplicitTypenameContext AllowImplicitTypename,
334  IdentifierInfo **CorrectedII) {
335  // FIXME: Consider allowing this outside C++1z mode as an extension.
336  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
337  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
338  !isClassName && !HasTrailingDot;
339 
340  // Determine where we will perform name lookup.
341  DeclContext *LookupCtx = nullptr;
342  if (ObjectTypePtr) {
343  QualType ObjectType = ObjectTypePtr.get();
344  if (ObjectType->isRecordType())
345  LookupCtx = computeDeclContext(ObjectType);
346  } else if (SS && SS->isNotEmpty()) {
347  LookupCtx = computeDeclContext(*SS, false);
348 
349  if (!LookupCtx) {
350  if (isDependentScopeSpecifier(*SS)) {
351  // C++ [temp.res]p3:
352  // A qualified-id that refers to a type and in which the
353  // nested-name-specifier depends on a template-parameter (14.6.2)
354  // shall be prefixed by the keyword typename to indicate that the
355  // qualified-id denotes a type, forming an
356  // elaborated-type-specifier (7.1.5.3).
357  //
358  // We therefore do not perform any name lookup if the result would
359  // refer to a member of an unknown specialization.
360  // In C++2a, in several contexts a 'typename' is not required. Also
361  // allow this as an extension.
362  if (AllowImplicitTypename == ImplicitTypenameContext::No &&
363  !isClassName && !IsCtorOrDtorName)
364  return nullptr;
365  bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
366  if (IsImplicitTypename) {
367  SourceLocation QualifiedLoc = SS->getRange().getBegin();
368  if (getLangOpts().CPlusPlus20)
369  Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
370  else
371  Diag(QualifiedLoc, diag::ext_implicit_typename)
372  << SS->getScopeRep() << II.getName()
373  << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
374  }
375 
376  // We know from the grammar that this name refers to a type,
377  // so build a dependent node to describe the type.
378  if (WantNontrivialTypeSourceInfo)
379  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
380  (ImplicitTypenameContext)IsImplicitTypename)
381  .get();
382 
383  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
384  QualType T =
385  CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
386  SourceLocation(), QualifierLoc, II, NameLoc);
387  return ParsedType::make(T);
388  }
389 
390  return nullptr;
391  }
392 
393  if (!LookupCtx->isDependentContext() &&
394  RequireCompleteDeclContext(*SS, LookupCtx))
395  return nullptr;
396  }
397 
398  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
399  // lookup for class-names.
400  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
401  LookupOrdinaryName;
402  LookupResult Result(*this, &II, NameLoc, Kind);
403  if (LookupCtx) {
404  // Perform "qualified" name lookup into the declaration context we
405  // computed, which is either the type of the base of a member access
406  // expression or the declaration context associated with a prior
407  // nested-name-specifier.
408  LookupQualifiedName(Result, LookupCtx);
409 
410  if (ObjectTypePtr && Result.empty()) {
411  // C++ [basic.lookup.classref]p3:
412  // If the unqualified-id is ~type-name, the type-name is looked up
413  // in the context of the entire postfix-expression. If the type T of
414  // the object expression is of a class type C, the type-name is also
415  // looked up in the scope of class C. At least one of the lookups shall
416  // find a name that refers to (possibly cv-qualified) T.
417  LookupName(Result, S);
418  }
419  } else {
420  // Perform unqualified name lookup.
421  LookupName(Result, S);
422 
423  // For unqualified lookup in a class template in MSVC mode, look into
424  // dependent base classes where the primary class template is known.
425  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
426  if (ParsedType TypeInBase =
427  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
428  return TypeInBase;
429  }
430  }
431 
432  NamedDecl *IIDecl = nullptr;
433  UsingShadowDecl *FoundUsingShadow = nullptr;
434  switch (Result.getResultKind()) {
437  if (CorrectedII) {
438  TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
439  AllowDeducedTemplate);
440  TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
441  S, SS, CCC, CTK_ErrorRecovery);
442  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
443  TemplateTy Template;
444  bool MemberOfUnknownSpecialization;
446  TemplateName.setIdentifier(NewII, NameLoc);
447  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
448  CXXScopeSpec NewSS, *NewSSPtr = SS;
449  if (SS && NNS) {
450  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
451  NewSSPtr = &NewSS;
452  }
453  if (Correction && (NNS || NewII != &II) &&
454  // Ignore a correction to a template type as the to-be-corrected
455  // identifier is not a template (typo correction for template names
456  // is handled elsewhere).
457  !(getLangOpts().CPlusPlus && NewSSPtr &&
458  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
459  Template, MemberOfUnknownSpecialization))) {
460  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
461  isClassName, HasTrailingDot, ObjectTypePtr,
462  IsCtorOrDtorName,
463  WantNontrivialTypeSourceInfo,
464  IsClassTemplateDeductionContext);
465  if (Ty) {
466  diagnoseTypo(Correction,
467  PDiag(diag::err_unknown_type_or_class_name_suggest)
468  << Result.getLookupName() << isClassName);
469  if (SS && NNS)
470  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
471  *CorrectedII = NewII;
472  return Ty;
473  }
474  }
475  }
476  // If typo correction failed or was not performed, fall through
477  [[fallthrough]];
480  Result.suppressDiagnostics();
481  return nullptr;
482 
484  // Recover from type-hiding ambiguities by hiding the type. We'll
485  // do the lookup again when looking for an object, and we can
486  // diagnose the error then. If we don't do this, then the error
487  // about hiding the type will be immediately followed by an error
488  // that only makes sense if the identifier was treated like a type.
489  if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
490  Result.suppressDiagnostics();
491  return nullptr;
492  }
493 
494  // Look to see if we have a type anywhere in the list of results.
495  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
496  Res != ResEnd; ++Res) {
497  NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
498  if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
499  RealRes) ||
500  (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
501  if (!IIDecl ||
502  // Make the selection of the recovery decl deterministic.
503  RealRes->getLocation() < IIDecl->getLocation()) {
504  IIDecl = RealRes;
505  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
506  }
507  }
508  }
509 
510  if (!IIDecl) {
511  // None of the entities we found is a type, so there is no way
512  // to even assume that the result is a type. In this case, don't
513  // complain about the ambiguity. The parser will either try to
514  // perform this lookup again (e.g., as an object name), which
515  // will produce the ambiguity, or will complain that it expected
516  // a type name.
517  Result.suppressDiagnostics();
518  return nullptr;
519  }
520 
521  // We found a type within the ambiguous lookup; diagnose the
522  // ambiguity and then return that type. This might be the right
523  // answer, or it might not be, but it suppresses any attempt to
524  // perform the name lookup again.
525  break;
526 
527  case LookupResult::Found:
528  IIDecl = Result.getFoundDecl();
529  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
530  break;
531  }
532 
533  assert(IIDecl && "Didn't find decl");
534 
535  QualType T;
536  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
537  // C++ [class.qual]p2: A lookup that would find the injected-class-name
538  // instead names the constructors of the class, except when naming a class.
539  // This is ill-formed when we're not actually forming a ctor or dtor name.
540  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
541  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
542  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
543  FoundRD->isInjectedClassName() &&
544  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
545  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
546  << &II << /*Type*/1;
547 
548  DiagnoseUseOfDecl(IIDecl, NameLoc);
549 
550  T = Context.getTypeDeclType(TD);
551  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
552  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
553  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
554  if (!HasTrailingDot)
555  T = Context.getObjCInterfaceType(IDecl);
556  FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
557  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
558  (void)DiagnoseUseOfDecl(UD, NameLoc);
559  // Recover with 'int'
560  return ParsedType::make(Context.IntTy);
561  } else if (AllowDeducedTemplate) {
562  if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
563  assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
564  TemplateName Template =
565  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
566  T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
567  false);
568  // Don't wrap in a further UsingType.
569  FoundUsingShadow = nullptr;
570  }
571  }
572 
573  if (T.isNull()) {
574  // If it's not plausibly a type, suppress diagnostics.
575  Result.suppressDiagnostics();
576  return nullptr;
577  }
578 
579  if (FoundUsingShadow)
580  T = Context.getUsingType(FoundUsingShadow, T);
581 
582  return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
583 }
584 
585 // Builds a fake NNS for the given decl context.
586 static NestedNameSpecifier *
588  for (;; DC = DC->getLookupParent()) {
589  DC = DC->getPrimaryContext();
590  auto *ND = dyn_cast<NamespaceDecl>(DC);
591  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
592  return NestedNameSpecifier::Create(Context, nullptr, ND);
593  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
594  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
595  RD->getTypeForDecl());
596  else if (isa<TranslationUnitDecl>(DC))
597  return NestedNameSpecifier::GlobalSpecifier(Context);
598  }
599  llvm_unreachable("something isn't in TU scope?");
600 }
601 
602 /// Find the parent class with dependent bases of the innermost enclosing method
603 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
604 /// up allowing unqualified dependent type names at class-level, which MSVC
605 /// correctly rejects.
606 static const CXXRecordDecl *
608  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
609  DC = DC->getPrimaryContext();
610  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
611  if (MD->getParent()->hasAnyDependentBases())
612  return MD->getParent();
613  }
614  return nullptr;
615 }
616 
618  SourceLocation NameLoc,
619  bool IsTemplateTypeArg) {
620  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
621 
622  NestedNameSpecifier *NNS = nullptr;
623  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
624  // If we weren't able to parse a default template argument, delay lookup
625  // until instantiation time by making a non-dependent DependentTypeName. We
626  // pretend we saw a NestedNameSpecifier referring to the current scope, and
627  // lookup is retried.
628  // FIXME: This hurts our diagnostic quality, since we get errors like "no
629  // type named 'Foo' in 'current_namespace'" when the user didn't write any
630  // name specifiers.
631  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
632  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
633  } else if (const CXXRecordDecl *RD =
635  // Build a DependentNameType that will perform lookup into RD at
636  // instantiation time.
637  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
638  RD->getTypeForDecl());
639 
640  // Diagnose that this identifier was undeclared, and retry the lookup during
641  // template instantiation.
642  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
643  << RD;
644  } else {
645  // This is not a situation that we should recover from.
646  return ParsedType();
647  }
648 
649  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
650 
651  // Build type location information. We synthesized the qualifier, so we have
652  // to build a fake NestedNameSpecifierLoc.
653  NestedNameSpecifierLocBuilder NNSLocBuilder;
654  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
655  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
656 
657  TypeLocBuilder Builder;
658  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
659  DepTL.setNameLoc(NameLoc);
661  DepTL.setQualifierLoc(QualifierLoc);
662  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
663 }
664 
665 /// isTagName() - This method is called *for error recovery purposes only*
666 /// to determine if the specified name is a valid tag name ("struct foo"). If
667 /// so, this returns the TST for the tag corresponding to it (TST_enum,
668 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
669 /// cases in C where the user forgot to specify the tag.
671  // Do a tag name lookup in this scope.
672  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
673  LookupName(R, S, false);
676  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
677  switch (TD->getTagKind()) {
678  case TTK_Struct: return DeclSpec::TST_struct;
680  case TTK_Union: return DeclSpec::TST_union;
681  case TTK_Class: return DeclSpec::TST_class;
682  case TTK_Enum: return DeclSpec::TST_enum;
683  }
684  }
685 
687 }
688 
689 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
690 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
691 /// then downgrade the missing typename error to a warning.
692 /// This is needed for MSVC compatibility; Example:
693 /// @code
694 /// template<class T> class A {
695 /// public:
696 /// typedef int TYPE;
697 /// };
698 /// template<class T> class B : public A<T> {
699 /// public:
700 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
701 /// };
702 /// @endcode
704  if (CurContext->isRecord()) {
706  return true;
707 
708  const Type *Ty = SS->getScopeRep()->getAsType();
709 
710  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
711  for (const auto &Base : RD->bases())
712  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
713  return true;
714  return S->isFunctionPrototypeScope();
715  }
716  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
717 }
718 
720  SourceLocation IILoc,
721  Scope *S,
722  CXXScopeSpec *SS,
723  ParsedType &SuggestedType,
724  bool IsTemplateName) {
725  // Don't report typename errors for editor placeholders.
726  if (II->isEditorPlaceholder())
727  return;
728  // We don't have anything to suggest (yet).
729  SuggestedType = nullptr;
730 
731  // There may have been a typo in the name of the type. Look up typo
732  // results, in case we have something that we can suggest.
733  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
734  /*AllowTemplates=*/IsTemplateName,
735  /*AllowNonTemplates=*/!IsTemplateName);
736  if (TypoCorrection Corrected =
737  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
738  CCC, CTK_ErrorRecovery)) {
739  // FIXME: Support error recovery for the template-name case.
740  bool CanRecover = !IsTemplateName;
741  if (Corrected.isKeyword()) {
742  // We corrected to a keyword.
743  diagnoseTypo(Corrected,
744  PDiag(IsTemplateName ? diag::err_no_template_suggest
745  : diag::err_unknown_typename_suggest)
746  << II);
747  II = Corrected.getCorrectionAsIdentifierInfo();
748  } else {
749  // We found a similarly-named type or interface; suggest that.
750  if (!SS || !SS->isSet()) {
751  diagnoseTypo(Corrected,
752  PDiag(IsTemplateName ? diag::err_no_template_suggest
753  : diag::err_unknown_typename_suggest)
754  << II, CanRecover);
755  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
756  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
757  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
758  II->getName().equals(CorrectedStr);
759  diagnoseTypo(Corrected,
760  PDiag(IsTemplateName
761  ? diag::err_no_member_template_suggest
762  : diag::err_unknown_nested_typename_suggest)
763  << II << DC << DroppedSpecifier << SS->getRange(),
764  CanRecover);
765  } else {
766  llvm_unreachable("could not have corrected a typo here");
767  }
768 
769  if (!CanRecover)
770  return;
771 
772  CXXScopeSpec tmpSS;
773  if (Corrected.getCorrectionSpecifier())
774  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
775  SourceRange(IILoc));
776  // FIXME: Support class template argument deduction here.
777  SuggestedType =
778  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
779  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
780  /*IsCtorOrDtorName=*/false,
781  /*WantNontrivialTypeSourceInfo=*/true);
782  }
783  return;
784  }
785 
786  if (getLangOpts().CPlusPlus && !IsTemplateName) {
787  // See if II is a class template that the user forgot to pass arguments to.
788  UnqualifiedId Name;
789  Name.setIdentifier(II, IILoc);
790  CXXScopeSpec EmptySS;
791  TemplateTy TemplateResult;
792  bool MemberOfUnknownSpecialization;
793  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
794  Name, nullptr, true, TemplateResult,
795  MemberOfUnknownSpecialization) == TNK_Type_template) {
796  diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
797  return;
798  }
799  }
800 
801  // FIXME: Should we move the logic that tries to recover from a missing tag
802  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
803 
804  if (!SS || (!SS->isSet() && !SS->isInvalid()))
805  Diag(IILoc, IsTemplateName ? diag::err_no_template
806  : diag::err_unknown_typename)
807  << II;
808  else if (DeclContext *DC = computeDeclContext(*SS, false))
809  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
810  : diag::err_typename_nested_not_found)
811  << II << DC << SS->getRange();
812  else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
813  SuggestedType =
814  ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
815  } else if (isDependentScopeSpecifier(*SS)) {
816  unsigned DiagID = diag::err_typename_missing;
817  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
818  DiagID = diag::ext_typename_missing;
819 
820  Diag(SS->getRange().getBegin(), DiagID)
821  << SS->getScopeRep() << II->getName()
822  << SourceRange(SS->getRange().getBegin(), IILoc)
823  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
824  SuggestedType = ActOnTypenameType(S, SourceLocation(),
825  *SS, *II, IILoc).get();
826  } else {
827  assert(SS && SS->isInvalid() &&
828  "Invalid scope specifier has already been diagnosed");
829  }
830 }
831 
832 /// Determine whether the given result set contains either a type name
833 /// or
834 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
835  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
836  NextToken.is(tok::less);
837 
838  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
839  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
840  return true;
841 
842  if (CheckTemplate && isa<TemplateDecl>(*I))
843  return true;
844  }
845 
846  return false;
847 }
848 
849 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
850  Scope *S, CXXScopeSpec &SS,
851  IdentifierInfo *&Name,
852  SourceLocation NameLoc) {
853  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
854  SemaRef.LookupParsedName(R, S, &SS);
855  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
856  StringRef FixItTagName;
857  switch (Tag->getTagKind()) {
858  case TTK_Class:
859  FixItTagName = "class ";
860  break;
861 
862  case TTK_Enum:
863  FixItTagName = "enum ";
864  break;
865 
866  case TTK_Struct:
867  FixItTagName = "struct ";
868  break;
869 
870  case TTK_Interface:
871  FixItTagName = "__interface ";
872  break;
873 
874  case TTK_Union:
875  FixItTagName = "union ";
876  break;
877  }
878 
879  StringRef TagName = FixItTagName.drop_back();
880  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
881  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
882  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
883 
884  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
885  I != IEnd; ++I)
886  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
887  << Name << TagName;
888 
889  // Replace lookup results with just the tag decl.
890  Result.clear(Sema::LookupTagName);
891  SemaRef.LookupParsedName(Result, S, &SS);
892  return true;
893  }
894 
895  return false;
896 }
897 
899  IdentifierInfo *&Name,
900  SourceLocation NameLoc,
901  const Token &NextToken,
903  DeclarationNameInfo NameInfo(Name, NameLoc);
904  ObjCMethodDecl *CurMethod = getCurMethodDecl();
905 
906  assert(NextToken.isNot(tok::coloncolon) &&
907  "parse nested name specifiers before calling ClassifyName");
908  if (getLangOpts().CPlusPlus && SS.isSet() &&
909  isCurrentClassName(*Name, S, &SS)) {
910  // Per [class.qual]p2, this names the constructors of SS, not the
911  // injected-class-name. We don't have a classification for that.
912  // There's not much point caching this result, since the parser
913  // will reject it later.
915  }
916 
917  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
918  LookupParsedName(Result, S, &SS, !CurMethod);
919 
920  if (SS.isInvalid())
921  return NameClassification::Error();
922 
923  // For unqualified lookup in a class template in MSVC mode, look into
924  // dependent base classes where the primary class template is known.
925  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
926  if (ParsedType TypeInBase =
927  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
928  return TypeInBase;
929  }
930 
931  // Perform lookup for Objective-C instance variables (including automatically
932  // synthesized instance variables), if we're in an Objective-C method.
933  // FIXME: This lookup really, really needs to be folded in to the normal
934  // unqualified lookup mechanism.
935  if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
936  DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
937  if (Ivar.isInvalid())
938  return NameClassification::Error();
939  if (Ivar.isUsable())
940  return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
941 
942  // We defer builtin creation until after ivar lookup inside ObjC methods.
943  if (Result.empty())
944  LookupBuiltin(Result);
945  }
946 
947  bool SecondTry = false;
948  bool IsFilteredTemplateName = false;
949 
950 Corrected:
951  switch (Result.getResultKind()) {
953  // If an unqualified-id is followed by a '(', then we have a function
954  // call.
955  if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
956  // In C++, this is an ADL-only call.
957  // FIXME: Reference?
958  if (getLangOpts().CPlusPlus)
959  return NameClassification::UndeclaredNonType();
960 
961  // C90 6.3.2.2:
962  // If the expression that precedes the parenthesized argument list in a
963  // function call consists solely of an identifier, and if no
964  // declaration is visible for this identifier, the identifier is
965  // implicitly declared exactly as if, in the innermost block containing
966  // the function call, the declaration
967  //
968  // extern int identifier ();
969  //
970  // appeared.
971  //
972  // We also allow this in C99 as an extension. However, this is not
973  // allowed in all language modes as functions without prototypes may not
974  // be supported.
975  if (getLangOpts().implicitFunctionsAllowed()) {
976  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
977  return NameClassification::NonType(D);
978  }
979  }
980 
981  if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
982  // In C++20 onwards, this could be an ADL-only call to a function
983  // template, and we're required to assume that this is a template name.
984  //
985  // FIXME: Find a way to still do typo correction in this case.
986  TemplateName Template =
987  Context.getAssumedTemplateName(NameInfo.getName());
988  return NameClassification::UndeclaredTemplate(Template);
989  }
990 
991  // In C, we first see whether there is a tag type by the same name, in
992  // which case it's likely that the user just forgot to write "enum",
993  // "struct", or "union".
994  if (!getLangOpts().CPlusPlus && !SecondTry &&
995  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
996  break;
997  }
998 
999  // Perform typo correction to determine if there is another name that is
1000  // close to this name.
1001  if (!SecondTry && CCC) {
1002  SecondTry = true;
1003  if (TypoCorrection Corrected =
1004  CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1005  &SS, *CCC, CTK_ErrorRecovery)) {
1006  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1007  unsigned QualifiedDiag = diag::err_no_member_suggest;
1008 
1009  NamedDecl *FirstDecl = Corrected.getFoundDecl();
1010  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1011  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1012  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1013  UnqualifiedDiag = diag::err_no_template_suggest;
1014  QualifiedDiag = diag::err_no_member_template_suggest;
1015  } else if (UnderlyingFirstDecl &&
1016  (isa<TypeDecl>(UnderlyingFirstDecl) ||
1017  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1018  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1019  UnqualifiedDiag = diag::err_unknown_typename_suggest;
1020  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1021  }
1022 
1023  if (SS.isEmpty()) {
1024  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1025  } else {// FIXME: is this even reachable? Test it.
1026  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1027  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1028  Name->getName().equals(CorrectedStr);
1029  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1030  << Name << computeDeclContext(SS, false)
1031  << DroppedSpecifier << SS.getRange());
1032  }
1033 
1034  // Update the name, so that the caller has the new name.
1035  Name = Corrected.getCorrectionAsIdentifierInfo();
1036 
1037  // Typo correction corrected to a keyword.
1038  if (Corrected.isKeyword())
1039  return Name;
1040 
1041  // Also update the LookupResult...
1042  // FIXME: This should probably go away at some point
1043  Result.clear();
1044  Result.setLookupName(Corrected.getCorrection());
1045  if (FirstDecl)
1046  Result.addDecl(FirstDecl);
1047 
1048  // If we found an Objective-C instance variable, let
1049  // LookupInObjCMethod build the appropriate expression to
1050  // reference the ivar.
1051  // FIXME: This is a gross hack.
1052  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1053  DeclResult R =
1054  LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1055  if (R.isInvalid())
1056  return NameClassification::Error();
1057  if (R.isUsable())
1058  return NameClassification::NonType(Ivar);
1059  }
1060 
1061  goto Corrected;
1062  }
1063  }
1064 
1065  // We failed to correct; just fall through and let the parser deal with it.
1066  Result.suppressDiagnostics();
1067  return NameClassification::Unknown();
1068 
1070  // We performed name lookup into the current instantiation, and there were
1071  // dependent bases, so we treat this result the same way as any other
1072  // dependent nested-name-specifier.
1073 
1074  // C++ [temp.res]p2:
1075  // A name used in a template declaration or definition and that is
1076  // dependent on a template-parameter is assumed not to name a type
1077  // unless the applicable name lookup finds a type name or the name is
1078  // qualified by the keyword typename.
1079  //
1080  // FIXME: If the next token is '<', we might want to ask the parser to
1081  // perform some heroics to see if we actually have a
1082  // template-argument-list, which would indicate a missing 'template'
1083  // keyword here.
1084  return NameClassification::DependentNonType();
1085  }
1086 
1087  case LookupResult::Found:
1090  break;
1091 
1093  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1094  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1095  /*AllowDependent=*/false)) {
1096  // C++ [temp.local]p3:
1097  // A lookup that finds an injected-class-name (10.2) can result in an
1098  // ambiguity in certain cases (for example, if it is found in more than
1099  // one base class). If all of the injected-class-names that are found
1100  // refer to specializations of the same class template, and if the name
1101  // is followed by a template-argument-list, the reference refers to the
1102  // class template itself and not a specialization thereof, and is not
1103  // ambiguous.
1104  //
1105  // This filtering can make an ambiguous result into an unambiguous one,
1106  // so try again after filtering out template names.
1107  FilterAcceptableTemplateNames(Result);
1108  if (!Result.isAmbiguous()) {
1109  IsFilteredTemplateName = true;
1110  break;
1111  }
1112  }
1113 
1114  // Diagnose the ambiguity and return an error.
1115  return NameClassification::Error();
1116  }
1117 
1118  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1119  (IsFilteredTemplateName ||
1120  hasAnyAcceptableTemplateNames(
1121  Result, /*AllowFunctionTemplates=*/true,
1122  /*AllowDependent=*/false,
1123  /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1124  getLangOpts().CPlusPlus20))) {
1125  // C++ [temp.names]p3:
1126  // After name lookup (3.4) finds that a name is a template-name or that
1127  // an operator-function-id or a literal- operator-id refers to a set of
1128  // overloaded functions any member of which is a function template if
1129  // this is followed by a <, the < is always taken as the delimiter of a
1130  // template-argument-list and never as the less-than operator.
1131  // C++2a [temp.names]p2:
1132  // A name is also considered to refer to a template if it is an
1133  // unqualified-id followed by a < and name lookup finds either one
1134  // or more functions or finds nothing.
1135  if (!IsFilteredTemplateName)
1136  FilterAcceptableTemplateNames(Result);
1137 
1138  bool IsFunctionTemplate;
1139  bool IsVarTemplate;
1140  TemplateName Template;
1141  if (Result.end() - Result.begin() > 1) {
1142  IsFunctionTemplate = true;
1143  Template = Context.getOverloadedTemplateName(Result.begin(),
1144  Result.end());
1145  } else if (!Result.empty()) {
1146  auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1147  *Result.begin(), /*AllowFunctionTemplates=*/true,
1148  /*AllowDependent=*/false));
1149  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1150  IsVarTemplate = isa<VarTemplateDecl>(TD);
1151 
1152  UsingShadowDecl *FoundUsingShadow =
1153  dyn_cast<UsingShadowDecl>(*Result.begin());
1154  assert(!FoundUsingShadow ||
1155  TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1156  Template =
1157  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1158  if (SS.isNotEmpty())
1159  Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1160  /*TemplateKeyword=*/false,
1161  Template);
1162  } else {
1163  // All results were non-template functions. This is a function template
1164  // name.
1165  IsFunctionTemplate = true;
1166  Template = Context.getAssumedTemplateName(NameInfo.getName());
1167  }
1168 
1169  if (IsFunctionTemplate) {
1170  // Function templates always go through overload resolution, at which
1171  // point we'll perform the various checks (e.g., accessibility) we need
1172  // to based on which function we selected.
1173  Result.suppressDiagnostics();
1174 
1175  return NameClassification::FunctionTemplate(Template);
1176  }
1177 
1178  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1179  : NameClassification::TypeTemplate(Template);
1180  }
1181 
1182  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1183  QualType T = Context.getTypeDeclType(Type);
1184  if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1185  T = Context.getUsingType(USD, T);
1186  return buildNamedType(*this, &SS, T, NameLoc);
1187  };
1188 
1189  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1190  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1191  DiagnoseUseOfDecl(Type, NameLoc);
1192  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1193  return BuildTypeFor(Type, *Result.begin());
1194  }
1195 
1196  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1197  if (!Class) {
1198  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1199  if (ObjCCompatibleAliasDecl *Alias =
1200  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1201  Class = Alias->getClassInterface();
1202  }
1203 
1204  if (Class) {
1205  DiagnoseUseOfDecl(Class, NameLoc);
1206 
1207  if (NextToken.is(tok::period)) {
1208  // Interface. <something> is parsed as a property reference expression.
1209  // Just return "unknown" as a fall-through for now.
1210  Result.suppressDiagnostics();
1211  return NameClassification::Unknown();
1212  }
1213 
1214  QualType T = Context.getObjCInterfaceType(Class);
1215  return ParsedType::make(T);
1216  }
1217 
1218  if (isa<ConceptDecl>(FirstDecl))
1219  return NameClassification::Concept(
1220  TemplateName(cast<TemplateDecl>(FirstDecl)));
1221 
1222  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1223  (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1224  return NameClassification::Error();
1225  }
1226 
1227  // We can have a type template here if we're classifying a template argument.
1228  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1229  !isa<VarTemplateDecl>(FirstDecl))
1230  return NameClassification::TypeTemplate(
1231  TemplateName(cast<TemplateDecl>(FirstDecl)));
1232 
1233  // Check for a tag type hidden by a non-type decl in a few cases where it
1234  // seems likely a type is wanted instead of the non-type that was found.
1235  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1236  if ((NextToken.is(tok::identifier) ||
1237  (NextIsOp &&
1238  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1239  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1240  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1241  DiagnoseUseOfDecl(Type, NameLoc);
1242  return BuildTypeFor(Type, *Result.begin());
1243  }
1244 
1245  // If we already know which single declaration is referenced, just annotate
1246  // that declaration directly. Defer resolving even non-overloaded class
1247  // member accesses, as we need to defer certain access checks until we know
1248  // the context.
1249  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1250  if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1251  return NameClassification::NonType(Result.getRepresentativeDecl());
1252 
1253  // Otherwise, this is an overload set that we will need to resolve later.
1254  Result.suppressDiagnostics();
1255  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1256  Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1257  Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1258  Result.begin(), Result.end()));
1259 }
1260 
1261 ExprResult
1263  SourceLocation NameLoc) {
1264  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1265  CXXScopeSpec SS;
1266  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1267  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1268 }
1269 
1270 ExprResult
1272  IdentifierInfo *Name,
1273  SourceLocation NameLoc,
1274  bool IsAddressOfOperand) {
1275  DeclarationNameInfo NameInfo(Name, NameLoc);
1276  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1277  NameInfo, IsAddressOfOperand,
1278  /*TemplateArgs=*/nullptr);
1279 }
1280 
1282  NamedDecl *Found,
1283  SourceLocation NameLoc,
1284  const Token &NextToken) {
1285  if (getCurMethodDecl() && SS.isEmpty())
1286  if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1287  return BuildIvarRefExpr(S, NameLoc, Ivar);
1288 
1289  // Reconstruct the lookup result.
1290  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1291  Result.addDecl(Found);
1292  Result.resolveKind();
1293 
1294  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1295  return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1296 }
1297 
1299  // For an implicit class member access, transform the result into a member
1300  // access expression if necessary.
1301  auto *ULE = cast<UnresolvedLookupExpr>(E);
1302  if ((*ULE->decls_begin())->isCXXClassMember()) {
1303  CXXScopeSpec SS;
1304  SS.Adopt(ULE->getQualifierLoc());
1305 
1306  // Reconstruct the lookup result.
1307  LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1308  LookupOrdinaryName);
1309  Result.setNamingClass(ULE->getNamingClass());
1310  for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1311  Result.addDecl(*I, I.getAccess());
1312  Result.resolveKind();
1313  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1314  nullptr, S);
1315  }
1316 
1317  // Otherwise, this is already in the form we needed, and no further checks
1318  // are necessary.
1319  return ULE;
1320 }
1321 
1324  auto *TD = Name.getAsTemplateDecl();
1325  if (!TD)
1326  return TemplateNameKindForDiagnostics::DependentTemplate;
1327  if (isa<ClassTemplateDecl>(TD))
1328  return TemplateNameKindForDiagnostics::ClassTemplate;
1329  if (isa<FunctionTemplateDecl>(TD))
1330  return TemplateNameKindForDiagnostics::FunctionTemplate;
1331  if (isa<VarTemplateDecl>(TD))
1332  return TemplateNameKindForDiagnostics::VarTemplate;
1333  if (isa<TypeAliasTemplateDecl>(TD))
1334  return TemplateNameKindForDiagnostics::AliasTemplate;
1335  if (isa<TemplateTemplateParmDecl>(TD))
1336  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1337  if (isa<ConceptDecl>(TD))
1338  return TemplateNameKindForDiagnostics::Concept;
1339  return TemplateNameKindForDiagnostics::DependentTemplate;
1340 }
1341 
1343  assert(DC->getLexicalParent() == CurContext &&
1344  "The next DeclContext should be lexically contained in the current one.");
1345  CurContext = DC;
1346  S->setEntity(DC);
1347 }
1348 
1350  assert(CurContext && "DeclContext imbalance!");
1351 
1352  CurContext = CurContext->getLexicalParent();
1353  assert(CurContext && "Popped translation unit!");
1354 }
1355 
1357  Decl *D) {
1358  // Unlike PushDeclContext, the context to which we return is not necessarily
1359  // the containing DC of TD, because the new context will be some pre-existing
1360  // TagDecl definition instead of a fresh one.
1361  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1362  CurContext = cast<TagDecl>(D)->getDefinition();
1363  assert(CurContext && "skipping definition of undefined tag");
1364  // Start lookups from the parent of the current context; we don't want to look
1365  // into the pre-existing complete definition.
1366  S->setEntity(CurContext->getLookupParent());
1367  return Result;
1368 }
1369 
1371  CurContext = static_cast<decltype(CurContext)>(Context);
1372 }
1373 
1374 /// EnterDeclaratorContext - Used when we must lookup names in the context
1375 /// of a declarator's nested name specifier.
1376 ///
1378  // C++0x [basic.lookup.unqual]p13:
1379  // A name used in the definition of a static data member of class
1380  // X (after the qualified-id of the static member) is looked up as
1381  // if the name was used in a member function of X.
1382  // C++0x [basic.lookup.unqual]p14:
1383  // If a variable member of a namespace is defined outside of the
1384  // scope of its namespace then any name used in the definition of
1385  // the variable member (after the declarator-id) is looked up as
1386  // if the definition of the variable member occurred in its
1387  // namespace.
1388  // Both of these imply that we should push a scope whose context
1389  // is the semantic context of the declaration. We can't use
1390  // PushDeclContext here because that context is not necessarily
1391  // lexically contained in the current context. Fortunately,
1392  // the containing scope should have the appropriate information.
1393 
1394  assert(!S->getEntity() && "scope already has entity");
1395 
1396 #ifndef NDEBUG
1397  Scope *Ancestor = S->getParent();
1398  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1399  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1400 #endif
1401 
1402  CurContext = DC;
1403  S->setEntity(DC);
1404 
1405  if (S->getParent()->isTemplateParamScope()) {
1406  // Also set the corresponding entities for all immediately-enclosing
1407  // template parameter scopes.
1408  EnterTemplatedContext(S->getParent(), DC);
1409  }
1410 }
1411 
1413  assert(S->getEntity() == CurContext && "Context imbalance!");
1414 
1415  // Switch back to the lexical context. The safety of this is
1416  // enforced by an assert in EnterDeclaratorContext.
1417  Scope *Ancestor = S->getParent();
1418  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1419  CurContext = Ancestor->getEntity();
1420 
1421  // We don't need to do anything with the scope, which is going to
1422  // disappear.
1423 }
1424 
1426  assert(S->isTemplateParamScope() &&
1427  "expected to be initializing a template parameter scope");
1428 
1429  // C++20 [temp.local]p7:
1430  // In the definition of a member of a class template that appears outside
1431  // of the class template definition, the name of a member of the class
1432  // template hides the name of a template-parameter of any enclosing class
1433  // templates (but not a template-parameter of the member if the member is a
1434  // class or function template).
1435  // C++20 [temp.local]p9:
1436  // In the definition of a class template or in the definition of a member
1437  // of such a template that appears outside of the template definition, for
1438  // each non-dependent base class (13.8.2.1), if the name of the base class
1439  // or the name of a member of the base class is the same as the name of a
1440  // template-parameter, the base class name or member name hides the
1441  // template-parameter name (6.4.10).
1442  //
1443  // This means that a template parameter scope should be searched immediately
1444  // after searching the DeclContext for which it is a template parameter
1445  // scope. For example, for
1446  // template<typename T> template<typename U> template<typename V>
1447  // void N::A<T>::B<U>::f(...)
1448  // we search V then B<U> (and base classes) then U then A<T> (and base
1449  // classes) then T then N then ::.
1450  unsigned ScopeDepth = getTemplateDepth(S);
1451  for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1452  DeclContext *SearchDCAfterScope = DC;
1453  for (; DC; DC = DC->getLookupParent()) {
1454  if (const TemplateParameterList *TPL =
1455  cast<Decl>(DC)->getDescribedTemplateParams()) {
1456  unsigned DCDepth = TPL->getDepth() + 1;
1457  if (DCDepth > ScopeDepth)
1458  continue;
1459  if (ScopeDepth == DCDepth)
1460  SearchDCAfterScope = DC = DC->getLookupParent();
1461  break;
1462  }
1463  }
1464  S->setLookupEntity(SearchDCAfterScope);
1465  }
1466 }
1467 
1469  // We assume that the caller has already called
1470  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1471  FunctionDecl *FD = D->getAsFunction();
1472  if (!FD)
1473  return;
1474 
1475  // Same implementation as PushDeclContext, but enters the context
1476  // from the lexical parent, rather than the top-level class.
1477  assert(CurContext == FD->getLexicalParent() &&
1478  "The next DeclContext should be lexically contained in the current one.");
1479  CurContext = FD;
1480  S->setEntity(CurContext);
1481 
1482  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1483  ParmVarDecl *Param = FD->getParamDecl(P);
1484  // If the parameter has an identifier, then add it to the scope
1485  if (Param->getIdentifier()) {
1486  S->AddDecl(Param);
1487  IdResolver.AddDecl(Param);
1488  }
1489  }
1490 }
1491 
1493  // Same implementation as PopDeclContext, but returns to the lexical parent,
1494  // rather than the top-level class.
1495  assert(CurContext && "DeclContext imbalance!");
1496  CurContext = CurContext->getLexicalParent();
1497  assert(CurContext && "Popped translation unit!");
1498 }
1499 
1500 /// Determine whether overloading is allowed for a new function
1501 /// declaration considering prior declarations of the same name.
1502 ///
1503 /// This routine determines whether overloading is possible, not
1504 /// whether a new declaration actually overloads a previous one.
1505 /// It will return true in C++ (where overloads are alway permitted)
1506 /// or, as a C extension, when either the new declaration or a
1507 /// previous one is declared with the 'overloadable' attribute.
1509  ASTContext &Context,
1510  const FunctionDecl *New) {
1511  if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1512  return true;
1513 
1514  // Multiversion function declarations are not overloads in the
1515  // usual sense of that term, but lookup will report that an
1516  // overload set was found if more than one multiversion function
1517  // declaration is present for the same name. It is therefore
1518  // inadequate to assume that some prior declaration(s) had
1519  // the overloadable attribute; checking is required. Since one
1520  // declaration is permitted to omit the attribute, it is necessary
1521  // to check at least two; hence the 'any_of' check below. Note that
1522  // the overloadable attribute is implicitly added to declarations
1523  // that were required to have it but did not.
1524  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1525  return llvm::any_of(Previous, [](const NamedDecl *ND) {
1526  return ND->hasAttr<OverloadableAttr>();
1527  });
1528  } else if (Previous.getResultKind() == LookupResult::Found)
1529  return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1530 
1531  return false;
1532 }
1533 
1534 /// Add this decl to the scope shadowed decl chains.
1535 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1536  // Move up the scope chain until we find the nearest enclosing
1537  // non-transparent context. The declaration will be introduced into this
1538  // scope.
1539  while (S->getEntity() && S->getEntity()->isTransparentContext())
1540  S = S->getParent();
1541 
1542  // Add scoped declarations into their context, so that they can be
1543  // found later. Declarations without a context won't be inserted
1544  // into any context.
1545  if (AddToContext)
1546  CurContext->addDecl(D);
1547 
1548  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1549  // are function-local declarations.
1550  if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1551  return;
1552 
1553  // Template instantiations should also not be pushed into scope.
1554  if (isa<FunctionDecl>(D) &&
1555  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1556  return;
1557 
1558  // If this replaces anything in the current scope,
1559  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1560  IEnd = IdResolver.end();
1561  for (; I != IEnd; ++I) {
1562  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1563  S->RemoveDecl(*I);
1564  IdResolver.RemoveDecl(*I);
1565 
1566  // Should only need to replace one decl.
1567  break;
1568  }
1569  }
1570 
1571  S->AddDecl(D);
1572 
1573  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1574  // Implicitly-generated labels may end up getting generated in an order that
1575  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1576  // the label at the appropriate place in the identifier chain.
1577  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1578  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1579  if (IDC == CurContext) {
1580  if (!S->isDeclScope(*I))
1581  continue;
1582  } else if (IDC->Encloses(CurContext))
1583  break;
1584  }
1585 
1586  IdResolver.InsertDeclAfter(I, D);
1587  } else {
1588  IdResolver.AddDecl(D);
1589  }
1590  warnOnReservedIdentifier(D);
1591 }
1592 
1594  bool AllowInlineNamespace) {
1595  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1596 }
1597 
1599  DeclContext *TargetDC = DC->getPrimaryContext();
1600  do {
1601  if (DeclContext *ScopeDC = S->getEntity())
1602  if (ScopeDC->getPrimaryContext() == TargetDC)
1603  return S;
1604  } while ((S = S->getParent()));
1605 
1606  return nullptr;
1607 }
1608 
1610  DeclContext*,
1611  ASTContext&);
1612 
1613 /// Filters out lookup results that don't fall within the given scope
1614 /// as determined by isDeclInScope.
1616  bool ConsiderLinkage,
1617  bool AllowInlineNamespace) {
1619  while (F.hasNext()) {
1620  NamedDecl *D = F.next();
1621 
1622  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1623  continue;
1624 
1625  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1626  continue;
1627 
1628  F.erase();
1629  }
1630 
1631  F.done();
1632 }
1633 
1634 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1635 /// have compatible owning modules.
1637  // [module.interface]p7:
1638  // A declaration is attached to a module as follows:
1639  // - If the declaration is a non-dependent friend declaration that nominates a
1640  // function with a declarator-id that is a qualified-id or template-id or that
1641  // nominates a class other than with an elaborated-type-specifier with neither
1642  // a nested-name-specifier nor a simple-template-id, it is attached to the
1643  // module to which the friend is attached ([basic.link]).
1644  if (New->getFriendObjectKind() &&
1647  makeMergedDefinitionVisible(New);
1648  return false;
1649  }
1650 
1651  Module *NewM = New->getOwningModule();
1652  Module *OldM = Old->getOwningModule();
1653 
1654  if (NewM && NewM->isPrivateModule())
1655  NewM = NewM->Parent;
1656  if (OldM && OldM->isPrivateModule())
1657  OldM = OldM->Parent;
1658 
1659  if (NewM == OldM)
1660  return false;
1661 
1662  // Partitions are part of the module, but a partition could import another
1663  // module, so verify that the PMIs agree.
1664  if (NewM && OldM &&
1665  (NewM->isModulePartition() || OldM->isModulePartition()) &&
1668  return false;
1669 
1670  bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1671  bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1672  if (NewIsModuleInterface || OldIsModuleInterface) {
1673  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1674  // if a declaration of D [...] appears in the purview of a module, all
1675  // other such declarations shall appear in the purview of the same module
1676  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1677  << New
1678  << NewIsModuleInterface
1679  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1680  << OldIsModuleInterface
1681  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1682  Diag(Old->getLocation(), diag::note_previous_declaration);
1683  New->setInvalidDecl();
1684  return true;
1685  }
1686 
1687  return false;
1688 }
1689 
1690 // [module.interface]p6:
1691 // A redeclaration of an entity X is implicitly exported if X was introduced by
1692 // an exported declaration; otherwise it shall not be exported.
1694  // [module.interface]p1:
1695  // An export-declaration shall inhabit a namespace scope.
1696  //
1697  // So it is meaningless to talk about redeclaration which is not at namespace
1698  // scope.
1699  if (!New->getLexicalDeclContext()
1701  ->isFileContext() ||
1702  !Old->getLexicalDeclContext()
1704  ->isFileContext())
1705  return false;
1706 
1707  bool IsNewExported = New->isInExportDeclContext();
1708  bool IsOldExported = Old->isInExportDeclContext();
1709 
1710  // It should be irrevelant if both of them are not exported.
1711  if (!IsNewExported && !IsOldExported)
1712  return false;
1713 
1714  if (IsOldExported)
1715  return false;
1716 
1717  assert(IsNewExported);
1718 
1719  auto Lk = Old->getFormalLinkage();
1720  int S = 0;
1721  if (Lk == Linkage::InternalLinkage)
1722  S = 1;
1723  else if (Lk == Linkage::ModuleLinkage)
1724  S = 2;
1725  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1726  Diag(Old->getLocation(), diag::note_previous_declaration);
1727  return true;
1728 }
1729 
1730 // A wrapper function for checking the semantic restrictions of
1731 // a redeclaration within a module.
1733  if (CheckRedeclarationModuleOwnership(New, Old))
1734  return true;
1735 
1736  if (CheckRedeclarationExported(New, Old))
1737  return true;
1738 
1739  return false;
1740 }
1741 
1742 // Check the redefinition in C++20 Modules.
1743 //
1744 // [basic.def.odr]p14:
1745 // For any definable item D with definitions in multiple translation units,
1746 // - if D is a non-inline non-templated function or variable, or
1747 // - if the definitions in different translation units do not satisfy the
1748 // following requirements,
1749 // the program is ill-formed; a diagnostic is required only if the definable
1750 // item is attached to a named module and a prior definition is reachable at
1751 // the point where a later definition occurs.
1752 // - Each such definition shall not be attached to a named module
1753 // ([module.unit]).
1754 // - Each such definition shall consist of the same sequence of tokens, ...
1755 // ...
1756 //
1757 // Return true if the redefinition is not allowed. Return false otherwise.
1759  const NamedDecl *Old) const {
1760  assert(getASTContext().isSameEntity(New, Old) &&
1761  "New and Old are not the same definition, we should diagnostic it "
1762  "immediately instead of checking it.");
1763  assert(const_cast<Sema *>(this)->isReachable(New) &&
1764  const_cast<Sema *>(this)->isReachable(Old) &&
1765  "We shouldn't see unreachable definitions here.");
1766 
1767  Module *NewM = New->getOwningModule();
1768  Module *OldM = Old->getOwningModule();
1769 
1770  // We only checks for named modules here. The header like modules is skipped.
1771  // FIXME: This is not right if we import the header like modules in the module
1772  // purview.
1773  //
1774  // For example, assuming "header.h" provides definition for `D`.
1775  // ```C++
1776  // //--- M.cppm
1777  // export module M;
1778  // import "header.h"; // or #include "header.h" but import it by clang modules
1779  // actually.
1780  //
1781  // //--- Use.cpp
1782  // import M;
1783  // import "header.h"; // or uses clang modules.
1784  // ```
1785  //
1786  // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1787  // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1788  // reject it. But the current implementation couldn't detect the case since we
1789  // don't record the information about the importee modules.
1790  //
1791  // But this might not be painful in practice. Since the design of C++20 Named
1792  // Modules suggests us to use headers in global module fragment instead of
1793  // module purview.
1794  if (NewM && NewM->isHeaderLikeModule())
1795  NewM = nullptr;
1796  if (OldM && OldM->isHeaderLikeModule())
1797  OldM = nullptr;
1798 
1799  if (!NewM && !OldM)
1800  return true;
1801 
1802  // [basic.def.odr]p14.3
1803  // Each such definition shall not be attached to a named module
1804  // ([module.unit]).
1805  if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1806  return true;
1807 
1808  // Then New and Old lives in the same TU if their share one same module unit.
1809  if (NewM)
1810  NewM = NewM->getTopLevelModule();
1811  if (OldM)
1812  OldM = OldM->getTopLevelModule();
1813  return OldM == NewM;
1814 }
1815 
1816 static bool isUsingDecl(NamedDecl *D) {
1817  return isa<UsingShadowDecl>(D) ||
1818  isa<UnresolvedUsingTypenameDecl>(D) ||
1819  isa<UnresolvedUsingValueDecl>(D);
1820 }
1821 
1822 /// Removes using shadow declarations from the lookup results.
1825  while (F.hasNext())
1826  if (isUsingDecl(F.next()))
1827  F.erase();
1828 
1829  F.done();
1830 }
1831 
1832 /// Check for this common pattern:
1833 /// @code
1834 /// class S {
1835 /// S(const S&); // DO NOT IMPLEMENT
1836 /// void operator=(const S&); // DO NOT IMPLEMENT
1837 /// };
1838 /// @endcode
1840  // FIXME: Should check for private access too but access is set after we get
1841  // the decl here.
1843  return false;
1844 
1845  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1846  return CD->isCopyConstructor();
1847  return D->isCopyAssignmentOperator();
1848 }
1849 
1850 // We need this to handle
1851 //
1852 // typedef struct {
1853 // void *foo() { return 0; }
1854 // } A;
1855 //
1856 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1857 // for example. If 'A', foo will have external linkage. If we have '*A',
1858 // foo will have no linkage. Since we can't know until we get to the end
1859 // of the typedef, this function finds out if D might have non-external linkage.
1860 // Callers should verify at the end of the TU if it D has external linkage or
1861 // not.
1862 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1863  const DeclContext *DC = D->getDeclContext();
1864  while (!DC->isTranslationUnit()) {
1865  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1866  if (!RD->hasNameForLinkage())
1867  return true;
1868  }
1869  DC = DC->getParent();
1870  }
1871 
1872  return !D->isExternallyVisible();
1873 }
1874 
1875 // FIXME: This needs to be refactored; some other isInMainFile users want
1876 // these semantics.
1877 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1878  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1879  return false;
1880  return S.SourceMgr.isInMainFile(Loc);
1881 }
1882 
1884  assert(D);
1885 
1886  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1887  return false;
1888 
1889  // Ignore all entities declared within templates, and out-of-line definitions
1890  // of members of class templates.
1891  if (D->getDeclContext()->isDependentContext() ||
1893  return false;
1894 
1895  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1896  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1897  return false;
1898  // A non-out-of-line declaration of a member specialization was implicitly
1899  // instantiated; it's the out-of-line declaration that we're interested in.
1900  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1901  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1902  return false;
1903 
1904  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1905  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1906  return false;
1907  } else {
1908  // 'static inline' functions are defined in headers; don't warn.
1909  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1910  return false;
1911  }
1912 
1913  if (FD->doesThisDeclarationHaveABody() &&
1914  Context.DeclMustBeEmitted(FD))
1915  return false;
1916  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1917  // Constants and utility variables are defined in headers with internal
1918  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1919  // like "inline".)
1920  if (!isMainFileLoc(*this, VD->getLocation()))
1921  return false;
1922 
1923  if (Context.DeclMustBeEmitted(VD))
1924  return false;
1925 
1926  if (VD->isStaticDataMember() &&
1927  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1928  return false;
1929  if (VD->isStaticDataMember() &&
1930  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1931  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1932  return false;
1933 
1934  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1935  return false;
1936  } else {
1937  return false;
1938  }
1939 
1940  // Only warn for unused decls internal to the translation unit.
1941  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1942  // for inline functions defined in the main source file, for instance.
1943  return mightHaveNonExternalLinkage(D);
1944 }
1945 
1947  if (!D)
1948  return;
1949 
1950  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1951  const FunctionDecl *First = FD->getFirstDecl();
1952  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1953  return; // First should already be in the vector.
1954  }
1955 
1956  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1957  const VarDecl *First = VD->getFirstDecl();
1958  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1959  return; // First should already be in the vector.
1960  }
1961 
1962  if (ShouldWarnIfUnusedFileScopedDecl(D))
1963  UnusedFileScopedDecls.push_back(D);
1964 }
1965 
1966 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1967  if (D->isInvalidDecl())
1968  return false;
1969 
1970  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1971  // For a decomposition declaration, warn if none of the bindings are
1972  // referenced, instead of if the variable itself is referenced (which
1973  // it is, by the bindings' expressions).
1974  for (auto *BD : DD->bindings())
1975  if (BD->isReferenced())
1976  return false;
1977  } else if (!D->getDeclName()) {
1978  return false;
1979  } else if (D->isReferenced() || D->isUsed()) {
1980  return false;
1981  }
1982 
1983  if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1984  return false;
1985 
1986  if (isa<LabelDecl>(D))
1987  return true;
1988 
1989  // Except for labels, we only care about unused decls that are local to
1990  // functions.
1991  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1992  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1993  // For dependent types, the diagnostic is deferred.
1994  WithinFunction =
1995  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1996  if (!WithinFunction)
1997  return false;
1998 
1999  if (isa<TypedefNameDecl>(D))
2000  return true;
2001 
2002  // White-list anything that isn't a local variable.
2003  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2004  return false;
2005 
2006  // Types of valid local variables should be complete, so this should succeed.
2007  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2008 
2009  const Expr *Init = VD->getInit();
2010  if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2011  Init = Cleanups->getSubExpr();
2012 
2013  const auto *Ty = VD->getType().getTypePtr();
2014 
2015  // Only look at the outermost level of typedef.
2016  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2017  // Allow anything marked with __attribute__((unused)).
2018  if (TT->getDecl()->hasAttr<UnusedAttr>())
2019  return false;
2020  }
2021 
2022  // Warn for reference variables whose initializtion performs lifetime
2023  // extension.
2024  if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2025  if (MTE->getExtendingDecl()) {
2026  Ty = VD->getType().getNonReferenceType().getTypePtr();
2027  Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2028  }
2029  }
2030 
2031  // If we failed to complete the type for some reason, or if the type is
2032  // dependent, don't diagnose the variable.
2033  if (Ty->isIncompleteType() || Ty->isDependentType())
2034  return false;
2035 
2036  // Look at the element type to ensure that the warning behaviour is
2037  // consistent for both scalars and arrays.
2038  Ty = Ty->getBaseElementTypeUnsafe();
2039 
2040  if (const TagType *TT = Ty->getAs<TagType>()) {
2041  const TagDecl *Tag = TT->getDecl();
2042  if (Tag->hasAttr<UnusedAttr>())
2043  return false;
2044 
2045  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2046  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2047  return false;
2048 
2049  if (Init) {
2050  const CXXConstructExpr *Construct =
2051  dyn_cast<CXXConstructExpr>(Init);
2052  if (Construct && !Construct->isElidable()) {
2053  CXXConstructorDecl *CD = Construct->getConstructor();
2054  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2055  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2056  return false;
2057  }
2058 
2059  // Suppress the warning if we don't know how this is constructed, and
2060  // it could possibly be non-trivial constructor.
2061  if (Init->isTypeDependent()) {
2062  for (const CXXConstructorDecl *Ctor : RD->ctors())
2063  if (!Ctor->isTrivial())
2064  return false;
2065  }
2066 
2067  // Suppress the warning if the constructor is unresolved because
2068  // its arguments are dependent.
2069  if (isa<CXXUnresolvedConstructExpr>(Init))
2070  return false;
2071  }
2072  }
2073  }
2074 
2075  // TODO: __attribute__((unused)) templates?
2076  }
2077 
2078  return true;
2079 }
2080 
2081 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2082  FixItHint &Hint) {
2083  if (isa<LabelDecl>(D)) {
2085  D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2086  true);
2087  if (AfterColon.isInvalid())
2088  return;
2089  Hint = FixItHint::CreateRemoval(
2090  CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2091  }
2092 }
2093 
2095  DiagnoseUnusedNestedTypedefs(
2096  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2097 }
2098 
2100  DiagReceiverTy DiagReceiver) {
2101  if (D->getTypeForDecl()->isDependentType())
2102  return;
2103 
2104  for (auto *TmpD : D->decls()) {
2105  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2106  DiagnoseUnusedDecl(T, DiagReceiver);
2107  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2108  DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2109  }
2110 }
2111 
2113  DiagnoseUnusedDecl(
2114  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2115 }
2116 
2117 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2118 /// unless they are marked attr(unused).
2119 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2120  if (!ShouldDiagnoseUnusedDecl(D))
2121  return;
2122 
2123  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2124  // typedefs can be referenced later on, so the diagnostics are emitted
2125  // at end-of-translation-unit.
2126  UnusedLocalTypedefNameCandidates.insert(TD);
2127  return;
2128  }
2129 
2130  FixItHint Hint;
2131  GenerateFixForUnusedDecl(D, Context, Hint);
2132 
2133  unsigned DiagID;
2134  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2135  DiagID = diag::warn_unused_exception_param;
2136  else if (isa<LabelDecl>(D))
2137  DiagID = diag::warn_unused_label;
2138  else
2139  DiagID = diag::warn_unused_variable;
2140 
2141  DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
2142 }
2143 
2145  DiagReceiverTy DiagReceiver) {
2146  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2147  // it's not really unused.
2148  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2149  VD->hasAttr<CleanupAttr>())
2150  return;
2151 
2152  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2153 
2154  if (Ty->isReferenceType() || Ty->isDependentType())
2155  return;
2156 
2157  if (const TagType *TT = Ty->getAs<TagType>()) {
2158  const TagDecl *Tag = TT->getDecl();
2159  if (Tag->hasAttr<UnusedAttr>())
2160  return;
2161  // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2162  // mimic gcc's behavior.
2163  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2164  if (!RD->hasAttr<WarnUnusedAttr>())
2165  return;
2166  }
2167  }
2168 
2169  // Don't warn about __block Objective-C pointer variables, as they might
2170  // be assigned in the block but not used elsewhere for the purpose of lifetime
2171  // extension.
2172  if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2173  return;
2174 
2175  // Don't warn about Objective-C pointer variables with precise lifetime
2176  // semantics; they can be used to ensure ARC releases the object at a known
2177  // time, which may mean assignment but no other references.
2178  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2179  return;
2180 
2181  auto iter = RefsMinusAssignments.find(VD);
2182  if (iter == RefsMinusAssignments.end())
2183  return;
2184 
2185  assert(iter->getSecond() >= 0 &&
2186  "Found a negative number of references to a VarDecl");
2187  if (iter->getSecond() != 0)
2188  return;
2189  unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2190  : diag::warn_unused_but_set_variable;
2191  DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2192 }
2193 
2194 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2195  Sema::DiagReceiverTy DiagReceiver) {
2196  // Verify that we have no forward references left. If so, there was a goto
2197  // or address of a label taken, but no definition of it. Label fwd
2198  // definitions are indicated with a null substmt which is also not a resolved
2199  // MS inline assembly label name.
2200  bool Diagnose = false;
2201  if (L->isMSAsmLabel())
2202  Diagnose = !L->isResolvedMSAsmLabel();
2203  else
2204  Diagnose = L->getStmt() == nullptr;
2205  if (Diagnose)
2206  DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2207  << L);
2208 }
2209 
2211  S->applyNRVO();
2212 
2213  if (S->decl_empty()) return;
2214  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2215  "Scope shouldn't contain decls!");
2216 
2217  /// We visit the decls in non-deterministic order, but we want diagnostics
2218  /// emitted in deterministic order. Collect any diagnostic that may be emitted
2219  /// and sort the diagnostics before emitting them, after we visited all decls.
2220  struct LocAndDiag {
2221  SourceLocation Loc;
2222  Optional<SourceLocation> PreviousDeclLoc;
2223  PartialDiagnostic PD;
2224  };
2225  SmallVector<LocAndDiag, 16> DeclDiags;
2226  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2227  DeclDiags.push_back(LocAndDiag{Loc, None, std::move(PD)});
2228  };
2229  auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2230  SourceLocation PreviousDeclLoc,
2231  PartialDiagnostic PD) {
2232  DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2233  };
2234 
2235  for (auto *TmpD : S->decls()) {
2236  assert(TmpD && "This decl didn't get pushed??");
2237 
2238  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2239  NamedDecl *D = cast<NamedDecl>(TmpD);
2240 
2241  // Diagnose unused variables in this scope.
2242  if (!S->hasUnrecoverableErrorOccurred()) {
2243  DiagnoseUnusedDecl(D, addDiag);
2244  if (const auto *RD = dyn_cast<RecordDecl>(D))
2245  DiagnoseUnusedNestedTypedefs(RD, addDiag);
2246  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2247  DiagnoseUnusedButSetDecl(VD, addDiag);
2248  RefsMinusAssignments.erase(VD);
2249  }
2250  }
2251 
2252  if (!D->getDeclName()) continue;
2253 
2254  // If this was a forward reference to a label, verify it was defined.
2255  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2256  CheckPoppedLabel(LD, *this, addDiag);
2257 
2258  // Remove this name from our lexical scope, and warn on it if we haven't
2259  // already.
2260  IdResolver.RemoveDecl(D);
2261  auto ShadowI = ShadowingDecls.find(D);
2262  if (ShadowI != ShadowingDecls.end()) {
2263  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2264  addDiagWithPrev(D->getLocation(), FD->getLocation(),
2265  PDiag(diag::warn_ctor_parm_shadows_field)
2266  << D << FD << FD->getParent());
2267  }
2268  ShadowingDecls.erase(ShadowI);
2269  }
2270  }
2271 
2272  llvm::sort(DeclDiags,
2273  [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2274  // The particular order for diagnostics is not important, as long
2275  // as the order is deterministic. Using the raw location is going
2276  // to generally be in source order unless there are macro
2277  // expansions involved.
2278  return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2279  });
2280  for (const LocAndDiag &D : DeclDiags) {
2281  Diag(D.Loc, D.PD);
2282  if (D.PreviousDeclLoc)
2283  Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2284  }
2285 }
2286 
2287 /// Look for an Objective-C class in the translation unit.
2288 ///
2289 /// \param Id The name of the Objective-C class we're looking for. If
2290 /// typo-correction fixes this name, the Id will be updated
2291 /// to the fixed name.
2292 ///
2293 /// \param IdLoc The location of the name in the translation unit.
2294 ///
2295 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2296 /// if there is no class with the given name.
2297 ///
2298 /// \returns The declaration of the named Objective-C class, or NULL if the
2299 /// class could not be found.
2301  SourceLocation IdLoc,
2302  bool DoTypoCorrection) {
2303  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2304  // creation from this context.
2305  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2306 
2307  if (!IDecl && DoTypoCorrection) {
2308  // Perform typo correction at the given location, but only if we
2309  // find an Objective-C class name.
2311  if (TypoCorrection C =
2312  CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2313  TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2314  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2315  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2316  Id = IDecl->getIdentifier();
2317  }
2318  }
2319  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2320  // This routine must always return a class definition, if any.
2321  if (Def && Def->getDefinition())
2322  Def = Def->getDefinition();
2323  return Def;
2324 }
2325 
2326 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2327 /// from S, where a non-field would be declared. This routine copes
2328 /// with the difference between C and C++ scoping rules in structs and
2329 /// unions. For example, the following code is well-formed in C but
2330 /// ill-formed in C++:
2331 /// @code
2332 /// struct S6 {
2333 /// enum { BAR } e;
2334 /// };
2335 ///
2336 /// void test_S6() {
2337 /// struct S6 a;
2338 /// a.e = BAR;
2339 /// }
2340 /// @endcode
2341 /// For the declaration of BAR, this routine will return a different
2342 /// scope. The scope S will be the scope of the unnamed enumeration
2343 /// within S6. In C++, this routine will return the scope associated
2344 /// with S6, because the enumeration's scope is a transparent
2345 /// context but structures can contain non-field names. In C, this
2346 /// routine will return the translation unit scope, since the
2347 /// enumeration's scope is a transparent context and structures cannot
2348 /// contain non-field names.
2350  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2351  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2352  (S->isClassScope() && !getLangOpts().CPlusPlus))
2353  S = S->getParent();
2354  return S;
2355 }
2356 
2357 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2359  switch (Error) {
2360  case ASTContext::GE_None:
2361  return "";
2363  return BuiltinInfo.getHeaderName(ID);
2365  return "stdio.h";
2367  return "setjmp.h";
2369  return "ucontext.h";
2370  }
2371  llvm_unreachable("unhandled error kind");
2372 }
2373 
2375  unsigned ID, SourceLocation Loc) {
2377 
2378  if (getLangOpts().CPlusPlus) {
2379  LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2380  Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2381  CLinkageDecl->setImplicit();
2382  Parent->addDecl(CLinkageDecl);
2383  Parent = CLinkageDecl;
2384  }
2385 
2386  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2387  /*TInfo=*/nullptr, SC_Extern,
2388  getCurFPFeatures().isFPConstrained(),
2389  false, Type->isFunctionProtoType());
2390  New->setImplicit();
2391  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2392 
2393  // Create Decl objects for each parameter, adding them to the
2394  // FunctionDecl.
2395  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2397  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2399  Context, New, SourceLocation(), SourceLocation(), nullptr,
2400  FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2401  parm->setScopeInfo(0, i);
2402  Params.push_back(parm);
2403  }
2404  New->setParams(Params);
2405  }
2406 
2407  AddKnownFunctionAttributes(New);
2408  return New;
2409 }
2410 
2411 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2412 /// file scope. lazily create a decl for it. ForRedeclaration is true
2413 /// if we're creating this built-in in anticipation of redeclaring the
2414 /// built-in.
2416  Scope *S, bool ForRedeclaration,
2417  SourceLocation Loc) {
2418  LookupNecessaryTypesForBuiltin(S, ID);
2419 
2421  QualType R = Context.GetBuiltinType(ID, Error);
2422  if (Error) {
2423  if (!ForRedeclaration)
2424  return nullptr;
2425 
2426  // If we have a builtin without an associated type we should not emit a
2427  // warning when we were not able to find a type for it.
2429  Context.BuiltinInfo.allowTypeMismatch(ID))
2430  return nullptr;
2431 
2432  // If we could not find a type for setjmp it is because the jmp_buf type was
2433  // not defined prior to the setjmp declaration.
2435  Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2436  << Context.BuiltinInfo.getName(ID);
2437  return nullptr;
2438  }
2439 
2440  // Generally, we emit a warning that the declaration requires the
2441  // appropriate header.
2442  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2443  << getHeaderName(Context.BuiltinInfo, ID, Error)
2444  << Context.BuiltinInfo.getName(ID);
2445  return nullptr;
2446  }
2447 
2448  if (!ForRedeclaration &&
2451  Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2452  : diag::ext_implicit_lib_function_decl)
2453  << Context.BuiltinInfo.getName(ID) << R;
2454  if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2455  Diag(Loc, diag::note_include_header_or_declare)
2456  << Header << Context.BuiltinInfo.getName(ID);
2457  }
2458 
2459  if (R.isNull())
2460  return nullptr;
2461 
2462  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2463  RegisterLocallyScopedExternCDecl(New, S);
2464 
2465  // TUScope is the translation-unit scope to insert this function into.
2466  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2467  // relate Scopes to DeclContexts, and probably eliminate CurContext
2468  // entirely, but we're not there yet.
2469  DeclContext *SavedContext = CurContext;
2470  CurContext = New->getDeclContext();
2471  PushOnScopeChains(New, TUScope);
2472  CurContext = SavedContext;
2473  return New;
2474 }
2475 
2476 /// Typedef declarations don't have linkage, but they still denote the same
2477 /// entity if their types are the same.
2478 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2479 /// isSameEntity.
2483  // This is only interesting when modules are enabled.
2484  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2485  return;
2486 
2487  // Empty sets are uninteresting.
2488  if (Previous.empty())
2489  return;
2490 
2491  LookupResult::Filter Filter = Previous.makeFilter();
2492  while (Filter.hasNext()) {
2493  NamedDecl *Old = Filter.next();
2494 
2495  // Non-hidden declarations are never ignored.
2496  if (S.isVisible(Old))
2497  continue;
2498 
2499  // Declarations of the same entity are not ignored, even if they have
2500  // different linkages.
2501  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2502  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2503  Decl->getUnderlyingType()))
2504  continue;
2505 
2506  // If both declarations give a tag declaration a typedef name for linkage
2507  // purposes, then they declare the same entity.
2508  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2509  Decl->getAnonDeclWithTypedefName())
2510  continue;
2511  }
2512 
2513  Filter.erase();
2514  }
2515 
2516  Filter.done();
2517 }
2518 
2520  QualType OldType;
2521  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2522  OldType = OldTypedef->getUnderlyingType();
2523  else
2524  OldType = Context.getTypeDeclType(Old);
2525  QualType NewType = New->getUnderlyingType();
2526 
2527  if (NewType->isVariablyModifiedType()) {
2528  // Must not redefine a typedef with a variably-modified type.
2529  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2530  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2531  << Kind << NewType;
2532  if (Old->getLocation().isValid())
2533  notePreviousDefinition(Old, New->getLocation());
2534  New->setInvalidDecl();
2535  return true;
2536  }
2537 
2538  if (OldType != NewType &&
2539  !OldType->isDependentType() &&
2540  !NewType->isDependentType() &&
2541  !Context.hasSameType(OldType, NewType)) {
2542  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2543  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2544  << Kind << NewType << OldType;
2545  if (Old->getLocation().isValid())
2546  notePreviousDefinition(Old, New->getLocation());
2547  New->setInvalidDecl();
2548  return true;
2549  }
2550  return false;
2551 }
2552 
2553 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2554 /// same name and scope as a previous declaration 'Old'. Figure out
2555 /// how to resolve this situation, merging decls or emitting
2556 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2557 ///
2559  LookupResult &OldDecls) {
2560  // If the new decl is known invalid already, don't bother doing any
2561  // merging checks.
2562  if (New->isInvalidDecl()) return;
2563 
2564  // Allow multiple definitions for ObjC built-in typedefs.
2565  // FIXME: Verify the underlying types are equivalent!
2566  if (getLangOpts().ObjC) {
2567  const IdentifierInfo *TypeID = New->getIdentifier();
2568  switch (TypeID->getLength()) {
2569  default: break;
2570  case 2:
2571  {
2572  if (!TypeID->isStr("id"))
2573  break;
2574  QualType T = New->getUnderlyingType();
2575  if (!T->isPointerType())
2576  break;
2577  if (!T->isVoidPointerType()) {
2578  QualType PT = T->castAs<PointerType>()->getPointeeType();
2579  if (!PT->isStructureType())
2580  break;
2581  }
2582  Context.setObjCIdRedefinitionType(T);
2583  // Install the built-in type for 'id', ignoring the current definition.
2584  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2585  return;
2586  }
2587  case 5:
2588  if (!TypeID->isStr("Class"))
2589  break;
2591  // Install the built-in type for 'Class', ignoring the current definition.
2592  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2593  return;
2594  case 3:
2595  if (!TypeID->isStr("SEL"))
2596  break;
2598  // Install the built-in type for 'SEL', ignoring the current definition.
2599  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2600  return;
2601  }
2602  // Fall through - the typedef name was not a builtin type.
2603  }
2604 
2605  // Verify the old decl was also a type.
2606  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2607  if (!Old) {
2608  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2609  << New->getDeclName();
2610 
2611  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2612  if (OldD->getLocation().isValid())
2613  notePreviousDefinition(OldD, New->getLocation());
2614 
2615  return New->setInvalidDecl();
2616  }
2617 
2618  // If the old declaration is invalid, just give up here.
2619  if (Old->isInvalidDecl())
2620  return New->setInvalidDecl();
2621 
2622  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2623  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2624  auto *NewTag = New->getAnonDeclWithTypedefName();
2625  NamedDecl *Hidden = nullptr;
2626  if (OldTag && NewTag &&
2627  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2628  !hasVisibleDefinition(OldTag, &Hidden)) {
2629  // There is a definition of this tag, but it is not visible. Use it
2630  // instead of our tag.
2631  New->setTypeForDecl(OldTD->getTypeForDecl());
2632  if (OldTD->isModed())
2633  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2634  OldTD->getUnderlyingType());
2635  else
2636  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2637 
2638  // Make the old tag definition visible.
2639  makeMergedDefinitionVisible(Hidden);
2640 
2641  // If this was an unscoped enumeration, yank all of its enumerators
2642  // out of the scope.
2643  if (isa<EnumDecl>(NewTag)) {
2644  Scope *EnumScope = getNonFieldDeclScope(S);
2645  for (auto *D : NewTag->decls()) {
2646  auto *ED = cast<EnumConstantDecl>(D);
2647  assert(EnumScope->isDeclScope(ED));
2648  EnumScope->RemoveDecl(ED);
2649  IdResolver.RemoveDecl(ED);
2650  ED->getLexicalDeclContext()->removeDecl(ED);
2651  }
2652  }
2653  }
2654  }
2655 
2656  // If the typedef types are not identical, reject them in all languages and
2657  // with any extensions enabled.
2658  if (isIncompatibleTypedef(Old, New))
2659  return;
2660 
2661  // The types match. Link up the redeclaration chain and merge attributes if
2662  // the old declaration was a typedef.
2663  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2664  New->setPreviousDecl(Typedef);
2665  mergeDeclAttributes(New, Old);
2666  }
2667 
2668  if (getLangOpts().MicrosoftExt)
2669  return;
2670 
2671  if (getLangOpts().CPlusPlus) {
2672  // C++ [dcl.typedef]p2:
2673  // In a given non-class scope, a typedef specifier can be used to
2674  // redefine the name of any type declared in that scope to refer
2675  // to the type to which it already refers.
2676  if (!isa<CXXRecordDecl>(CurContext))
2677  return;
2678 
2679  // C++0x [dcl.typedef]p4:
2680  // In a given class scope, a typedef specifier can be used to redefine
2681  // any class-name declared in that scope that is not also a typedef-name
2682  // to refer to the type to which it already refers.
2683  //
2684  // This wording came in via DR424, which was a correction to the
2685  // wording in DR56, which accidentally banned code like:
2686  //
2687  // struct S {
2688  // typedef struct A { } A;
2689  // };
2690  //
2691  // in the C++03 standard. We implement the C++0x semantics, which
2692  // allow the above but disallow
2693  //
2694  // struct S {
2695  // typedef int I;
2696  // typedef int I;
2697  // };
2698  //
2699  // since that was the intent of DR56.
2700  if (!isa<TypedefNameDecl>(Old))
2701  return;
2702 
2703  Diag(New->getLocation(), diag::err_redefinition)
2704  << New->getDeclName();
2705  notePreviousDefinition(Old, New->getLocation());
2706  return New->setInvalidDecl();
2707  }
2708 
2709  // Modules always permit redefinition of typedefs, as does C11.
2710  if (getLangOpts().Modules || getLangOpts().C11)
2711  return;
2712 
2713  // If we have a redefinition of a typedef in C, emit a warning. This warning
2714  // is normally mapped to an error, but can be controlled with
2715  // -Wtypedef-redefinition. If either the original or the redefinition is
2716  // in a system header, don't emit this for compatibility with GCC.
2717  if (getDiagnostics().getSuppressSystemWarnings() &&
2718  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2719  (Old->isImplicit() ||
2720  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2721  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2722  return;
2723 
2724  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2725  << New->getDeclName();
2726  notePreviousDefinition(Old, New->getLocation());
2727 }
2728 
2729 /// DeclhasAttr - returns true if decl Declaration already has the target
2730 /// attribute.
2731 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2732  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2733  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2734  for (const auto *i : D->attrs())
2735  if (i->getKind() == A->getKind()) {
2736  if (Ann) {
2737  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2738  return true;
2739  continue;
2740  }
2741  // FIXME: Don't hardcode this check
2742  if (OA && isa<OwnershipAttr>(i))
2743  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2744  return true;
2745  }
2746 
2747  return false;
2748 }
2749 
2751  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2752  return VD->isThisDeclarationADefinition();
2753  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2754  return TD->isCompleteDefinition() || TD->isBeingDefined();
2755  return true;
2756 }
2757 
2758 /// Merge alignment attributes from \p Old to \p New, taking into account the
2759 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2760 ///
2761 /// \return \c true if any attributes were added to \p New.
2762 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2763  // Look for alignas attributes on Old, and pick out whichever attribute
2764  // specifies the strictest alignment requirement.
2765  AlignedAttr *OldAlignasAttr = nullptr;
2766  AlignedAttr *OldStrictestAlignAttr = nullptr;
2767  unsigned OldAlign = 0;
2768  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2769  // FIXME: We have no way of representing inherited dependent alignments
2770  // in a case like:
2771  // template<int A, int B> struct alignas(A) X;
2772  // template<int A, int B> struct alignas(B) X {};
2773  // For now, we just ignore any alignas attributes which are not on the
2774  // definition in such a case.
2775  if (I->isAlignmentDependent())
2776  return false;
2777 
2778  if (I->isAlignas())
2779  OldAlignasAttr = I;
2780 
2781  unsigned Align = I->getAlignment(S.Context);
2782  if (Align > OldAlign) {
2783  OldAlign = Align;
2784  OldStrictestAlignAttr = I;
2785  }
2786  }
2787 
2788  // Look for alignas attributes on New.
2789  AlignedAttr *NewAlignasAttr = nullptr;
2790  unsigned NewAlign = 0;
2791  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2792  if (I->isAlignmentDependent())
2793  return false;
2794 
2795  if (I->isAlignas())
2796  NewAlignasAttr = I;
2797 
2798  unsigned Align = I->getAlignment(S.Context);
2799  if (Align > NewAlign)
2800  NewAlign = Align;
2801  }
2802 
2803  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2804  // Both declarations have 'alignas' attributes. We require them to match.
2805  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2806  // fall short. (If two declarations both have alignas, they must both match
2807  // every definition, and so must match each other if there is a definition.)
2808 
2809  // If either declaration only contains 'alignas(0)' specifiers, then it
2810  // specifies the natural alignment for the type.
2811  if (OldAlign == 0 || NewAlign == 0) {
2812  QualType Ty;
2813  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2814  Ty = VD->getType();
2815  else
2816  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2817 
2818  if (OldAlign == 0)
2819  OldAlign = S.Context.getTypeAlign(Ty);
2820  if (NewAlign == 0)
2821  NewAlign = S.Context.getTypeAlign(Ty);
2822  }
2823 
2824  if (OldAlign != NewAlign) {
2825  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2827  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2828  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2829  }
2830  }
2831 
2832  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2833  // C++11 [dcl.align]p6:
2834  // if any declaration of an entity has an alignment-specifier,
2835  // every defining declaration of that entity shall specify an
2836  // equivalent alignment.
2837  // C11 6.7.5/7:
2838  // If the definition of an object does not have an alignment
2839  // specifier, any other declaration of that object shall also
2840  // have no alignment specifier.
2841  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2842  << OldAlignasAttr;
2843  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2844  << OldAlignasAttr;
2845  }
2846 
2847  bool AnyAdded = false;
2848 
2849  // Ensure we have an attribute representing the strictest alignment.
2850  if (OldAlign > NewAlign) {
2851  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2852  Clone->setInherited(true);
2853  New->addAttr(Clone);
2854  AnyAdded = true;
2855  }
2856 
2857  // Ensure we have an alignas attribute if the old declaration had one.
2858  if (OldAlignasAttr && !NewAlignasAttr &&
2859  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2860  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2861  Clone->setInherited(true);
2862  New->addAttr(Clone);
2863  AnyAdded = true;
2864  }
2865 
2866  return AnyAdded;
2867 }
2868 
2869 #define WANT_DECL_MERGE_LOGIC
2870 #include "clang/Sema/AttrParsedAttrImpl.inc"
2871 #undef WANT_DECL_MERGE_LOGIC
2872 
2873 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2874  const InheritableAttr *Attr,
2876  // Diagnose any mutual exclusions between the attribute that we want to add
2877  // and attributes that already exist on the declaration.
2878  if (!DiagnoseMutualExclusions(S, D, Attr))
2879  return false;
2880 
2881  // This function copies an attribute Attr from a previous declaration to the
2882  // new declaration D if the new declaration doesn't itself have that attribute
2883  // yet or if that attribute allows duplicates.
2884  // If you're adding a new attribute that requires logic different from
2885  // "use explicit attribute on decl if present, else use attribute from
2886  // previous decl", for example if the attribute needs to be consistent
2887  // between redeclarations, you need to call a custom merge function here.
2888  InheritableAttr *NewAttr = nullptr;
2889  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2890  NewAttr = S.mergeAvailabilityAttr(
2891  D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2892  AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2893  AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2894  AA->getPriority());
2895  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2896  NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2897  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2898  NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2899  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2900  NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2901  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2902  NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2903  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2904  NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2905  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2906  NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2907  FA->getFirstArg());
2908  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2909  NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2910  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2911  NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2912  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2913  NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2914  IA->getInheritanceModel());
2915  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2916  NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2917  &S.Context.Idents.get(AA->getSpelling()));
2918  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2919  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2920  isa<CUDAGlobalAttr>(Attr))) {
2921  // CUDA target attributes are part of function signature for
2922  // overloading purposes and must not be merged.
2923  return false;
2924  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2925  NewAttr = S.mergeMinSizeAttr(D, *MA);
2926  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2927  NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2928  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2929  NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2930  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2931  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2932  else if (isa<AlignedAttr>(Attr))
2933  // AlignedAttrs are handled separately, because we need to handle all
2934  // such attributes on a declaration at the same time.
2935  NewAttr = nullptr;
2936  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2937  (AMK == Sema::AMK_Override ||
2940  NewAttr = nullptr;
2941  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2942  NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2943  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2944  NewAttr = S.mergeImportModuleAttr(D, *IMA);
2945  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2946  NewAttr = S.mergeImportNameAttr(D, *INA);
2947  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2948  NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2949  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2950  NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2951  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2952  NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2953  else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2954  NewAttr =
2955  S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2956  else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2957  NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2958  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2959  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2960 
2961  if (NewAttr) {
2962  NewAttr->setInherited(true);
2963  D->addAttr(NewAttr);
2964  if (isa<MSInheritanceAttr>(NewAttr))
2965  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2966  return true;
2967  }
2968 
2969  return false;
2970 }
2971 
2972 static const NamedDecl *getDefinition(const Decl *D) {
2973  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2974  return TD->getDefinition();
2975  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2976  const VarDecl *Def = VD->getDefinition();
2977  if (Def)
2978  return Def;
2979  return VD->getActingDefinition();
2980  }
2981  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2982  const FunctionDecl *Def = nullptr;
2983  if (FD->isDefined(Def, true))
2984  return Def;
2985  }
2986  return nullptr;
2987 }
2988 
2989 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2990  for (const auto *Attribute : D->attrs())
2991  if (Attribute->getKind() == Kind)
2992  return true;
2993  return false;
2994 }
2995 
2996 /// checkNewAttributesAfterDef - If we already have a definition, check that
2997 /// there are no new attributes in this declaration.
2998 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2999  if (!New->hasAttrs())
3000  return;
3001 
3002  const NamedDecl *Def = getDefinition(Old);
3003  if (!Def || Def == New)
3004  return;
3005 
3006  AttrVec &NewAttributes = New->getAttrs();
3007  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3008  const Attr *NewAttribute = NewAttributes[I];
3009 
3010  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3011  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3012  Sema::SkipBodyInfo SkipBody;
3013  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3014 
3015  // If we're skipping this definition, drop the "alias" attribute.
3016  if (SkipBody.ShouldSkip) {
3017  NewAttributes.erase(NewAttributes.begin() + I);
3018  --E;
3019  continue;
3020  }
3021  } else {
3022  VarDecl *VD = cast<VarDecl>(New);
3023  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3025  ? diag::err_alias_after_tentative
3026  : diag::err_redefinition;
3027  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3028  if (Diag == diag::err_redefinition)
3029  S.notePreviousDefinition(Def, VD->getLocation());
3030  else
3031  S.Diag(Def->getLocation(), diag::note_previous_definition);
3032  VD->setInvalidDecl();
3033  }
3034  ++I;
3035  continue;
3036  }
3037 
3038  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3039  // Tentative definitions are only interesting for the alias check above.
3040  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3041  ++I;
3042  continue;
3043  }
3044  }
3045 
3046  if (hasAttribute(Def, NewAttribute->getKind())) {
3047  ++I;
3048  continue; // regular attr merging will take care of validating this.
3049  }
3050 
3051  if (isa<C11NoReturnAttr>(NewAttribute)) {
3052  // C's _Noreturn is allowed to be added to a function after it is defined.
3053  ++I;
3054  continue;
3055  } else if (isa<UuidAttr>(NewAttribute)) {
3056  // msvc will allow a subsequent definition to add an uuid to a class
3057  ++I;
3058  continue;
3059  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3060  if (AA->isAlignas()) {
3061  // C++11 [dcl.align]p6:
3062  // if any declaration of an entity has an alignment-specifier,
3063  // every defining declaration of that entity shall specify an
3064  // equivalent alignment.
3065  // C11 6.7.5/7:
3066  // If the definition of an object does not have an alignment
3067  // specifier, any other declaration of that object shall also
3068  // have no alignment specifier.
3069  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3070  << AA;
3071  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3072  << AA;
3073  NewAttributes.erase(NewAttributes.begin() + I);
3074  --E;
3075  continue;
3076  }
3077  } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3078  // If there is a C definition followed by a redeclaration with this
3079  // attribute then there are two different definitions. In C++, prefer the
3080  // standard diagnostics.
3081  if (!S.getLangOpts().CPlusPlus) {
3082  S.Diag(NewAttribute->getLocation(),
3083  diag::err_loader_uninitialized_redeclaration);
3084  S.Diag(Def->getLocation(), diag::note_previous_definition);
3085  NewAttributes.erase(NewAttributes.begin() + I);
3086  --E;
3087  continue;
3088  }
3089  } else if (isa<SelectAnyAttr>(NewAttribute) &&
3090  cast<VarDecl>(New)->isInline() &&
3091  !cast<VarDecl>(New)->isInlineSpecified()) {
3092  // Don't warn about applying selectany to implicitly inline variables.
3093  // Older compilers and language modes would require the use of selectany
3094  // to make such variables inline, and it would have no effect if we
3095  // honored it.
3096  ++I;
3097  continue;
3098  } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3099  // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3100  // declarations after definitions.
3101  ++I;
3102  continue;
3103  }
3104 
3105  S.Diag(NewAttribute->getLocation(),
3106  diag::warn_attribute_precede_definition);
3107  S.Diag(Def->getLocation(), diag::note_previous_definition);
3108  NewAttributes.erase(NewAttributes.begin() + I);
3109  --E;
3110  }
3111 }
3112 
3113 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3114  const ConstInitAttr *CIAttr,
3115  bool AttrBeforeInit) {
3116  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3117 
3118  // Figure out a good way to write this specifier on the old declaration.
3119  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3120  // enough of the attribute list spelling information to extract that without
3121  // heroics.
3122  std::string SuitableSpelling;
3123  if (S.getLangOpts().CPlusPlus20)
3124  SuitableSpelling = std::string(
3125  S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3126  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3127  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3128  InsertLoc, {tok::l_square, tok::l_square,
3129  S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3130  S.PP.getIdentifierInfo("require_constant_initialization"),
3131  tok::r_square, tok::r_square}));
3132  if (SuitableSpelling.empty())
3133  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3134  InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3135  S.PP.getIdentifierInfo("require_constant_initialization"),
3136  tok::r_paren, tok::r_paren}));
3137  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3138  SuitableSpelling = "constinit";
3139  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3140  SuitableSpelling = "[[clang::require_constant_initialization]]";
3141  if (SuitableSpelling.empty())
3142  SuitableSpelling = "__attribute__((require_constant_initialization))";
3143  SuitableSpelling += " ";
3144 
3145  if (AttrBeforeInit) {
3146  // extern constinit int a;
3147  // int a = 0; // error (missing 'constinit'), accepted as extension
3148  assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3149  S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3150  << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3151  S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3152  } else {
3153  // int a = 0;
3154  // constinit extern int a; // error (missing 'constinit')
3155  S.Diag(CIAttr->getLocation(),
3156  CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3157  : diag::warn_require_const_init_added_too_late)
3158  << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3159  S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3160  << CIAttr->isConstinit()
3161  << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3162  }
3163 }
3164 
3165 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3167  AvailabilityMergeKind AMK) {
3168  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3169  UsedAttr *NewAttr = OldAttr->clone(Context);
3170  NewAttr->setInherited(true);
3171  New->addAttr(NewAttr);
3172  }
3173  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3174  RetainAttr *NewAttr = OldAttr->clone(Context);
3175  NewAttr->setInherited(true);
3176  New->addAttr(NewAttr);
3177  }
3178 
3179  if (!Old->hasAttrs() && !New->hasAttrs())
3180  return;
3181 
3182  // [dcl.constinit]p1:
3183  // If the [constinit] specifier is applied to any declaration of a
3184  // variable, it shall be applied to the initializing declaration.
3185  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3186  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3187  if (bool(OldConstInit) != bool(NewConstInit)) {
3188  const auto *OldVD = cast<VarDecl>(Old);
3189  auto *NewVD = cast<VarDecl>(New);
3190 
3191  // Find the initializing declaration. Note that we might not have linked
3192  // the new declaration into the redeclaration chain yet.
3193  const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3194  if (!InitDecl &&
3195  (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3196  InitDecl = NewVD;
3197 
3198  if (InitDecl == NewVD) {
3199  // This is the initializing declaration. If it would inherit 'constinit',
3200  // that's ill-formed. (Note that we do not apply this to the attribute
3201  // form).
3202  if (OldConstInit && OldConstInit->isConstinit())
3203  diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3204  /*AttrBeforeInit=*/true);
3205  } else if (NewConstInit) {
3206  // This is the first time we've been told that this declaration should
3207  // have a constant initializer. If we already saw the initializing
3208  // declaration, this is too late.
3209  if (InitDecl && InitDecl != NewVD) {
3210  diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3211  /*AttrBeforeInit=*/false);
3212  NewVD->dropAttr<ConstInitAttr>();
3213  }
3214  }
3215  }
3216 
3217  // Attributes declared post-definition are currently ignored.
3218  checkNewAttributesAfterDef(*this, New, Old);
3219 
3220  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3221  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3222  if (!OldA->isEquivalent(NewA)) {
3223  // This redeclaration changes __asm__ label.
3224  Diag(New->getLocation(), diag::err_different_asm_label);
3225  Diag(OldA->getLocation(), diag::note_previous_declaration);
3226  }
3227  } else if (Old->isUsed()) {
3228  // This redeclaration adds an __asm__ label to a declaration that has
3229  // already been ODR-used.
3230  Diag(New->getLocation(), diag::err_late_asm_label_name)
3231  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3232  }
3233  }
3234 
3235  // Re-declaration cannot add abi_tag's.
3236  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3237  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3238  for (const auto &NewTag : NewAbiTagAttr->tags()) {
3239  if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3240  Diag(NewAbiTagAttr->getLocation(),
3241  diag::err_new_abi_tag_on_redeclaration)
3242  << NewTag;
3243  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3244  }
3245  }
3246  } else {
3247  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3248  Diag(Old->getLocation(), diag::note_previous_declaration);
3249  }
3250  }
3251 
3252  // This redeclaration adds a section attribute.
3253  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3254  if (auto *VD = dyn_cast<VarDecl>(New)) {
3255  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3256  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3257  Diag(Old->getLocation(), diag::note_previous_declaration);
3258  }
3259  }
3260  }
3261 
3262  // Redeclaration adds code-seg attribute.
3263  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3264  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3265  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3266  Diag(New->getLocation(), diag::warn_mismatched_section)
3267  << 0 /*codeseg*/;
3268  Diag(Old->getLocation(), diag::note_previous_declaration);
3269  }
3270 
3271  if (!Old->hasAttrs())
3272  return;
3273 
3274  bool foundAny = New->hasAttrs();
3275 
3276  // Ensure that any moving of objects within the allocated map is done before
3277  // we process them.
3278  if (!foundAny) New->setAttrs(AttrVec());
3279 
3280  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3281  // Ignore deprecated/unavailable/availability attributes if requested.
3282  AvailabilityMergeKind LocalAMK = AMK_None;
3283  if (isa<DeprecatedAttr>(I) ||
3284  isa<UnavailableAttr>(I) ||
3285  isa<AvailabilityAttr>(I)) {
3286  switch (AMK) {
3287  case AMK_None:
3288  continue;
3289 
3290  case AMK_Redeclaration:
3291  case AMK_Override:
3292  case AMK_ProtocolImplementation:
3293  case AMK_OptionalProtocolImplementation:
3294  LocalAMK = AMK;
3295  break;
3296  }
3297  }
3298 
3299  // Already handled.
3300  if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3301  continue;
3302 
3303  if (mergeDeclAttribute(*this, New, I, LocalAMK))
3304  foundAny = true;
3305  }
3306 
3307  if (mergeAlignedAttrs(*this, New, Old))
3308  foundAny = true;
3309 
3310  if (!foundAny) New->dropAttrs();
3311 }
3312 
3313 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3314 /// to the new one.
3316  const ParmVarDecl *oldDecl,
3317  Sema &S) {
3318  // C++11 [dcl.attr.depend]p2:
3319  // The first declaration of a function shall specify the
3320  // carries_dependency attribute for its declarator-id if any declaration
3321  // of the function specifies the carries_dependency attribute.
3322  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3323  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3324  S.Diag(CDA->getLocation(),
3325  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3326  // Find the first declaration of the parameter.
3327  // FIXME: Should we build redeclaration chains for function parameters?
3328  const FunctionDecl *FirstFD =
3329  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3330  const ParmVarDecl *FirstVD =
3331  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3332  S.Diag(FirstVD->getLocation(),
3333  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3334  }
3335 
3336  if (!oldDecl->hasAttrs())
3337  return;
3338 
3339  bool foundAny = newDecl->hasAttrs();
3340 
3341  // Ensure that any moving of objects within the allocated map is
3342  // done before we process them.
3343  if (!foundAny) newDecl->setAttrs(AttrVec());
3344 
3345  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3346  if (!DeclHasAttr(newDecl, I)) {
3347  InheritableAttr *newAttr =
3348  cast<InheritableParamAttr>(I->clone(S.Context));
3349  newAttr->setInherited(true);
3350  newDecl->addAttr(newAttr);
3351  foundAny = true;
3352  }
3353  }
3354 
3355  if (!foundAny) newDecl->dropAttrs();
3356 }
3357 
3359  const ASTContext &Ctx) {
3360 
3361  auto NoSizeInfo = [&Ctx](QualType Ty) {
3362  if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3363  return true;
3364  if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3365  return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3366  return false;
3367  };
3368 
3369  // `type[]` is equivalent to `type *` and `type[*]`.
3370  if (NoSizeInfo(Old) && NoSizeInfo(New))
3371  return true;
3372 
3373  // Don't try to compare VLA sizes, unless one of them has the star modifier.
3374  if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3375  const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3376  const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3377  if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3378  (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3379  return false;
3380  return true;
3381  }
3382 
3383  // Only compare size, ignore Size modifiers and CVR.
3384  if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3385  return Ctx.getAsConstantArrayType(Old)->getSize() ==
3386  Ctx.getAsConstantArrayType(New)->getSize();
3387  }
3388 
3389  // Don't try to compare dependent sized array
3391  return true;
3392  }
3393 
3394  return Old == New;
3395 }
3396 
3397 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3398  const ParmVarDecl *OldParam,
3399  Sema &S) {
3400  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3401  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3402  if (*Oldnullability != *Newnullability) {
3403  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3405  *Newnullability,
3407  != 0))
3409  *Oldnullability,
3411  != 0));
3412  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3413  }
3414  } else {
3415  QualType NewT = NewParam->getType();
3416  NewT = S.Context.getAttributedType(
3417  AttributedType::getNullabilityAttrKind(*Oldnullability),
3418  NewT, NewT);
3419  NewParam->setType(NewT);
3420  }
3421  }
3422  const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3423  const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3424  if (OldParamDT && NewParamDT &&
3425  OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3426  QualType OldParamOT = OldParamDT->getOriginalType();
3427  QualType NewParamOT = NewParamDT->getOriginalType();
3428  if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3429  S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3430  << NewParam << NewParamOT;
3431  S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3432  << OldParamOT;
3433  }
3434  }
3435 }
3436 
3437 namespace {
3438 
3439 /// Used in MergeFunctionDecl to keep track of function parameters in
3440 /// C.
3441 struct GNUCompatibleParamWarning {
3442  ParmVarDecl *OldParm;
3443  ParmVarDecl *NewParm;
3444  QualType PromotedType;
3445 };
3446 
3447 } // end anonymous namespace
3448 
3449 // Determine whether the previous declaration was a definition, implicit
3450 // declaration, or a declaration.
3451 template <typename T>
3452 static std::pair<diag::kind, SourceLocation>
3453 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3454  diag::kind PrevDiag;
3455  SourceLocation OldLocation = Old->getLocation();
3456  if (Old->isThisDeclarationADefinition())
3457  PrevDiag = diag::note_previous_definition;
3458  else if (Old->isImplicit()) {
3459  PrevDiag = diag::note_previous_implicit_declaration;
3460  if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3461  if (FD->getBuiltinID())
3462  PrevDiag = diag::note_previous_builtin_declaration;
3463  }
3464  if (OldLocation.isInvalid())
3465  OldLocation = New->getLocation();
3466  } else
3467  PrevDiag = diag::note_previous_declaration;
3468  return std::make_pair(PrevDiag, OldLocation);
3469 }
3470 
3471 /// canRedefineFunction - checks if a function can be redefined. Currently,
3472 /// only extern inline functions can be redefined, and even then only in
3473 /// GNU89 mode.
3474 static bool canRedefineFunction(const FunctionDecl *FD,
3475  const LangOptions& LangOpts) {
3476  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3477  !LangOpts.CPlusPlus &&
3478  FD->isInlineSpecified() &&
3479  FD->getStorageClass() == SC_Extern);
3480 }
3481 
3483  const AttributedType *AT = T->getAs<AttributedType>();
3484  while (AT && !AT->isCallingConv())
3485  AT = AT->getModifiedType()->getAs<AttributedType>();
3486  return AT;
3487 }
3488 
3489 template <typename T>
3490 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3491  const DeclContext *DC = Old->getDeclContext();
3492  if (DC->isRecord())
3493  return false;
3494 
3495  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3496  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3497  return true;
3498  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3499  return true;
3500  return false;
3501 }
3502 
3503 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3504 static bool isExternC(VarTemplateDecl *) { return false; }
3505 static bool isExternC(FunctionTemplateDecl *) { return false; }
3506 
3507 /// Check whether a redeclaration of an entity introduced by a
3508 /// using-declaration is valid, given that we know it's not an overload
3509 /// (nor a hidden tag declaration).
3510 template<typename ExpectedDecl>
3512  ExpectedDecl *New) {
3513  // C++11 [basic.scope.declarative]p4:
3514  // Given a set of declarations in a single declarative region, each of
3515  // which specifies the same unqualified name,
3516  // -- they shall all refer to the same entity, or all refer to functions
3517  // and function templates; or
3518  // -- exactly one declaration shall declare a class name or enumeration
3519  // name that is not a typedef name and the other declarations shall all
3520  // refer to the same variable or enumerator, or all refer to functions
3521  // and function templates; in this case the class name or enumeration
3522  // name is hidden (3.3.10).
3523 
3524  // C++11 [namespace.udecl]p14:
3525  // If a function declaration in namespace scope or block scope has the
3526  // same name and the same parameter-type-list as a function introduced
3527  // by a using-declaration, and the declarations do not declare the same
3528  // function, the program is ill-formed.
3529 
3530  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3531  if (Old &&
3532  !Old->getDeclContext()->getRedeclContext()->Equals(
3533  New->getDeclContext()->getRedeclContext()) &&
3534  !(isExternC(Old) && isExternC(New)))
3535  Old = nullptr;
3536 
3537  if (!Old) {
3538  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3539  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3540  S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3541  return true;
3542  }
3543  return false;
3544 }
3545 
3547  const FunctionDecl *B) {
3548  assert(A->getNumParams() == B->getNumParams());
3549 
3550  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3551  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3552  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3553  if (AttrA == AttrB)
3554  return true;
3555  return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3556  AttrA->isDynamic() == AttrB->isDynamic();
3557  };
3558 
3559  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3560 }
3561 
3562 /// If necessary, adjust the semantic declaration context for a qualified
3563 /// declaration to name the correct inline namespace within the qualifier.
3565  DeclaratorDecl *OldD) {
3566  // The only case where we need to update the DeclContext is when
3567  // redeclaration lookup for a qualified name finds a declaration
3568  // in an inline namespace within the context named by the qualifier:
3569  //
3570  // inline namespace N { int f(); }
3571  // int ::f(); // Sema DC needs adjusting from :: to N::.
3572  //
3573  // For unqualified declarations, the semantic context *can* change
3574  // along the redeclaration chain (for local extern declarations,
3575  // extern "C" declarations, and friend declarations in particular).
3576  if (!NewD->getQualifier())
3577  return;
3578 
3579  // NewD is probably already in the right context.
3580  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3581  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3582  if (NamedDC->Equals(SemaDC))
3583  return;
3584 
3585  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3586  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3587  "unexpected context for redeclaration");
3588 
3589  auto *LexDC = NewD->getLexicalDeclContext();
3590  auto FixSemaDC = [=](NamedDecl *D) {
3591  if (!D)
3592  return;
3593  D->setDeclContext(SemaDC);
3594  D->setLexicalDeclContext(LexDC);
3595  };
3596 
3597  FixSemaDC(NewD);
3598  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3599  FixSemaDC(FD->getDescribedFunctionTemplate());
3600  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3601  FixSemaDC(VD->getDescribedVarTemplate());
3602 }
3603 
3604 /// MergeFunctionDecl - We just parsed a function 'New' from
3605 /// declarator D which has the same name and scope as a previous
3606 /// declaration 'Old'. Figure out how to resolve this situation,
3607 /// merging decls or emitting diagnostics as appropriate.
3608 ///
3609 /// In C++, New and Old must be declarations that are not
3610 /// overloaded. Use IsOverload to determine whether New and Old are
3611 /// overloaded, and to select the Old declaration that New should be
3612 /// merged with.
3613 ///
3614 /// Returns true if there was an error, false otherwise.
3616  bool MergeTypeWithOld, bool NewDeclIsDefn) {
3617  // Verify the old decl was also a function.
3618  FunctionDecl *Old = OldD->getAsFunction();
3619  if (!Old) {
3620  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3621  if (New->getFriendObjectKind()) {
3622  Diag(New->getLocation(), diag::err_using_decl_friend);
3623  Diag(Shadow->getTargetDecl()->getLocation(),
3624  diag::note_using_decl_target);
3625  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3626  << 0;
3627  return true;
3628  }
3629 
3630  // Check whether the two declarations might declare the same function or
3631  // function template.
3632  if (FunctionTemplateDecl *NewTemplate =
3634  if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3635  NewTemplate))
3636  return true;
3637  OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3638  ->getAsFunction();
3639  } else {
3640  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3641  return true;
3642  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3643  }
3644  } else {
3645  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3646  << New->getDeclName();
3647  notePreviousDefinition(OldD, New->getLocation());
3648  return true;
3649  }
3650  }
3651 
3652  // If the old declaration was found in an inline namespace and the new
3653  // declaration was qualified, update the DeclContext to match.
3655 
3656  // If the old declaration is invalid, just give up here.
3657  if (Old->isInvalidDecl())
3658  return true;
3659 
3660  // Disallow redeclaration of some builtins.
3661  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3662  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3663  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3664  << Old << Old->getType();
3665  return true;
3666  }
3667 
3668  diag::kind PrevDiag;
3669  SourceLocation OldLocation;
3670  std::tie(PrevDiag, OldLocation) =
3672 
3673  // Don't complain about this if we're in GNU89 mode and the old function
3674  // is an extern inline function.
3675  // Don't complain about specializations. They are not supposed to have
3676  // storage classes.
3677  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3678  New->getStorageClass() == SC_Static &&
3679  Old->hasExternalFormalLinkage() &&
3681  !canRedefineFunction(Old, getLangOpts())) {
3682  if (getLangOpts().MicrosoftExt) {
3683  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3684  Diag(OldLocation, PrevDiag);
3685  } else {
3686  Diag(New->getLocation(), diag::err_static_non_static) << New;
3687  Diag(OldLocation, PrevDiag);
3688  return true;
3689  }
3690  }
3691 
3692  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3693  if (!Old->hasAttr<InternalLinkageAttr>()) {
3694  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3695  << ILA;
3696  Diag(Old->getLocation(), diag::note_previous_declaration);
3697  New->dropAttr<InternalLinkageAttr>();
3698  }
3699 
3700  if (auto *EA = New->getAttr<ErrorAttr>()) {
3701  if (!Old->hasAttr<ErrorAttr>()) {
3702  Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3703  Diag(Old->getLocation(), diag::note_previous_declaration);
3704  New->dropAttr<ErrorAttr>();
3705  }
3706  }
3707 
3708  if (CheckRedeclarationInModule(New, Old))
3709  return true;
3710 
3711  if (!getLangOpts().CPlusPlus) {
3712  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3713  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3714  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3715  << New << OldOvl;
3716 
3717  // Try our best to find a decl that actually has the overloadable
3718  // attribute for the note. In most cases (e.g. programs with only one
3719  // broken declaration/definition), this won't matter.
3720  //
3721  // FIXME: We could do this if we juggled some extra state in
3722  // OverloadableAttr, rather than just removing it.
3723  const Decl *DiagOld = Old;
3724  if (OldOvl) {
3725  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3726  const auto *A = D->getAttr<OverloadableAttr>();
3727  return A && !A->isImplicit();
3728  });
3729  // If we've implicitly added *all* of the overloadable attrs to this
3730  // chain, emitting a "previous redecl" note is pointless.
3731  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3732  }
3733 
3734  if (DiagOld)
3735  Diag(DiagOld->getLocation(),
3736  diag::note_attribute_overloadable_prev_overload)
3737  << OldOvl;
3738 
3739  if (OldOvl)
3740  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3741  else
3742  New->dropAttr<OverloadableAttr>();
3743  }
3744  }
3745 
3746  // If a function is first declared with a calling convention, but is later
3747  // declared or defined without one, all following decls assume the calling
3748  // convention of the first.
3749  //
3750  // It's OK if a function is first declared without a calling convention,
3751  // but is later declared or defined with the default calling convention.
3752  //
3753  // To test if either decl has an explicit calling convention, we look for
3754  // AttributedType sugar nodes on the type as written. If they are missing or
3755  // were canonicalized away, we assume the calling convention was implicit.
3756  //
3757  // Note also that we DO NOT return at this point, because we still have
3758  // other tests to run.
3759  QualType OldQType = Context.getCanonicalType(Old->getType());
3760  QualType NewQType = Context.getCanonicalType(New->getType());
3761  const FunctionType *OldType = cast<FunctionType>(OldQType);
3762  const FunctionType *NewType = cast<FunctionType>(NewQType);
3763  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3764  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3765  bool RequiresAdjustment = false;
3766 
3767  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3768  FunctionDecl *First = Old->getFirstDecl();
3769  const FunctionType *FT =
3770  First->getType().getCanonicalType()->castAs<FunctionType>();
3771  FunctionType::ExtInfo FI = FT->getExtInfo();
3772  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3773  if (!NewCCExplicit) {
3774  // Inherit the CC from the previous declaration if it was specified
3775  // there but not here.
3776  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3777  RequiresAdjustment = true;
3778  } else if (Old->getBuiltinID()) {
3779  // Builtin attribute isn't propagated to the new one yet at this point,
3780  // so we check if the old one is a builtin.
3781 
3782  // Calling Conventions on a Builtin aren't really useful and setting a
3783  // default calling convention and cdecl'ing some builtin redeclarations is
3784  // common, so warn and ignore the calling convention on the redeclaration.
3785  Diag(New->getLocation(), diag::warn_cconv_unsupported)
3786  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3787  << (int)CallingConventionIgnoredReason::BuiltinFunction;
3788  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3789  RequiresAdjustment = true;
3790  } else {
3791  // Calling conventions aren't compatible, so complain.
3792  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3793  Diag(New->getLocation(), diag::err_cconv_change)
3794  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3795  << !FirstCCExplicit
3796  << (!FirstCCExplicit ? "" :
3797  FunctionType::getNameForCallConv(FI.getCC()));
3798 
3799  // Put the note on the first decl, since it is the one that matters.
3800  Diag(First->getLocation(), diag::note_previous_declaration);
3801  return true;
3802  }
3803  }
3804 
3805  // FIXME: diagnose the other way around?
3806  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3807  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3808  RequiresAdjustment = true;
3809  }
3810 
3811  // Merge regparm attribute.
3812  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3813  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3814  if (NewTypeInfo.getHasRegParm()) {
3815  Diag(New->getLocation(), diag::err_regparm_mismatch)
3816  << NewType->getRegParmType()
3817  << OldType->getRegParmType();
3818  Diag(OldLocation, diag::note_previous_declaration);
3819  return true;
3820  }
3821 
3822  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3823  RequiresAdjustment = true;
3824  }
3825 
3826  // Merge ns_returns_retained attribute.
3827  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3828  if (NewTypeInfo.getProducesResult()) {
3829  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3830  << "'ns_returns_retained'";
3831  Diag(OldLocation, diag::note_previous_declaration);
3832  return true;
3833  }
3834 
3835  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3836  RequiresAdjustment = true;
3837  }
3838 
3839  if (OldTypeInfo.getNoCallerSavedRegs() !=
3840  NewTypeInfo.getNoCallerSavedRegs()) {
3841  if (NewTypeInfo.getNoCallerSavedRegs()) {
3842  AnyX86NoCallerSavedRegistersAttr *Attr =
3843  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3844  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3845  Diag(OldLocation, diag::note_previous_declaration);
3846  return true;
3847  }
3848 
3849  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3850  RequiresAdjustment = true;
3851  }
3852 
3853  if (RequiresAdjustment) {
3854  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3855  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3856  New->setType(QualType(AdjustedType, 0));
3857  NewQType = Context.getCanonicalType(New->getType());
3858  }
3859 
3860  // If this redeclaration makes the function inline, we may need to add it to
3861  // UndefinedButUsed.
3862  if (!Old->isInlined() && New->isInlined() &&
3863  !New->hasAttr<GNUInlineAttr>() &&
3864  !getLangOpts().GNUInline &&
3865  Old->isUsed(false) &&
3866  !Old->isDefined() && !New->isThisDeclarationADefinition())
3867  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3868  SourceLocation()));
3869 
3870  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3871  // about it.
3872  if (New->hasAttr<GNUInlineAttr>() &&
3873  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3874  UndefinedButUsed.erase(Old->getCanonicalDecl());
3875  }
3876 
3877  // If pass_object_size params don't match up perfectly, this isn't a valid
3878  // redeclaration.
3879  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3880  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3881  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3882  << New->getDeclName();
3883  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3884  return true;
3885  }
3886 
3887  if (getLangOpts().CPlusPlus) {
3888  // C++1z [over.load]p2
3889  // Certain function declarations cannot be overloaded:
3890  // -- Function declarations that differ only in the return type,
3891  // the exception specification, or both cannot be overloaded.
3892 
3893  // Check the exception specifications match. This may recompute the type of
3894  // both Old and New if it resolved exception specifications, so grab the
3895  // types again after this. Because this updates the type, we do this before
3896  // any of the other checks below, which may update the "de facto" NewQType
3897  // but do not necessarily update the type of New.
3898  if (CheckEquivalentExceptionSpec(Old, New))
3899  return true;
3900  OldQType = Context.getCanonicalType(Old->getType());
3901  NewQType = Context.getCanonicalType(New->getType());
3902 
3903  // Go back to the type source info to compare the declared return types,
3904  // per C++1y [dcl.type.auto]p13:
3905  // Redeclarations or specializations of a function or function template
3906  // with a declared return type that uses a placeholder type shall also
3907  // use that placeholder, not a deduced type.
3908  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3909  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3910  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3911  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3912  OldDeclaredReturnType)) {
3913  QualType ResQT;
3914  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3915  OldDeclaredReturnType->isObjCObjectPointerType())
3916  // FIXME: This does the wrong thing for a deduced return type.
3917  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3918  if (ResQT.isNull()) {
3919  if (New->isCXXClassMember() && New->isOutOfLine())
3920  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3921  << New << New->getReturnTypeSourceRange();
3922  else
3923  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3924  << New->getReturnTypeSourceRange();
3925  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3926  << Old->getReturnTypeSourceRange();
3927  return true;
3928  }
3929  else
3930  NewQType = ResQT;
3931  }
3932 
3933  QualType OldReturnType = OldType->getReturnType();
3934  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3935  if (OldReturnType != NewReturnType) {
3936  // If this function has a deduced return type and has already been
3937  // defined, copy the deduced value from the old declaration.
3938  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3939  if (OldAT && OldAT->isDeduced()) {
3940  QualType DT = OldAT->getDeducedType();
3941  if (DT.isNull()) {
3942  New->setType(SubstAutoTypeDependent(New->getType()));
3943  NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3944  } else {
3945  New->setType(SubstAutoType(New->getType(), DT));
3946  NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3947  }
3948  }
3949  }
3950 
3951  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3952  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3953  if (OldMethod && NewMethod) {
3954  // Preserve triviality.
3955  NewMethod->setTrivial(OldMethod->isTrivial());
3956 
3957  // MSVC allows explicit template specialization at class scope:
3958  // 2 CXXMethodDecls referring to the same function will be injected.
3959  // We don't want a redeclaration error.
3960  bool IsClassScopeExplicitSpecialization =
3961  OldMethod->isFunctionTemplateSpecialization() &&
3962  NewMethod->isFunctionTemplateSpecialization();
3963  bool isFriend = NewMethod->getFriendObjectKind();
3964 
3965  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3966  !IsClassScopeExplicitSpecialization) {
3967  // -- Member function declarations with the same name and the
3968  // same parameter types cannot be overloaded if any of them
3969  // is a static member function declaration.
3970  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3971  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3972  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3973  return true;
3974  }
3975 
3976  // C++ [class.mem]p1:
3977  // [...] A member shall not be declared twice in the
3978  // member-specification, except that a nested class or member
3979  // class template can be declared and then later defined.
3980  if (!inTemplateInstantiation()) {
3981  unsigned NewDiag;
3982  if (isa<CXXConstructorDecl>(OldMethod))
3983  NewDiag = diag::err_constructor_redeclared;
3984  else if (isa<CXXDestructorDecl>(NewMethod))
3985  NewDiag = diag::err_destructor_redeclared;
3986  else if (isa<CXXConversionDecl>(NewMethod))
3987  NewDiag = diag::err_conv_function_redeclared;
3988  else
3989  NewDiag = diag::err_member_redeclared;
3990 
3991  Diag(New->getLocation(), NewDiag);
3992  } else {
3993  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3994  << New << New->getType();
3995  }
3996  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3997  return true;
3998 
3999  // Complain if this is an explicit declaration of a special
4000  // member that was initially declared implicitly.
4001  //
4002  // As an exception, it's okay to befriend such methods in order
4003  // to permit the implicit constructor/destructor/operator calls.
4004  } else if (OldMethod->isImplicit()) {
4005  if (isFriend) {
4006  NewMethod->setImplicit();
4007  } else {
4008  Diag(NewMethod->getLocation(),
4009  diag::err_definition_of_implicitly_declared_member)
4010  << New << getSpecialMember(OldMethod);
4011  return true;
4012  }
4013  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4014  Diag(NewMethod->getLocation(),
4015  diag::err_definition_of_explicitly_defaulted_member)
4016  << getSpecialMember(OldMethod);
4017  return true;
4018  }
4019  }
4020 
4021  // C++11 [dcl.attr.noreturn]p1:
4022  // The first declaration of a function shall specify the noreturn
4023  // attribute if any declaration of that function specifies the noreturn
4024  // attribute.
4025  if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4026  if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4027  Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4028  << NRA;
4029  Diag(Old->getLocation(), diag::note_previous_declaration);
4030  }
4031 
4032  // C++11 [dcl.attr.depend]p2:
4033  // The first declaration of a function shall specify the
4034  // carries_dependency attribute for its declarator-id if any declaration
4035  // of the function specifies the carries_dependency attribute.
4036  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4037  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4038  Diag(CDA->getLocation(),
4039  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4040  Diag(Old->getFirstDecl()->getLocation(),
4041  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4042  }
4043 
4044  // (C++98 8.3.5p3):
4045  // All declarations for a function shall agree exactly in both the
4046  // return type and the parameter-type-list.
4047  // We also want to respect all the extended bits except noreturn.
4048 
4049  // noreturn should now match unless the old type info didn't have it.
4050  QualType OldQTypeForComparison = OldQType;
4051  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4052  auto *OldType = OldQType->castAs<FunctionProtoType>();
4053  const FunctionType *OldTypeForComparison
4054  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4055  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4056  assert(OldQTypeForComparison.isCanonical());
4057  }
4058 
4059  if (haveIncompatibleLanguageLinkages(Old, New)) {
4060  // As a special case, retain the language linkage from previous
4061  // declarations of a friend function as an extension.
4062  //
4063  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4064  // and is useful because there's otherwise no way to specify language
4065  // linkage within class scope.
4066  //
4067  // Check cautiously as the friend object kind isn't yet complete.
4068  if (New->getFriendObjectKind() != Decl::FOK_None) {
4069  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4070  Diag(OldLocation, PrevDiag);
4071  } else {
4072  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4073  Diag(OldLocation, PrevDiag);
4074  return true;
4075  }
4076  }
4077 
4078  // If the function types are compatible, merge the declarations. Ignore the
4079  // exception specifier because it was already checked above in
4080  // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4081  // about incompatible types under -fms-compatibility.
4082  if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4083  NewQType))
4084  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4085 
4086  // If the types are imprecise (due to dependent constructs in friends or
4087  // local extern declarations), it's OK if they differ. We'll check again
4088  // during instantiation.
4089  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4090  return false;
4091 
4092  // Fall through for conflicting redeclarations and redefinitions.
4093  }
4094 
4095  // C: Function types need to be compatible, not identical. This handles
4096  // duplicate function decls like "void f(int); void f(enum X);" properly.
4097  if (!getLangOpts().CPlusPlus) {
4098  // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4099  // type is specified by a function definition that contains a (possibly
4100  // empty) identifier list, both shall agree in the number of parameters
4101  // and the type of each parameter shall be compatible with the type that
4102  // results from the application of default argument promotions to the
4103  // type of the corresponding identifier. ...
4104  // This cannot be handled by ASTContext::typesAreCompatible() because that
4105  // doesn't know whether the function type is for a definition or not when
4106  // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4107  // we need to cover here is that the number of arguments agree as the
4108  // default argument promotion rules were already checked by
4109  // ASTContext::typesAreCompatible().
4110  if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4111  Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4112  if (Old->hasInheritedPrototype())
4113  Old = Old->getCanonicalDecl();
4114  Diag(New->getLocation(), diag::err_conflicting_types) << New;
4115  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4116  return true;
4117  }
4118 
4119  // If we are merging two functions where only one of them has a prototype,
4120  // we may have enough information to decide to issue a diagnostic that the
4121  // function without a protoype will change behavior in C2x. This handles
4122  // cases like:
4123  // void i(); void i(int j);
4124  // void i(int j); void i();
4125  // void i(); void i(int j) {}
4126  // See ActOnFinishFunctionBody() for other cases of the behavior change
4127  // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4128  // type without a prototype.
4129  if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4130  !New->isImplicit() && !Old->isImplicit()) {
4131  const FunctionDecl *WithProto, *WithoutProto;
4132  if (New->hasWrittenPrototype()) {
4133  WithProto = New;
4134  WithoutProto = Old;
4135  } else {
4136  WithProto = Old;
4137  WithoutProto = New;
4138  }
4139 
4140  if (WithProto->getNumParams() != 0) {
4141  if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4142  // The one without the prototype will be changing behavior in C2x, so
4143  // warn about that one so long as it's a user-visible declaration.
4144  bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4145  if (WithoutProto == New)
4146  IsWithoutProtoADef = NewDeclIsDefn;
4147  else
4148  IsWithProtoADef = NewDeclIsDefn;
4149  Diag(WithoutProto->getLocation(),
4150  diag::warn_non_prototype_changes_behavior)
4151  << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4152  << (WithoutProto == Old) << IsWithProtoADef;
4153 
4154  // The reason the one without the prototype will be changing behavior
4155  // is because of the one with the prototype, so note that so long as
4156  // it's a user-visible declaration. There is one exception to this:
4157  // when the new declaration is a definition without a prototype, the
4158  // old declaration with a prototype is not the cause of the issue,
4159  // and that does not need to be noted because the one with a
4160  // prototype will not change behavior in C2x.
4161  if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4162  !IsWithoutProtoADef)
4163  Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4164  }
4165  }
4166  }
4167 
4168  if (Context.typesAreCompatible(OldQType, NewQType)) {
4169  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4170  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4171  const FunctionProtoType *OldProto = nullptr;
4172  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4173  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4174  // The old declaration provided a function prototype, but the
4175  // new declaration does not. Merge in the prototype.
4176  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4177  NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4178  OldProto->getParamTypes(),
4179  OldProto->getExtProtoInfo());
4180  New->setType(NewQType);
4181  New->setHasInheritedPrototype();
4182 
4183  // Synthesize parameters with the same types.
4185  for (const auto &ParamType : OldProto->param_types()) {
4187  Context, New, SourceLocation(), SourceLocation(), nullptr,
4188  ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4189  Param->setScopeInfo(0, Params.size());
4190  Param->setImplicit();
4191  Params.push_back(Param);
4192  }
4193 
4194  New->setParams(Params);
4195  }
4196 
4197  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4198  }
4199  }
4200 
4201  // Check if the function types are compatible when pointer size address
4202  // spaces are ignored.
4203  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4204  return false;
4205 
4206  // GNU C permits a K&R definition to follow a prototype declaration
4207  // if the declared types of the parameters in the K&R definition
4208  // match the types in the prototype declaration, even when the
4209  // promoted types of the parameters from the K&R definition differ
4210  // from the types in the prototype. GCC then keeps the types from
4211  // the prototype.
4212  //
4213  // If a variadic prototype is followed by a non-variadic K&R definition,
4214  // the K&R definition becomes variadic. This is sort of an edge case, but
4215  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4216  // C99 6.9.1p8.
4217  if (!getLangOpts().CPlusPlus &&
4218  Old->hasPrototype() && !New->hasPrototype() &&
4219  New->getType()->getAs<FunctionProtoType>() &&
4220  Old->getNumParams() == New->getNumParams()) {
4221  SmallVector<QualType, 16> ArgTypes;
4223  const FunctionProtoType *OldProto
4224  = Old->getType()->getAs<FunctionProtoType>();
4225  const FunctionProtoType *NewProto
4226  = New->getType()->getAs<FunctionProtoType>();
4227 
4228  // Determine whether this is the GNU C extension.
4229  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4230  NewProto->getReturnType());
4231  bool LooseCompatible = !MergedReturn.isNull();
4232  for (unsigned Idx = 0, End = Old->getNumParams();
4233  LooseCompatible && Idx != End; ++Idx) {
4234  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4235  ParmVarDecl *NewParm = New->getParamDecl(Idx);
4236  if (Context.typesAreCompatible(OldParm->getType(),
4237  NewProto->getParamType(Idx))) {
4238  ArgTypes.push_back(NewParm->getType());
4239  } else if (Context.typesAreCompatible(OldParm->getType(),
4240  NewParm->getType(),
4241  /*CompareUnqualified=*/true)) {
4242  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4243  NewProto->getParamType(Idx) };
4244  Warnings.push_back(Warn);
4245  ArgTypes.push_back(NewParm->getType());
4246  } else
4247  LooseCompatible = false;
4248  }
4249 
4250  if (LooseCompatible) {
4251  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4252  Diag(Warnings[Warn].NewParm->getLocation(),
4253  diag::ext_param_promoted_not_compatible_with_prototype)
4254  << Warnings[Warn].PromotedType
4255  << Warnings[Warn].OldParm->getType();
4256  if (Warnings[Warn].OldParm->getLocation().isValid())
4257  Diag(Warnings[Warn].OldParm->getLocation(),
4258  diag::note_previous_declaration);
4259  }
4260 
4261  if (MergeTypeWithOld)
4262  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4263  OldProto->getExtProtoInfo()));
4264  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4265  }
4266 
4267  // Fall through to diagnose conflicting types.
4268  }
4269 
4270  // A function that has already been declared has been redeclared or
4271  // defined with a different type; show an appropriate diagnostic.
4272 
4273  // If the previous declaration was an implicitly-generated builtin
4274  // declaration, then at the very least we should use a specialized note.
4275  unsigned BuiltinID;
4276  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4277  // If it's actually a library-defined builtin function like 'malloc'
4278  // or 'printf', just warn about the incompatible redeclaration.
4279  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4280  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4281  Diag(OldLocation, diag::note_previous_builtin_declaration)
4282  << Old << Old->getType();
4283  return false;
4284  }
4285 
4286  PrevDiag = diag::note_previous_builtin_declaration;
4287  }
4288 
4289  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4290  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4291  return true;
4292 }
4293 
4294 /// Completes the merge of two function declarations that are
4295 /// known to be compatible.
4296 ///
4297 /// This routine handles the merging of attributes and other
4298 /// properties of function declarations from the old declaration to
4299 /// the new declaration, once we know that New is in fact a
4300 /// redeclaration of Old.
4301 ///
4302 /// \returns false
4304  Scope *S, bool MergeTypeWithOld) {
4305  // Merge the attributes
4306  mergeDeclAttributes(New, Old);
4307 
4308  // Merge "pure" flag.
4309  if (Old->isPure())
4310  New->setPure();
4311 
4312  // Merge "used" flag.
4313  if (Old->getMostRecentDecl()->isUsed(false))
4314  New->setIsUsed();
4315 
4316  // Merge attributes from the parameters. These can mismatch with K&R
4317  // declarations.
4318  if (New->getNumParams() == Old->getNumParams())
4319  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4320  ParmVarDecl *NewParam = New->getParamDecl(i);
4321  ParmVarDecl *OldParam = Old->getParamDecl(i);
4322  mergeParamDeclAttributes(NewParam, OldParam, *this);
4323  mergeParamDeclTypes(NewParam, OldParam, *this);
4324  }
4325 
4326  if (getLangOpts().CPlusPlus)
4327  return MergeCXXFunctionDecl(New, Old, S);
4328 
4329  // Merge the function types so the we get the composite types for the return
4330  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4331  // was visible.
4332  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4333  if (!Merged.isNull() && MergeTypeWithOld)
4334  New->setType(Merged);
4335 
4336  return false;
4337 }
4338 
4340  ObjCMethodDecl *oldMethod) {
4341  // Merge the attributes, including deprecated/unavailable
4342  AvailabilityMergeKind MergeKind =
4343  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4344  ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4345  : AMK_ProtocolImplementation)
4346  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4347  : AMK_Override;
4348 
4349  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4350 
4351  // Merge attributes from the parameters.
4353  oe = oldMethod->param_end();
4355  ni = newMethod->param_begin(), ne = newMethod->param_end();
4356  ni != ne && oi != oe; ++ni, ++oi)
4357  mergeParamDeclAttributes(*ni, *oi, *this);
4358 
4359  CheckObjCMethodOverride(newMethod, oldMethod);
4360 }
4361 
4362 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4363  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4364 
4366  ? diag::err_redefinition_different_type
4367  : diag::err_redeclaration_different_type)
4368  << New->getDeclName() << New->getType() << Old->getType();
4369 
4370  diag::kind PrevDiag;
4371  SourceLocation OldLocation;
4372  std::tie(PrevDiag, OldLocation)
4374  S.Diag(OldLocation, PrevDiag);
4375  New->setInvalidDecl();
4376 }
4377 
4378 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4379 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4380 /// emitting diagnostics as appropriate.
4381 ///
4382 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4383 /// to here in AddInitializerToDecl. We can't check them before the initializer
4384 /// is attached.
4386  bool MergeTypeWithOld) {
4387  if (New->isInvalidDecl() || Old->isInvalidDecl())
4388  return;
4389 
4390  QualType MergedT;
4391  if (getLangOpts().CPlusPlus) {
4392  if (New->getType()->isUndeducedType()) {
4393  // We don't know what the new type is until the initializer is attached.
4394  return;
4395  } else if (Context.hasSameType(New->getType(), Old->getType())) {
4396  // These could still be something that needs exception specs checked.
4397  return MergeVarDeclExceptionSpecs(New, Old);
4398  }
4399  // C++ [basic.link]p10:
4400  // [...] the types specified by all declarations referring to a given
4401  // object or function shall be identical, except that declarations for an
4402  // array object can specify array types that differ by the presence or
4403  // absence of a major array bound (8.3.4).
4404  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4405  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4406  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4407 
4408  // We are merging a variable declaration New into Old. If it has an array
4409  // bound, and that bound differs from Old's bound, we should diagnose the
4410  // mismatch.
4411  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4412  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4413  PrevVD = PrevVD->getPreviousDecl()) {
4414  QualType PrevVDTy = PrevVD->getType();
4415  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4416  continue;
4417 
4418  if (!Context.hasSameType(New->getType(), PrevVDTy))
4419  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4420  }
4421  }
4422 
4423  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4424  if (Context.hasSameType(OldArray->getElementType(),
4425  NewArray->getElementType()))
4426  MergedT = New->getType();
4427  }
4428  // FIXME: Check visibility. New is hidden but has a complete type. If New
4429  // has no array bound, it should not inherit one from Old, if Old is not
4430  // visible.
4431  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4432  if (Context.hasSameType(OldArray->getElementType(),
4433  NewArray->getElementType()))
4434  MergedT = Old->getType();
4435  }
4436  }
4437  else if (New->getType()->isObjCObjectPointerType() &&
4438  Old->getType()->isObjCObjectPointerType()) {
4439  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4440  Old->getType());
4441  }
4442  } else {
4443  // C 6.2.7p2:
4444  // All declarations that refer to the same object or function shall have
4445  // compatible type.
4446  MergedT = Context.mergeTypes(New->getType(), Old->getType());
4447  }
4448  if (MergedT.isNull()) {
4449  // It's OK if we couldn't merge types if either type is dependent, for a
4450  // block-scope variable. In other cases (static data members of class
4451  // templates, variable templates, ...), we require the types to be
4452  // equivalent.
4453  // FIXME: The C++ standard doesn't say anything about this.
4454  if ((New->getType()->isDependentType() ||
4455  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4456  // If the old type was dependent, we can't merge with it, so the new type
4457  // becomes dependent for now. We'll reproduce the original type when we
4458  // instantiate the TypeSourceInfo for the variable.
4459  if (!New->getType()->isDependentType() && MergeTypeWithOld)
4460  New->setType(Context.DependentTy);
4461  return;
4462  }
4463  return diagnoseVarDeclTypeMismatch(*this, New, Old);
4464  }
4465 
4466  // Don't actually update the type on the new declaration if the old
4467  // declaration was an extern declaration in a different scope.
4468  if (MergeTypeWithOld)
4469  New->setType(MergedT);
4470 }
4471 
4472 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4474  // C11 6.2.7p4:
4475  // For an identifier with internal or external linkage declared
4476  // in a scope in which a prior declaration of that identifier is
4477  // visible, if the prior declaration specifies internal or
4478  // external linkage, the type of the identifier at the later
4479  // declaration becomes the composite type.
4480  //
4481  // If the variable isn't visible, we do not merge with its type.
4482  if (Previous.isShadowed())
4483  return false;
4484 
4485  if (S.getLangOpts().CPlusPlus) {
4486  // C++11 [dcl.array]p3:
4487  // If there is a preceding declaration of the entity in the same
4488  // scope in which the bound was specified, an omitted array bound
4489  // is taken to be the same as in that earlier declaration.
4490  return NewVD->isPreviousDeclInSameBlockScope() ||
4491  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4493  } else {
4494  // If the old declaration was function-local, don't merge with its
4495  // type unless we're in the same function.
4496  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4497  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4498  }
4499 }
4500 
4501 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4502 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4503 /// situation, merging decls or emitting diagnostics as appropriate.
4504 ///
4505 /// Tentative definition rules (C99 6.9.2p2) are checked by
4506 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4507 /// definitions here, since the initializer hasn't been attached.
4508 ///
4510  // If the new decl is already invalid, don't do any other checking.
4511  if (New->isInvalidDecl())
4512  return;
4513 
4514  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4515  return;
4516 
4517  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4518 
4519  // Verify the old decl was also a variable or variable template.
4520  VarDecl *Old = nullptr;
4521  VarTemplateDecl *OldTemplate = nullptr;
4522  if (Previous.isSingleResult()) {
4523  if (NewTemplate) {
4524  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4525  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4526 
4527  if (auto *Shadow =
4528  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4529  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4530  return New->setInvalidDecl();
4531  } else {
4532  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4533 
4534  if (auto *Shadow =
4535  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4536  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4537  return New->setInvalidDecl();
4538  }
4539  }
4540  if (!Old) {
4541  Diag(New->getLocation(), diag::err_redefinition_different_kind)
4542  << New->getDeclName();
4543  notePreviousDefinition(Previous.getRepresentativeDecl(),
4544  New->getLocation());
4545  return New->setInvalidDecl();
4546  }
4547 
4548  // If the old declaration was found in an inline namespace and the new
4549  // declaration was qualified, update the DeclContext to match.
4551 
4552  // Ensure the template parameters are compatible.
4553  if (NewTemplate &&
4554  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4555  OldTemplate->getTemplateParameters(),
4556  /*Complain=*/true, TPL_TemplateMatch))
4557  return New->setInvalidDecl();
4558 
4559  // C++ [class.mem]p1:
4560  // A member shall not be declared twice in the member-specification [...]
4561  //
4562  // Here, we need only consider static data members.
4563  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4564  Diag(New->getLocation(), diag::err_duplicate_member)
4565  << New->getIdentifier();
4566  Diag(Old->getLocation(), diag::note_previous_declaration);
4567  New->setInvalidDecl();
4568  }
4569 
4570  mergeDeclAttributes(New, Old);
4571  // Warn if an already-declared variable is made a weak_import in a subsequent
4572  // declaration
4573  if (New->hasAttr<WeakImportAttr>() &&
4574  Old->getStorageClass() == SC_None &&
4575  !Old->hasAttr<WeakImportAttr>()) {
4576  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4577  Diag(Old->getLocation(), diag::note_previous_declaration);
4578  // Remove weak_import attribute on new declaration.
4579  New->dropAttr<WeakImportAttr>();
4580  }
4581 
4582  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4583  if (!Old->hasAttr<InternalLinkageAttr>()) {
4584  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4585  << ILA;
4586  Diag(Old->getLocation(), diag::note_previous_declaration);
4587  New->dropAttr<InternalLinkageAttr>();
4588  }
4589 
4590  // Merge the types.
4591  VarDecl *MostRecent = Old->getMostRecentDecl();
4592  if (MostRecent != Old) {
4593  MergeVarDeclTypes(New, MostRecent,
4594  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4595  if (New->isInvalidDecl())
4596  return;
4597  }
4598 
4599  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4600  if (New->isInvalidDecl())
4601  return;
4602 
4603  diag::kind PrevDiag;
4604  SourceLocation OldLocation;
4605  std::tie(PrevDiag, OldLocation) =
4607 
4608  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4609  if (New->getStorageClass() == SC_Static &&
4610  !New->isStaticDataMember() &&
4611  Old->hasExternalFormalLinkage()) {
4612  if (getLangOpts().MicrosoftExt) {
4613  Diag(New->getLocation(), diag::ext_static_non_static)
4614  << New->getDeclName();
4615  Diag(OldLocation, PrevDiag);
4616  } else {
4617  Diag(New->getLocation(), diag::err_static_non_static)
4618  << New->getDeclName();
4619  Diag(OldLocation, PrevDiag);
4620  return New->setInvalidDecl();
4621  }
4622  }
4623  // C99 6.2.2p4:
4624  // For an identifier declared with the storage-class specifier
4625  // extern in a scope in which a prior declaration of that
4626  // identifier is visible,23) if the prior declaration specifies
4627  // internal or external linkage, the linkage of the identifier at
4628  // the later declaration is the same as the linkage specified at
4629  // the prior declaration. If no prior declaration is visible, or
4630  // if the prior declaration specifies no linkage, then the
4631  // identifier has external linkage.
4632  if (New->hasExternalStorage() && Old->hasLinkage())
4633  /* Okay */;
4634  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4635  !New->isStaticDataMember() &&
4637  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4638  Diag(OldLocation, PrevDiag);
4639  return New->setInvalidDecl();
4640  }
4641 
4642  // Check if extern is followed by non-extern and vice-versa.
4643  if (New->hasExternalStorage() &&
4644  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4645  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4646  Diag(OldLocation, PrevDiag);
4647  return New->setInvalidDecl();
4648  }
4649  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4650  !New->hasExternalStorage()) {
4651  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4652  Diag(OldLocation, PrevDiag);
4653  return New->setInvalidDecl();
4654  }
4655 
4656  if (CheckRedeclarationInModule(New, Old))
4657  return;
4658 
4659  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4660 
4661  // FIXME: The test for external storage here seems wrong? We still
4662  // need to check for mismatches.
4663  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4664  // Don't complain about out-of-line definitions of static members.
4665  !(Old->getLexicalDeclContext()->isRecord() &&
4666  !New->getLexicalDeclContext()->isRecord())) {
4667  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4668  Diag(OldLocation, PrevDiag);
4669  return New->setInvalidDecl();
4670  }
4671 
4672  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4673  if (VarDecl *Def = Old->getDefinition()) {
4674  // C++1z [dcl.fcn.spec]p4:
4675  // If the definition of a variable appears in a translation unit before
4676  // its first declaration as inline, the program is ill-formed.
4677  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4678  Diag(Def->getLocation(), diag::note_previous_definition);
4679  }
4680  }
4681 
4682  // If this redeclaration makes the variable inline, we may need to add it to
4683  // UndefinedButUsed.
4684  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4685  !Old->getDefinition() && !New->isThisDeclarationADefinition())
4686  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4687  SourceLocation()));
4688 
4689  if (New->getTLSKind() != Old->getTLSKind()) {
4690  if (!Old->getTLSKind()) {
4691  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4692  Diag(OldLocation, PrevDiag);
4693  } else if (!New->getTLSKind()) {
4694  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4695  Diag(OldLocation, PrevDiag);
4696  } else {
4697  // Do not allow redeclaration to change the variable between requiring
4698  // static and dynamic initialization.
4699  // FIXME: GCC allows this, but uses the TLS keyword on the first
4700  // declaration to determine the kind. Do we need to be compatible here?
4701  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4702  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4703  Diag(OldLocation, PrevDiag);
4704  }
4705  }
4706 
4707  // C++ doesn't have tentative definitions, so go right ahead and check here.
4708  if (getLangOpts().CPlusPlus) {
4709  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4710  Old->getCanonicalDecl()->isConstexpr()) {
4711  // This definition won't be a definition any more once it's been merged.
4712  Diag(New->getLocation(),
4713  diag::warn_deprecated_redundant_constexpr_static_def);
4714  } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4715  VarDecl *Def = Old->getDefinition();
4716  if (Def && checkVarDeclRedefinition(Def, New))
4717  return;
4718  }
4719  }
4720 
4721  if (haveIncompatibleLanguageLinkages(Old, New)) {
4722  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4723  Diag(OldLocation, PrevDiag);
4724  New->setInvalidDecl();
4725  return;
4726  }
4727 
4728  // Merge "used" flag.
4729  if (Old->getMostRecentDecl()->isUsed(false))
4730  New->setIsUsed();
4731 
4732  // Keep a chain of previous declarations.
4733  New->setPreviousDecl(Old);
4734  if (NewTemplate)
4735  NewTemplate->setPreviousDecl(OldTemplate);
4736 
4737  // Inherit access appropriately.
4738  New->setAccess(Old->getAccess());
4739  if (NewTemplate)
4740  NewTemplate->setAccess(New->getAccess());
4741 
4742  if (Old->isInline())
4743  New->setImplicitlyInline();
4744 }
4745 
4747  SourceManager &SrcMgr = getSourceManager();
4748  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4749  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4750  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4751  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4752  auto &HSI = PP.getHeaderSearchInfo();
4753  StringRef HdrFilename =
4754  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4755 
4756  auto noteFromModuleOrInclude = [&](Module *Mod,
4757  SourceLocation IncLoc) -> bool {
4758  // Redefinition errors with modules are common with non modular mapped
4759  // headers, example: a non-modular header H in module A that also gets
4760  // included directly in a TU. Pointing twice to the same header/definition
4761  // is confusing, try to get better diagnostics when modules is on.
4762  if (IncLoc.isValid()) {
4763  if (Mod) {
4764  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4765  << HdrFilename.str() << Mod->getFullModuleName();
4766  if (!Mod->DefinitionLoc.isInvalid())
4767  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4768  << Mod->getFullModuleName();
4769  } else {
4770  Diag(IncLoc, diag::note_redefinition_include_same_file)
4771  << HdrFilename.str();
4772  }
4773  return true;
4774  }
4775 
4776  return false;
4777  };
4778 
4779  // Is it the same file and same offset? Provide more information on why
4780  // this leads to a redefinition error.
4781  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4782  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4783  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4784  bool EmittedDiag =
4785  noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4786  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4787 
4788  // If the header has no guards, emit a note suggesting one.
4789  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4790  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4791 
4792  if (EmittedDiag)
4793  return;
4794  }
4795 
4796  // Redefinition coming from different files or couldn't do better above.
4797  if (Old->getLocation().isValid())
4798  Diag(Old->getLocation(), diag::note_previous_definition);
4799 }
4800 
4801 /// We've just determined that \p Old and \p New both appear to be definitions
4802 /// of the same variable. Either diagnose or fix the problem.
4804  if (!hasVisibleDefinition(Old) &&
4805  (New->getFormalLinkage() == InternalLinkage ||
4806  New->isInline() ||
4807  isa<VarTemplateSpecializationDecl>(New) ||
4808  New->getDescribedVarTemplate() ||
4810  New->getDeclContext()->isDependentContext())) {
4811  // The previous definition is hidden, and multiple definitions are
4812  // permitted (in separate TUs). Demote this to a declaration.
4814 
4815  // Make the canonical definition visible.
4816  if (auto *OldTD = Old->getDescribedVarTemplate())
4817  makeMergedDefinitionVisible(OldTD);
4818  makeMergedDefinitionVisible(Old);
4819  return false;
4820  } else {
4821  Diag(New->getLocation(), diag::err_redefinition) << New;
4822  notePreviousDefinition(Old, New->getLocation());
4823  New->setInvalidDecl();
4824  return true;
4825  }
4826 }
4827 
4828 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4829 /// no declarator (e.g. "struct foo;") is parsed.
4831  DeclSpec &DS,
4832  const ParsedAttributesView &DeclAttrs,
4833  RecordDecl *&AnonRecord) {
4834  return ParsedFreeStandingDeclSpec(
4835  S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4836 }
4837 
4838 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4839 // disambiguate entities defined in different scopes.
4840 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4841 // compatibility.
4842 // We will pick our mangling number depending on which version of MSVC is being
4843 // targeted.
4844 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4846  ? S->getMSCurManglingNumber()
4847  : S->getMSLastManglingNumber();
4848 }
4849 
4850 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4851  if (!Context.getLangOpts().CPlusPlus)
4852  return;
4853 
4854  if (isa<CXXRecordDecl>(Tag->getParent())) {
4855  // If this tag is the direct child of a class, number it if
4856  // it is anonymous.
4857  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4858  return;
4859  MangleNumberingContext &MCtx =
4860  Context.getManglingNumberContext(Tag->getParent());
4861  Context.setManglingNumber(
4862  Tag, MCtx.getManglingNumber(
4863  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4864  return;
4865  }
4866 
4867  // If this tag isn't a direct child of a class, number it if it is local.
4868  MangleNumberingContext *MCtx;
4869  Decl *ManglingContextDecl;
4870  std::tie(MCtx, ManglingContextDecl) =
4871  getCurrentMangleNumberContext(Tag->getDeclContext());
4872  if (MCtx) {
4873  Context.setManglingNumber(
4874  Tag, MCtx->getManglingNumber(
4875  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4876  }
4877 }
4878 
4879 namespace {
4880 struct NonCLikeKind {
4881  enum {
4882  None,
4883  BaseClass,
4884  DefaultMemberInit,
4885  Lambda,
4886  Friend,
4887  OtherMember,
4888  Invalid,
4889  } Kind = None;
4890  SourceRange Range;
4891 
4892  explicit operator bool() { return Kind != None; }
4893 };
4894 }
4895 
4896 /// Determine whether a class is C-like, according to the rules of C++
4897 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4898 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4899  if (RD->isInvalidDecl())
4900  return {NonCLikeKind::Invalid, {}};
4901 
4902  // C++ [dcl.typedef]p9: [P1766R1]
4903  // An unnamed class with a typedef name for linkage purposes shall not
4904  //
4905  // -- have any base classes
4906  if (RD->getNumBases())
4907  return {NonCLikeKind::BaseClass,
4909  RD->bases_end()[-1].getEndLoc())};
4910  bool Invalid = false;
4911  for (Decl *D : RD->decls()) {
4912  // Don't complain about things we already diagnosed.
4913  if (D->isInvalidDecl()) {
4914  Invalid = true;
4915  continue;
4916  }
4917 
4918  // -- have any [...] default member initializers
4919  if (auto *FD = dyn_cast<FieldDecl>(D)) {
4920  if (FD->hasInClassInitializer()) {
4921  auto *Init = FD->getInClassInitializer();
4922  return {NonCLikeKind::DefaultMemberInit,
4923  Init ? Init->getSourceRange() : D->getSourceRange()};
4924  }
4925  continue;
4926  }
4927 
4928  // FIXME: We don't allow friend declarations. This violates the wording of
4929  // P1766, but not the intent.
4930  if (isa<FriendDecl>(D))
4931  return {NonCLikeKind::Friend, D->getSourceRange()};
4932 
4933  // -- declare any members other than non-static data members, member
4934  // enumerations, or member classes,
4935  if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4936  isa<EnumDecl>(D))
4937  continue;
4938  auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4939  if (!MemberRD) {
4940  if (D->isImplicit())
4941  continue;
4942  return {NonCLikeKind::OtherMember, D->getSourceRange()};
4943  }
4944 
4945  // -- contain a lambda-expression,
4946  if (MemberRD->isLambda())
4947  return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4948 
4949  // and all member classes shall also satisfy these requirements
4950  // (recursively).
4951  if (MemberRD->isThisDeclarationADefinition()) {
4952  if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4953  return Kind;
4954  }
4955  }
4956 
4957  return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4958 }
4959 
4961  TypedefNameDecl *NewTD) {
4962  if (TagFromDeclSpec->isInvalidDecl())
4963  return;
4964 
4965  // Do nothing if the tag already has a name for linkage purposes.
4966  if (TagFromDeclSpec->hasNameForLinkage())
4967  return;
4968 
4969  // A well-formed anonymous tag must always be a TUK_Definition.
4970  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4971 
4972  // The type must match the tag exactly; no qualifiers allowed.
4973  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4974  Context.getTagDeclType(TagFromDeclSpec))) {
4975  if (getLangOpts().CPlusPlus)
4976  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4977  return;
4978  }
4979 
4980  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4981  // An unnamed class with a typedef name for linkage purposes shall [be
4982  // C-like].
4983  //
4984  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4985  // shouldn't happen, but there are constructs that the language rule doesn't
4986  // disallow for which we can't reasonably avoid computing linkage early.
4987  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4988  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4989  : NonCLikeKind();
4990  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4991  if (NonCLike || ChangesLinkage) {
4992  if (NonCLike.Kind == NonCLikeKind::Invalid)
4993  return;
4994 
4995  unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4996  if (ChangesLinkage) {
4997  // If the linkage changes, we can't accept this as an extension.
4998  if (NonCLike.Kind == NonCLikeKind::None)
4999  DiagID = diag::err_typedef_changes_linkage;
5000  else
5001  DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5002  }
5003 
5004  SourceLocation FixitLoc =
5005  getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5006  llvm::SmallString<40> TextToInsert;
5007  TextToInsert += ' ';
5008  TextToInsert += NewTD->getIdentifier()->getName();
5009 
5010  Diag(FixitLoc, DiagID)
5011  << isa<TypeAliasDecl>(NewTD)
5012  << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5013  if (NonCLike.Kind != NonCLikeKind::None) {
5014  Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5015  << NonCLike.Kind - 1 << NonCLike.Range;
5016  }
5017  Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5018  << NewTD << isa<TypeAliasDecl>(NewTD);
5019 
5020  if (ChangesLinkage)
5021  return;
5022  }
5023 
5024  // Otherwise, set this as the anon-decl typedef for the tag.
5025  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5026 }
5027 
5029  switch (T) {
5030  case DeclSpec::TST_class:
5031  return 0;
5032  case DeclSpec::TST_struct:
5033  return 1;
5035  return 2;
5036  case DeclSpec::TST_union:
5037  return 3;
5038  case DeclSpec::TST_enum:
5039  return 4;
5040  default:
5041  llvm_unreachable("unexpected type specifier");
5042  }
5043 }
5044 
5045 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5046 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5047 /// parameters to cope with template friend declarations.
5049  DeclSpec &DS,
5050  const ParsedAttributesView &DeclAttrs,
5051  MultiTemplateParamsArg TemplateParams,
5052  bool IsExplicitInstantiation,
5053  RecordDecl *&AnonRecord) {
5054  Decl *TagD = nullptr;
5055  TagDecl *Tag = nullptr;
5056  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5061  TagD = DS.getRepAsDecl();
5062 
5063  if (!TagD) // We probably had an error
5064  return nullptr;
5065 
5066  // Note that the above type specs guarantee that the
5067  // type rep is a Decl, whereas in many of the others
5068  // it's a Type.
5069  if (isa<TagDecl>(TagD))
5070  Tag = cast<TagDecl>(TagD);
5071  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5072  Tag = CTD->getTemplatedDecl();
5073  }
5074 
5075  if (Tag) {
5076  handleTagNumbering(Tag, S);
5077  Tag->setFreeStanding();
5078  if (Tag->isInvalidDecl())
5079  return Tag;
5080  }
5081 
5082  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5083  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5084  // or incomplete types shall not be restrict-qualified."
5085  if (TypeQuals & DeclSpec::TQ_restrict)
5086  Diag(DS.getRestrictSpecLoc(),
5087  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5088  << DS.getSourceRange();
5089  }
5090 
5091  if (DS.isInlineSpecified())
5092  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5093  << getLangOpts().CPlusPlus17;
5094 
5095  if (DS.hasConstexprSpecifier()) {
5096  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5097  // and definitions of functions and variables.
5098  // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5099  // the declaration of a function or function template
5100  if (Tag)
5101  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5103  << static_cast<int>(DS.getConstexprSpecifier());
5104  else
5105  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5106  << static_cast<int>(DS.getConstexprSpecifier());
5107  // Don't emit warnings after this error.
5108  return TagD;
5109  }
5110 
5111  DiagnoseFunctionSpecifiers(DS);
5112 
5113  if (DS.isFriendSpecified()) {
5114  // If we're dealing with a decl but not a TagDecl, assume that
5115  // whatever routines created it handled the friendship aspect.
5116  if (TagD && !Tag)
5117  return nullptr;
5118  return ActOnFriendTypeDecl(S, DS, TemplateParams);
5119  }
5120 
5121  const CXXScopeSpec &SS = DS.getTypeSpecScope();
5122  bool IsExplicitSpecialization =
5123  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5124  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5125  !IsExplicitInstantiation && !IsExplicitSpecialization &&
5126  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5127  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5128  // nested-name-specifier unless it is an explicit instantiation
5129  // or an explicit specialization.
5130  //
5131  // FIXME: We allow class template partial specializations here too, per the
5132  // obvious intent of DR1819.
5133  //
5134  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5135  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5137  return nullptr;
5138  }
5139 
5140  // Track whether this decl-specifier declares anything.
5141  bool DeclaresAnything = true;
5142 
5143  // Handle anonymous struct definitions.
5144  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5145  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5147  if (getLangOpts().CPlusPlus ||
5148  Record->getDeclContext()->isRecord()) {
5149  // If CurContext is a DeclContext that can contain statements,
5150  // RecursiveASTVisitor won't visit the decls that
5151  // BuildAnonymousStructOrUnion() will put into CurContext.
5152  // Also store them here so that they can be part of the
5153  // DeclStmt that gets created in this case.
5154  // FIXME: Also return the IndirectFieldDecls created by
5155  // BuildAnonymousStructOr union, for the same reason?
5156  if (CurContext->isFunctionOrMethod())
5157  AnonRecord = Record;
5158  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5159  Context.getPrintingPolicy());
5160  }
5161 
5162  DeclaresAnything = false;
5163  }
5164  }
5165 
5166  // C11 6.7.2.1p2:
5167  // A struct-declaration that does not declare an anonymous structure or
5168  // anonymous union shall contain a struct-declarator-list.
5169  //
5170  // This rule also existed in C89 and C99; the grammar for struct-declaration
5171  // did not permit a struct-declaration without a struct-declarator-list.
5172  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5174  // Check for Microsoft C extension: anonymous struct/union member.
5175  // Handle 2 kinds of anonymous struct/union:
5176  // struct STRUCT;
5177  // union UNION;
5178  // and
5179  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5180  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5181  if ((Tag && Tag->getDeclName()) ||
5183  RecordDecl *Record = nullptr;
5184  if (Tag)
5185  Record = dyn_cast<RecordDecl>(Tag);
5186  else if (const RecordType *RT =
5188  Record = RT->getDecl();
5189  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5190  Record = UT->getDecl();
5191 
5192  if (Record && getLangOpts().MicrosoftExt) {
5193  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5194  << Record->isUnion() << DS.getSourceRange();
5195  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5196  }
5197 
5198  DeclaresAnything = false;
5199  }
5200  }
5201 
5202  // Skip all the checks below if we have a type error.
5203  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5204  (TagD && TagD->isInvalidDecl()))
5205  return TagD;
5206 
5207  if (getLangOpts().CPlusPlus &&
5209  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5210  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5211  !Enum->getIdentifier() && !Enum->isInvalidDecl())
5212  DeclaresAnything = false;
5213 
5214  if (!DS.isMissingDeclaratorOk()) {
5215  // Customize diagnostic for a typedef missing a name.
5217  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5218  << DS.getSourceRange();
5219  else
5220  DeclaresAnything = false;
5221  }
5222 
5223  if (DS.isModulePrivateSpecified() &&
5224  Tag && Tag->getDeclContext()->isFunctionOrMethod())
5225  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5226  << Tag->getTagKind()
5228 
5229  ActOnDocumentableDecl(TagD);
5230 
5231  // C 6.7/2:
5232  // A declaration [...] shall declare at least a declarator [...], a tag,
5233  // or the members of an enumeration.
5234  // C++ [dcl.dcl]p3:
5235  // [If there are no declarators], and except for the declaration of an
5236  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5237  // names into the program, or shall redeclare a name introduced by a
5238  // previous declaration.
5239  if (!DeclaresAnything) {
5240  // In C, we allow this as a (popular) extension / bug. Don't bother
5241  // producing further diagnostics for redundant qualifiers after this.
5242  Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5243  ? diag::err_no_declarators
5244  : diag::ext_no_declarators)
5245  << DS.getSourceRange();
5246  return TagD;
5247  }
5248 
5249  // C++ [dcl.stc]p1:
5250  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5251  // init-declarator-list of the declaration shall not be empty.
5252  // C++ [dcl.fct.spec]p1:
5253  // If a cv-qualifier appears in a decl-specifier-seq, the
5254  // init-declarator-list of the declaration shall not be empty.
5255  //
5256  // Spurious qualifiers here appear to be valid in C.
5257  unsigned DiagID = diag::warn_standalone_specifier;
5258  if (getLangOpts().CPlusPlus)
5259  DiagID = diag::ext_standalone_specifier;
5260 
5261  // Note that a linkage-specification sets a storage class, but
5262  // 'extern "C" struct foo;' is actually valid and not theoretically
5263  // useless.
5264  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5265  if (SCS == DeclSpec::SCS_mutable)
5266  // Since mutable is not a viable storage class specifier in C, there is
5267  // no reason to treat it as an extension. Instead, diagnose as an error.
5268  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5269  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5270  Diag(DS.getStorageClassSpecLoc(), DiagID)
5272  }
5273 
5274  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5275  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5276  << DeclSpec::getSpecifierName(TSCS);
5277  if (DS.getTypeQualifiers()) {
5279  Diag(DS.getConstSpecLoc(), DiagID) << "const";
5281  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5282  // Restrict is covered above.
5284  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5286  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5287  }
5288 
5289  // Warn about ignored type attributes, for example:
5290  // __attribute__((aligned)) struct A;
5291  // Attributes should be placed after tag to apply to type declaration.
5292  if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5293  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5294  if (TypeSpecType == DeclSpec::TST_class ||
5295  TypeSpecType == DeclSpec::TST_struct ||
5296  TypeSpecType == DeclSpec::TST_interface ||
5297  TypeSpecType == DeclSpec::TST_union ||
5298  TypeSpecType == DeclSpec::TST_enum) {
5299  for (const ParsedAttr &AL : DS.getAttributes())
5300  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5301  << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5302  for (const ParsedAttr &AL : DeclAttrs)
5303  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5304  << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5305  }
5306  }
5307 
5308  return TagD;
5309 }
5310 
5311 /// We are trying to inject an anonymous member into the given scope;
5312 /// check if there's an existing declaration that can't be overloaded.
5313 ///
5314 /// \return true if this is a forbidden redeclaration
5315 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5316  Scope *S,
5317  DeclContext *Owner,
5318  DeclarationName Name,
5319  SourceLocation NameLoc,
5320  bool IsUnion) {
5321  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5323  if (!SemaRef.LookupName(R, S)) return false;
5324 
5325  // Pick a representative declaration.
5327  assert(PrevDecl && "Expected a non-null Decl");
5328 
5329  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5330  return false;
5331 
5332  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5333  << IsUnion << Name;
5334  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5335 
5336  return true;
5337 }
5338 
5339 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5340 /// anonymous struct or union AnonRecord into the owning context Owner
5341 /// and scope S. This routine will be invoked just after we realize
5342 /// that an unnamed union or struct is actually an anonymous union or
5343 /// struct, e.g.,
5344 ///
5345 /// @code
5346 /// union {
5347 /// int i;
5348 /// float f;
5349 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5350 /// // f into the surrounding scope.x
5351 /// @endcode
5352 ///
5353 /// This routine is recursive, injecting the names of nested anonymous
5354 /// structs/unions into the owning context and scope as well.
5355 static bool
5357  RecordDecl *AnonRecord, AccessSpecifier AS,
5358  SmallVectorImpl<NamedDecl *> &Chaining) {
5359  bool Invalid = false;
5360 
5361  // Look every FieldDecl and IndirectFieldDecl with a name.
5362  for (auto *D : AnonRecord->decls()) {
5363  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5364  cast<NamedDecl>(D)->getDeclName()) {
5365  ValueDecl *VD = cast<ValueDecl>(D);
5366  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5367  VD->getLocation(),
5368  AnonRecord->isUnion())) {
5369  // C++ [class.union]p2:
5370  // The names of the members of an anonymous union shall be
5371  // distinct from the names of any other entity in the
5372  // scope in which the anonymous union is declared.
5373  Invalid = true;
5374  } else {
5375  // C++ [class.union]p2:
5376  // For the purpose of name lookup, after the anonymous union
5377  // definition, the members of the anonymous union are
5378  // considered to have been defined in the scope in which the
5379  // anonymous union is declared.
5380  unsigned OldChainingSize = Chaining.size();
5381  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5382  Chaining.append(IF->chain_begin(), IF->chain_end());
5383  else
5384  Chaining.push_back(VD);
5385 
5386  assert(Chaining.size() >= 2);
5387  NamedDecl **NamedChain =
5388  new (SemaRef.Context)NamedDecl*[Chaining.size()];
5389  for (unsigned i = 0; i < Chaining.size(); i++)
5390  NamedChain[i] = Chaining[i];
5391 
5393  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5394  VD->getType(), {NamedChain, Chaining.size()});
5395 
5396  for (const auto *Attr : VD->attrs())
5397  IndirectField->addAttr(Attr->clone(SemaRef.Context));
5398 
5399  IndirectField->setAccess(AS);
5400  IndirectField->setImplicit();
5401  SemaRef.PushOnScopeChains(IndirectField, S);
5402 
5403  // That includes picking up the appropriate access specifier.
5404  if (AS != AS_none) IndirectField->setAccess(AS);
5405 
5406  Chaining.resize(OldChainingSize);
5407  }
5408  }
5409  }
5410 
5411  return Invalid;
5412 }
5413 
5414 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5415 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5416 /// illegal input values are mapped to SC_None.
5417 static StorageClass
5419  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5420  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5421  "Parser allowed 'typedef' as storage class VarDecl.");
5422  switch (StorageClassSpec) {
5423  case DeclSpec::SCS_unspecified: return SC_None;
5424  case DeclSpec::SCS_extern:
5425  if (DS.isExternInLinkageSpec())
5426  return SC_None;
5427  return SC_Extern;
5428  case DeclSpec::SCS_static: return SC_Static;
5429  case DeclSpec::SCS_auto: return SC_Auto;
5430  case DeclSpec::SCS_register: return SC_Register;
5432  // Illegal SCSs map to None: error reporting is up to the caller.
5433  case DeclSpec::SCS_mutable: // Fall through.
5434  case DeclSpec::SCS_typedef: return SC_None;
5435  }
5436  llvm_unreachable("unknown storage class specifier");
5437 }
5438 
5440  assert(Record->hasInClassInitializer());
5441 
5442  for (const auto *I : Record->decls()) {
5443  const auto *FD = dyn_cast<FieldDecl>(I);
5444  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5445  FD = IFD->getAnonField();
5446  if (FD && FD->hasInClassInitializer())
5447  return FD->getLocation();
5448  }
5449 
5450  llvm_unreachable("couldn't find in-class initializer");
5451 }
5452 
5454  SourceLocation DefaultInitLoc) {
5455  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5456  return;
5457 
5458  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5459  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5460 }
5461 
5463  CXXRecordDecl *AnonUnion) {
5464  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5465  return;
5466 
5468 }
5469 
5470 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5471 /// anonymous structure or union. Anonymous unions are a C++ feature
5472 /// (C++ [class.union]) and a C11 feature; anonymous structures
5473 /// are a C11 feature and GNU C++ extension.
5475  AccessSpecifier AS,
5476  RecordDecl *Record,
5477  const PrintingPolicy &Policy) {
5478  DeclContext *Owner = Record->getDeclContext();
5479 
5480  // Diagnose whether this anonymous struct/union is an extension.
5481  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5482  Diag(Record->getLocation(), diag::ext_anonymous_union);
5483  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5484  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5485  else if (!Record->isUnion() && !getLangOpts().C11)
5486  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5487 
5488  // C and C++ require different kinds of checks for anonymous
5489  // structs/unions.
5490  bool Invalid = false;
5491  if (getLangOpts().CPlusPlus) {
5492  const char *PrevSpec = nullptr;
5493  if (Record->isUnion()) {
5494  // C++ [class.union]p6:
5495  // C++17 [class.union.anon]p2:
5496  // Anonymous unions declared in a named namespace or in the
5497  // global namespace shall be declared static.
5498  unsigned DiagID;
5499  DeclContext *OwnerScope = Owner->getRedeclContext();
5501  (OwnerScope->isTranslationUnit() ||
5502  (OwnerScope->isNamespace() &&
5503  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5504  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5505  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5506 
5507  // Recover by adding 'static'.
5509  PrevSpec, DiagID, Policy);
5510  }
5511  // C++ [class.union]p6:
5512  // A storage class is not allowed in a declaration of an
5513  // anonymous union in a class scope.
5515  isa<RecordDecl>(Owner)) {
5517  diag::err_anonymous_union_with_storage_spec)
5519 
5520  // Recover by removing the storage specifier.
5521  DS.