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