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