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