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