clang  8.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 
1931  switch (Error) {
1932  case ASTContext::GE_None:
1933  return "";
1935  return "stdio.h";
1937  return "setjmp.h";
1939  return "ucontext.h";
1940  }
1941  llvm_unreachable("unhandled error kind");
1942 }
1943 
1944 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1945 /// file scope. lazily create a decl for it. ForRedeclaration is true
1946 /// if we're creating this built-in in anticipation of redeclaring the
1947 /// built-in.
1949  Scope *S, bool ForRedeclaration,
1950  SourceLocation Loc) {
1951  LookupPredefedObjCSuperType(*this, S, II);
1952 
1954  QualType R = Context.GetBuiltinType(ID, Error);
1955  if (Error) {
1956  if (ForRedeclaration)
1957  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1958  << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1959  return nullptr;
1960  }
1961 
1962  if (!ForRedeclaration &&
1963  (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1964  Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1965  Diag(Loc, diag::ext_implicit_lib_function_decl)
1966  << Context.BuiltinInfo.getName(ID) << R;
1967  if (Context.BuiltinInfo.getHeaderName(ID) &&
1968  !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1969  Diag(Loc, diag::note_include_header_or_declare)
1970  << Context.BuiltinInfo.getHeaderName(ID)
1971  << Context.BuiltinInfo.getName(ID);
1972  }
1973 
1974  if (R.isNull())
1975  return nullptr;
1976 
1978  if (getLangOpts().CPlusPlus) {
1979  LinkageSpecDecl *CLinkageDecl =
1980  LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1981  LinkageSpecDecl::lang_c, false);
1982  CLinkageDecl->setImplicit();
1983  Parent->addDecl(CLinkageDecl);
1984  Parent = CLinkageDecl;
1985  }
1986 
1987  FunctionDecl *New = FunctionDecl::Create(Context,
1988  Parent,
1989  Loc, Loc, II, R, /*TInfo=*/nullptr,
1990  SC_Extern,
1991  false,
1992  R->isFunctionProtoType());
1993  New->setImplicit();
1994 
1995  // Create Decl objects for each parameter, adding them to the
1996  // FunctionDecl.
1997  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1999  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2000  ParmVarDecl *parm =
2002  nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2003  SC_None, nullptr);
2004  parm->setScopeInfo(0, i);
2005  Params.push_back(parm);
2006  }
2007  New->setParams(Params);
2008  }
2009 
2010  AddKnownFunctionAttributes(New);
2011  RegisterLocallyScopedExternCDecl(New, S);
2012 
2013  // TUScope is the translation-unit scope to insert this function into.
2014  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2015  // relate Scopes to DeclContexts, and probably eliminate CurContext
2016  // entirely, but we're not there yet.
2017  DeclContext *SavedContext = CurContext;
2018  CurContext = Parent;
2019  PushOnScopeChains(New, TUScope);
2020  CurContext = SavedContext;
2021  return New;
2022 }
2023 
2024 /// Typedef declarations don't have linkage, but they still denote the same
2025 /// entity if their types are the same.
2026 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2027 /// isSameEntity.
2031  // This is only interesting when modules are enabled.
2032  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2033  return;
2034 
2035  // Empty sets are uninteresting.
2036  if (Previous.empty())
2037  return;
2038 
2039  LookupResult::Filter Filter = Previous.makeFilter();
2040  while (Filter.hasNext()) {
2041  NamedDecl *Old = Filter.next();
2042 
2043  // Non-hidden declarations are never ignored.
2044  if (S.isVisible(Old))
2045  continue;
2046 
2047  // Declarations of the same entity are not ignored, even if they have
2048  // different linkages.
2049  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2050  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2051  Decl->getUnderlyingType()))
2052  continue;
2053 
2054  // If both declarations give a tag declaration a typedef name for linkage
2055  // purposes, then they declare the same entity.
2056  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2058  continue;
2059  }
2060 
2061  Filter.erase();
2062  }
2063 
2064  Filter.done();
2065 }
2066 
2068  QualType OldType;
2069  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2070  OldType = OldTypedef->getUnderlyingType();
2071  else
2072  OldType = Context.getTypeDeclType(Old);
2073  QualType NewType = New->getUnderlyingType();
2074 
2075  if (NewType->isVariablyModifiedType()) {
2076  // Must not redefine a typedef with a variably-modified type.
2077  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2078  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2079  << Kind << NewType;
2080  if (Old->getLocation().isValid())
2081  notePreviousDefinition(Old, New->getLocation());
2082  New->setInvalidDecl();
2083  return true;
2084  }
2085 
2086  if (OldType != NewType &&
2087  !OldType->isDependentType() &&
2088  !NewType->isDependentType() &&
2089  !Context.hasSameType(OldType, NewType)) {
2090  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2091  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2092  << Kind << NewType << OldType;
2093  if (Old->getLocation().isValid())
2094  notePreviousDefinition(Old, New->getLocation());
2095  New->setInvalidDecl();
2096  return true;
2097  }
2098  return false;
2099 }
2100 
2101 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2102 /// same name and scope as a previous declaration 'Old'. Figure out
2103 /// how to resolve this situation, merging decls or emitting
2104 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2105 ///
2107  LookupResult &OldDecls) {
2108  // If the new decl is known invalid already, don't bother doing any
2109  // merging checks.
2110  if (New->isInvalidDecl()) return;
2111 
2112  // Allow multiple definitions for ObjC built-in typedefs.
2113  // FIXME: Verify the underlying types are equivalent!
2114  if (getLangOpts().ObjC) {
2115  const IdentifierInfo *TypeID = New->getIdentifier();
2116  switch (TypeID->getLength()) {
2117  default: break;
2118  case 2:
2119  {
2120  if (!TypeID->isStr("id"))
2121  break;
2122  QualType T = New->getUnderlyingType();
2123  if (!T->isPointerType())
2124  break;
2125  if (!T->isVoidPointerType()) {
2126  QualType PT = T->getAs<PointerType>()->getPointeeType();
2127  if (!PT->isStructureType())
2128  break;
2129  }
2130  Context.setObjCIdRedefinitionType(T);
2131  // Install the built-in type for 'id', ignoring the current definition.
2132  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2133  return;
2134  }
2135  case 5:
2136  if (!TypeID->isStr("Class"))
2137  break;
2139  // Install the built-in type for 'Class', ignoring the current definition.
2140  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2141  return;
2142  case 3:
2143  if (!TypeID->isStr("SEL"))
2144  break;
2146  // Install the built-in type for 'SEL', ignoring the current definition.
2147  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2148  return;
2149  }
2150  // Fall through - the typedef name was not a builtin type.
2151  }
2152 
2153  // Verify the old decl was also a type.
2154  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2155  if (!Old) {
2156  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2157  << New->getDeclName();
2158 
2159  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2160  if (OldD->getLocation().isValid())
2161  notePreviousDefinition(OldD, New->getLocation());
2162 
2163  return New->setInvalidDecl();
2164  }
2165 
2166  // If the old declaration is invalid, just give up here.
2167  if (Old->isInvalidDecl())
2168  return New->setInvalidDecl();
2169 
2170  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2171  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2172  auto *NewTag = New->getAnonDeclWithTypedefName();
2173  NamedDecl *Hidden = nullptr;
2174  if (OldTag && NewTag &&
2175  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2176  !hasVisibleDefinition(OldTag, &Hidden)) {
2177  // There is a definition of this tag, but it is not visible. Use it
2178  // instead of our tag.
2179  New->setTypeForDecl(OldTD->getTypeForDecl());
2180  if (OldTD->isModed())
2181  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2182  OldTD->getUnderlyingType());
2183  else
2184  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2185 
2186  // Make the old tag definition visible.
2187  makeMergedDefinitionVisible(Hidden);
2188 
2189  // If this was an unscoped enumeration, yank all of its enumerators
2190  // out of the scope.
2191  if (isa<EnumDecl>(NewTag)) {
2192  Scope *EnumScope = getNonFieldDeclScope(S);
2193  for (auto *D : NewTag->decls()) {
2194  auto *ED = cast<EnumConstantDecl>(D);
2195  assert(EnumScope->isDeclScope(ED));
2196  EnumScope->RemoveDecl(ED);
2197  IdResolver.RemoveDecl(ED);
2198  ED->getLexicalDeclContext()->removeDecl(ED);
2199  }
2200  }
2201  }
2202  }
2203 
2204  // If the typedef types are not identical, reject them in all languages and
2205  // with any extensions enabled.
2206  if (isIncompatibleTypedef(Old, New))
2207  return;
2208 
2209  // The types match. Link up the redeclaration chain and merge attributes if
2210  // the old declaration was a typedef.
2211  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2212  New->setPreviousDecl(Typedef);
2213  mergeDeclAttributes(New, Old);
2214  }
2215 
2216  if (getLangOpts().MicrosoftExt)
2217  return;
2218 
2219  if (getLangOpts().CPlusPlus) {
2220  // C++ [dcl.typedef]p2:
2221  // In a given non-class scope, a typedef specifier can be used to
2222  // redefine the name of any type declared in that scope to refer
2223  // to the type to which it already refers.
2224  if (!isa<CXXRecordDecl>(CurContext))
2225  return;
2226 
2227  // C++0x [dcl.typedef]p4:
2228  // In a given class scope, a typedef specifier can be used to redefine
2229  // any class-name declared in that scope that is not also a typedef-name
2230  // to refer to the type to which it already refers.
2231  //
2232  // This wording came in via DR424, which was a correction to the
2233  // wording in DR56, which accidentally banned code like:
2234  //
2235  // struct S {
2236  // typedef struct A { } A;
2237  // };
2238  //
2239  // in the C++03 standard. We implement the C++0x semantics, which
2240  // allow the above but disallow
2241  //
2242  // struct S {
2243  // typedef int I;
2244  // typedef int I;
2245  // };
2246  //
2247  // since that was the intent of DR56.
2248  if (!isa<TypedefNameDecl>(Old))
2249  return;
2250 
2251  Diag(New->getLocation(), diag::err_redefinition)
2252  << New->getDeclName();
2253  notePreviousDefinition(Old, New->getLocation());
2254  return New->setInvalidDecl();
2255  }
2256 
2257  // Modules always permit redefinition of typedefs, as does C11.
2258  if (getLangOpts().Modules || getLangOpts().C11)
2259  return;
2260 
2261  // If we have a redefinition of a typedef in C, emit a warning. This warning
2262  // is normally mapped to an error, but can be controlled with
2263  // -Wtypedef-redefinition. If either the original or the redefinition is
2264  // in a system header, don't emit this for compatibility with GCC.
2265  if (getDiagnostics().getSuppressSystemWarnings() &&
2266  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2267  (Old->isImplicit() ||
2268  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2269  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2270  return;
2271 
2272  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2273  << New->getDeclName();
2274  notePreviousDefinition(Old, New->getLocation());
2275 }
2276 
2277 /// DeclhasAttr - returns true if decl Declaration already has the target
2278 /// attribute.
2279 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2280  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2281  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2282  for (const auto *i : D->attrs())
2283  if (i->getKind() == A->getKind()) {
2284  if (Ann) {
2285  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2286  return true;
2287  continue;
2288  }
2289  // FIXME: Don't hardcode this check
2290  if (OA && isa<OwnershipAttr>(i))
2291  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2292  return true;
2293  }
2294 
2295  return false;
2296 }
2297 
2299  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2300  return VD->isThisDeclarationADefinition();
2301  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2302  return TD->isCompleteDefinition() || TD->isBeingDefined();
2303  return true;
2304 }
2305 
2306 /// Merge alignment attributes from \p Old to \p New, taking into account the
2307 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2308 ///
2309 /// \return \c true if any attributes were added to \p New.
2310 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2311  // Look for alignas attributes on Old, and pick out whichever attribute
2312  // specifies the strictest alignment requirement.
2313  AlignedAttr *OldAlignasAttr = nullptr;
2314  AlignedAttr *OldStrictestAlignAttr = nullptr;
2315  unsigned OldAlign = 0;
2316  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2317  // FIXME: We have no way of representing inherited dependent alignments
2318  // in a case like:
2319  // template<int A, int B> struct alignas(A) X;
2320  // template<int A, int B> struct alignas(B) X {};
2321  // For now, we just ignore any alignas attributes which are not on the
2322  // definition in such a case.
2323  if (I->isAlignmentDependent())
2324  return false;
2325 
2326  if (I->isAlignas())
2327  OldAlignasAttr = I;
2328 
2329  unsigned Align = I->getAlignment(S.Context);
2330  if (Align > OldAlign) {
2331  OldAlign = Align;
2332  OldStrictestAlignAttr = I;
2333  }
2334  }
2335 
2336  // Look for alignas attributes on New.
2337  AlignedAttr *NewAlignasAttr = nullptr;
2338  unsigned NewAlign = 0;
2339  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2340  if (I->isAlignmentDependent())
2341  return false;
2342 
2343  if (I->isAlignas())
2344  NewAlignasAttr = I;
2345 
2346  unsigned Align = I->getAlignment(S.Context);
2347  if (Align > NewAlign)
2348  NewAlign = Align;
2349  }
2350 
2351  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2352  // Both declarations have 'alignas' attributes. We require them to match.
2353  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2354  // fall short. (If two declarations both have alignas, they must both match
2355  // every definition, and so must match each other if there is a definition.)
2356 
2357  // If either declaration only contains 'alignas(0)' specifiers, then it
2358  // specifies the natural alignment for the type.
2359  if (OldAlign == 0 || NewAlign == 0) {
2360  QualType Ty;
2361  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2362  Ty = VD->getType();
2363  else
2364  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2365 
2366  if (OldAlign == 0)
2367  OldAlign = S.Context.getTypeAlign(Ty);
2368  if (NewAlign == 0)
2369  NewAlign = S.Context.getTypeAlign(Ty);
2370  }
2371 
2372  if (OldAlign != NewAlign) {
2373  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2374  << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2375  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2376  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2377  }
2378  }
2379 
2380  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2381  // C++11 [dcl.align]p6:
2382  // if any declaration of an entity has an alignment-specifier,
2383  // every defining declaration of that entity shall specify an
2384  // equivalent alignment.
2385  // C11 6.7.5/7:
2386  // If the definition of an object does not have an alignment
2387  // specifier, any other declaration of that object shall also
2388  // have no alignment specifier.
2389  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2390  << OldAlignasAttr;
2391  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2392  << OldAlignasAttr;
2393  }
2394 
2395  bool AnyAdded = false;
2396 
2397  // Ensure we have an attribute representing the strictest alignment.
2398  if (OldAlign > NewAlign) {
2399  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2400  Clone->setInherited(true);
2401  New->addAttr(Clone);
2402  AnyAdded = true;
2403  }
2404 
2405  // Ensure we have an alignas attribute if the old declaration had one.
2406  if (OldAlignasAttr && !NewAlignasAttr &&
2407  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2408  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2409  Clone->setInherited(true);
2410  New->addAttr(Clone);
2411  AnyAdded = true;
2412  }
2413 
2414  return AnyAdded;
2415 }
2416 
2417 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2418  const InheritableAttr *Attr,
2420  // This function copies an attribute Attr from a previous declaration to the
2421  // new declaration D if the new declaration doesn't itself have that attribute
2422  // yet or if that attribute allows duplicates.
2423  // If you're adding a new attribute that requires logic different from
2424  // "use explicit attribute on decl if present, else use attribute from
2425  // previous decl", for example if the attribute needs to be consistent
2426  // between redeclarations, you need to call a custom merge function here.
2427  InheritableAttr *NewAttr = nullptr;
2428  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2429  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2430  NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2431  AA->isImplicit(), AA->getIntroduced(),
2432  AA->getDeprecated(),
2433  AA->getObsoleted(), AA->getUnavailable(),
2434  AA->getMessage(), AA->getStrict(),
2435  AA->getReplacement(), AMK,
2436  AttrSpellingListIndex);
2437  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2438  NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2439  AttrSpellingListIndex);
2440  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2441  NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2442  AttrSpellingListIndex);
2443  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2444  NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2445  AttrSpellingListIndex);
2446  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2447  NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2448  AttrSpellingListIndex);
2449  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2450  NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2451  FA->getFormatIdx(), FA->getFirstArg(),
2452  AttrSpellingListIndex);
2453  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2454  NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2455  AttrSpellingListIndex);
2456  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2457  NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2458  AttrSpellingListIndex);
2459  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2460  NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2461  AttrSpellingListIndex,
2462  IA->getSemanticSpelling());
2463  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2464  NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2465  &S.Context.Idents.get(AA->getSpelling()),
2466  AttrSpellingListIndex);
2467  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2468  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2469  isa<CUDAGlobalAttr>(Attr))) {
2470  // CUDA target attributes are part of function signature for
2471  // overloading purposes and must not be merged.
2472  return false;
2473  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2474  NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2475  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2476  NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2477  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2478  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2479  else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2480  NewAttr = S.mergeCommonAttr(D, *CommonA);
2481  else if (isa<AlignedAttr>(Attr))
2482  // AlignedAttrs are handled separately, because we need to handle all
2483  // such attributes on a declaration at the same time.
2484  NewAttr = nullptr;
2485  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2486  (AMK == Sema::AMK_Override ||
2488  NewAttr = nullptr;
2489  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2490  NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2491  UA->getGuid());
2492  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2493  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2494 
2495  if (NewAttr) {
2496  NewAttr->setInherited(true);
2497  D->addAttr(NewAttr);
2498  if (isa<MSInheritanceAttr>(NewAttr))
2499  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2500  return true;
2501  }
2502 
2503  return false;
2504 }
2505 
2506 static const NamedDecl *getDefinition(const Decl *D) {
2507  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2508  return TD->getDefinition();
2509  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2510  const VarDecl *Def = VD->getDefinition();
2511  if (Def)
2512  return Def;
2513  return VD->getActingDefinition();
2514  }
2515  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2516  return FD->getDefinition();
2517  return nullptr;
2518 }
2519 
2520 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2521  for (const auto *Attribute : D->attrs())
2522  if (Attribute->getKind() == Kind)
2523  return true;
2524  return false;
2525 }
2526 
2527 /// checkNewAttributesAfterDef - If we already have a definition, check that
2528 /// there are no new attributes in this declaration.
2529 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2530  if (!New->hasAttrs())
2531  return;
2532 
2533  const NamedDecl *Def = getDefinition(Old);
2534  if (!Def || Def == New)
2535  return;
2536 
2537  AttrVec &NewAttributes = New->getAttrs();
2538  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2539  const Attr *NewAttribute = NewAttributes[I];
2540 
2541  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2542  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2543  Sema::SkipBodyInfo SkipBody;
2544  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2545 
2546  // If we're skipping this definition, drop the "alias" attribute.
2547  if (SkipBody.ShouldSkip) {
2548  NewAttributes.erase(NewAttributes.begin() + I);
2549  --E;
2550  continue;
2551  }
2552  } else {
2553  VarDecl *VD = cast<VarDecl>(New);
2554  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2556  ? diag::err_alias_after_tentative
2557  : diag::err_redefinition;
2558  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2559  if (Diag == diag::err_redefinition)
2560  S.notePreviousDefinition(Def, VD->getLocation());
2561  else
2562  S.Diag(Def->getLocation(), diag::note_previous_definition);
2563  VD->setInvalidDecl();
2564  }
2565  ++I;
2566  continue;
2567  }
2568 
2569  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2570  // Tentative definitions are only interesting for the alias check above.
2571  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2572  ++I;
2573  continue;
2574  }
2575  }
2576 
2577  if (hasAttribute(Def, NewAttribute->getKind())) {
2578  ++I;
2579  continue; // regular attr merging will take care of validating this.
2580  }
2581 
2582  if (isa<C11NoReturnAttr>(NewAttribute)) {
2583  // C's _Noreturn is allowed to be added to a function after it is defined.
2584  ++I;
2585  continue;
2586  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2587  if (AA->isAlignas()) {
2588  // C++11 [dcl.align]p6:
2589  // if any declaration of an entity has an alignment-specifier,
2590  // every defining declaration of that entity shall specify an
2591  // equivalent alignment.
2592  // C11 6.7.5/7:
2593  // If the definition of an object does not have an alignment
2594  // specifier, any other declaration of that object shall also
2595  // have no alignment specifier.
2596  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2597  << AA;
2598  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2599  << AA;
2600  NewAttributes.erase(NewAttributes.begin() + I);
2601  --E;
2602  continue;
2603  }
2604  }
2605 
2606  S.Diag(NewAttribute->getLocation(),
2607  diag::warn_attribute_precede_definition);
2608  S.Diag(Def->getLocation(), diag::note_previous_definition);
2609  NewAttributes.erase(NewAttributes.begin() + I);
2610  --E;
2611  }
2612 }
2613 
2614 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2616  AvailabilityMergeKind AMK) {
2617  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2618  UsedAttr *NewAttr = OldAttr->clone(Context);
2619  NewAttr->setInherited(true);
2620  New->addAttr(NewAttr);
2621  }
2622 
2623  if (!Old->hasAttrs() && !New->hasAttrs())
2624  return;
2625 
2626  // Attributes declared post-definition are currently ignored.
2627  checkNewAttributesAfterDef(*this, New, Old);
2628 
2629  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2630  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2631  if (OldA->getLabel() != NewA->getLabel()) {
2632  // This redeclaration changes __asm__ label.
2633  Diag(New->getLocation(), diag::err_different_asm_label);
2634  Diag(OldA->getLocation(), diag::note_previous_declaration);
2635  }
2636  } else if (Old->isUsed()) {
2637  // This redeclaration adds an __asm__ label to a declaration that has
2638  // already been ODR-used.
2639  Diag(New->getLocation(), diag::err_late_asm_label_name)
2640  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2641  }
2642  }
2643 
2644  // Re-declaration cannot add abi_tag's.
2645  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2646  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2647  for (const auto &NewTag : NewAbiTagAttr->tags()) {
2648  if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2649  NewTag) == OldAbiTagAttr->tags_end()) {
2650  Diag(NewAbiTagAttr->getLocation(),
2651  diag::err_new_abi_tag_on_redeclaration)
2652  << NewTag;
2653  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2654  }
2655  }
2656  } else {
2657  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2658  Diag(Old->getLocation(), diag::note_previous_declaration);
2659  }
2660  }
2661 
2662  // This redeclaration adds a section attribute.
2663  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2664  if (auto *VD = dyn_cast<VarDecl>(New)) {
2665  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2666  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2667  Diag(Old->getLocation(), diag::note_previous_declaration);
2668  }
2669  }
2670  }
2671 
2672  // Redeclaration adds code-seg attribute.
2673  const auto *NewCSA = New->getAttr<CodeSegAttr>();
2674  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2675  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2676  Diag(New->getLocation(), diag::warn_mismatched_section)
2677  << 0 /*codeseg*/;
2678  Diag(Old->getLocation(), diag::note_previous_declaration);
2679  }
2680 
2681  if (!Old->hasAttrs())
2682  return;
2683 
2684  bool foundAny = New->hasAttrs();
2685 
2686  // Ensure that any moving of objects within the allocated map is done before
2687  // we process them.
2688  if (!foundAny) New->setAttrs(AttrVec());
2689 
2690  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2691  // Ignore deprecated/unavailable/availability attributes if requested.
2692  AvailabilityMergeKind LocalAMK = AMK_None;
2693  if (isa<DeprecatedAttr>(I) ||
2694  isa<UnavailableAttr>(I) ||
2695  isa<AvailabilityAttr>(I)) {
2696  switch (AMK) {
2697  case AMK_None:
2698  continue;
2699 
2700  case AMK_Redeclaration:
2701  case AMK_Override:
2702  case AMK_ProtocolImplementation:
2703  LocalAMK = AMK;
2704  break;
2705  }
2706  }
2707 
2708  // Already handled.
2709  if (isa<UsedAttr>(I))
2710  continue;
2711 
2712  if (mergeDeclAttribute(*this, New, I, LocalAMK))
2713  foundAny = true;
2714  }
2715 
2716  if (mergeAlignedAttrs(*this, New, Old))
2717  foundAny = true;
2718 
2719  if (!foundAny) New->dropAttrs();
2720 }
2721 
2722 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2723 /// to the new one.
2725  const ParmVarDecl *oldDecl,
2726  Sema &S) {
2727  // C++11 [dcl.attr.depend]p2:
2728  // The first declaration of a function shall specify the
2729  // carries_dependency attribute for its declarator-id if any declaration
2730  // of the function specifies the carries_dependency attribute.
2731  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2732  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2733  S.Diag(CDA->getLocation(),
2734  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2735  // Find the first declaration of the parameter.
2736  // FIXME: Should we build redeclaration chains for function parameters?
2737  const FunctionDecl *FirstFD =
2738  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2739  const ParmVarDecl *FirstVD =
2740  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2741  S.Diag(FirstVD->getLocation(),
2742  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2743  }
2744 
2745  if (!oldDecl->hasAttrs())
2746  return;
2747 
2748  bool foundAny = newDecl->hasAttrs();
2749 
2750  // Ensure that any moving of objects within the allocated map is
2751  // done before we process them.
2752  if (!foundAny) newDecl->setAttrs(AttrVec());
2753 
2754  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2755  if (!DeclHasAttr(newDecl, I)) {
2756  InheritableAttr *newAttr =
2757  cast<InheritableParamAttr>(I->clone(S.Context));
2758  newAttr->setInherited(true);
2759  newDecl->addAttr(newAttr);
2760  foundAny = true;
2761  }
2762  }
2763 
2764  if (!foundAny) newDecl->dropAttrs();
2765 }
2766 
2767 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2768  const ParmVarDecl *OldParam,
2769  Sema &S) {
2770  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2771  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2772  if (*Oldnullability != *Newnullability) {
2773  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2775  *Newnullability,
2777  != 0))
2779  *Oldnullability,
2781  != 0));
2782  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2783  }
2784  } else {
2785  QualType NewT = NewParam->getType();
2786  NewT = S.Context.getAttributedType(
2787  AttributedType::getNullabilityAttrKind(*Oldnullability),
2788  NewT, NewT);
2789  NewParam->setType(NewT);
2790  }
2791  }
2792 }
2793 
2794 namespace {
2795 
2796 /// Used in MergeFunctionDecl to keep track of function parameters in
2797 /// C.
2798 struct GNUCompatibleParamWarning {
2799  ParmVarDecl *OldParm;
2800  ParmVarDecl *NewParm;
2801  QualType PromotedType;
2802 };
2803 
2804 } // end anonymous namespace
2805 
2806 /// getSpecialMember - get the special member enum for a method.
2808  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2809  if (Ctor->isDefaultConstructor())
2811 
2812  if (Ctor->isCopyConstructor())
2813  return Sema::CXXCopyConstructor;
2814 
2815  if (Ctor->isMoveConstructor())
2816  return Sema::CXXMoveConstructor;
2817  } else if (isa<CXXDestructorDecl>(MD)) {
2818  return Sema::CXXDestructor;
2819  } else if (MD->isCopyAssignmentOperator()) {
2820  return Sema::CXXCopyAssignment;
2821  } else if (MD->isMoveAssignmentOperator()) {
2822  return Sema::CXXMoveAssignment;
2823  }
2824 
2825  return Sema::CXXInvalid;
2826 }
2827 
2828 // Determine whether the previous declaration was a definition, implicit
2829 // declaration, or a declaration.
2830 template <typename T>
2831 static std::pair<diag::kind, SourceLocation>
2832 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2833  diag::kind PrevDiag;
2834  SourceLocation OldLocation = Old->getLocation();
2835  if (Old->isThisDeclarationADefinition())
2836  PrevDiag = diag::note_previous_definition;
2837  else if (Old->isImplicit()) {
2838  PrevDiag = diag::note_previous_implicit_declaration;
2839  if (OldLocation.isInvalid())
2840  OldLocation = New->getLocation();
2841  } else
2842  PrevDiag = diag::note_previous_declaration;
2843  return std::make_pair(PrevDiag, OldLocation);
2844 }
2845 
2846 /// canRedefineFunction - checks if a function can be redefined. Currently,
2847 /// only extern inline functions can be redefined, and even then only in
2848 /// GNU89 mode.
2849 static bool canRedefineFunction(const FunctionDecl *FD,
2850  const LangOptions& LangOpts) {
2851  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2852  !LangOpts.CPlusPlus &&
2853  FD->isInlineSpecified() &&
2854  FD->getStorageClass() == SC_Extern);
2855 }
2856 
2858  const AttributedType *AT = T->getAs<AttributedType>();
2859  while (AT && !AT->isCallingConv())
2860  AT = AT->getModifiedType()->getAs<AttributedType>();
2861  return AT;
2862 }
2863 
2864 template <typename T>
2865 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2866  const DeclContext *DC = Old->getDeclContext();
2867  if (DC->isRecord())
2868  return false;
2869 
2870  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2871  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2872  return true;
2873  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2874  return true;
2875  return false;
2876 }
2877 
2878 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2879 static bool isExternC(VarTemplateDecl *) { return false; }
2880 
2881 /// Check whether a redeclaration of an entity introduced by a
2882 /// using-declaration is valid, given that we know it's not an overload
2883 /// (nor a hidden tag declaration).
2884 template<typename ExpectedDecl>
2886  ExpectedDecl *New) {
2887  // C++11 [basic.scope.declarative]p4:
2888  // Given a set of declarations in a single declarative region, each of
2889  // which specifies the same unqualified name,
2890  // -- they shall all refer to the same entity, or all refer to functions
2891  // and function templates; or
2892  // -- exactly one declaration shall declare a class name or enumeration
2893  // name that is not a typedef name and the other declarations shall all
2894  // refer to the same variable or enumerator, or all refer to functions
2895  // and function templates; in this case the class name or enumeration
2896  // name is hidden (3.3.10).
2897 
2898  // C++11 [namespace.udecl]p14:
2899  // If a function declaration in namespace scope or block scope has the
2900  // same name and the same parameter-type-list as a function introduced
2901  // by a using-declaration, and the declarations do not declare the same
2902  // function, the program is ill-formed.
2903 
2904  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2905  if (Old &&
2906  !Old->getDeclContext()->getRedeclContext()->Equals(
2907  New->getDeclContext()->getRedeclContext()) &&
2908  !(isExternC(Old) && isExternC(New)))
2909  Old = nullptr;
2910 
2911  if (!Old) {
2912  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2913  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2914  S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2915  return true;
2916  }
2917  return false;
2918 }
2919 
2921  const FunctionDecl *B) {
2922  assert(A->getNumParams() == B->getNumParams());
2923 
2924  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2925  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2926  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2927  if (AttrA == AttrB)
2928  return true;
2929  return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2930  };
2931 
2932  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2933 }
2934 
2935 /// If necessary, adjust the semantic declaration context for a qualified
2936 /// declaration to name the correct inline namespace within the qualifier.
2938  DeclaratorDecl *OldD) {
2939  // The only case where we need to update the DeclContext is when
2940  // redeclaration lookup for a qualified name finds a declaration
2941  // in an inline namespace within the context named by the qualifier:
2942  //
2943  // inline namespace N { int f(); }
2944  // int ::f(); // Sema DC needs adjusting from :: to N::.
2945  //
2946  // For unqualified declarations, the semantic context *can* change
2947  // along the redeclaration chain (for local extern declarations,
2948  // extern "C" declarations, and friend declarations in particular).
2949  if (!NewD->getQualifier())
2950  return;
2951 
2952  // NewD is probably already in the right context.
2953  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2954  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2955  if (NamedDC->Equals(SemaDC))
2956  return;
2957 
2958  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2959  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2960  "unexpected context for redeclaration");
2961 
2962  auto *LexDC = NewD->getLexicalDeclContext();
2963  auto FixSemaDC = [=](NamedDecl *D) {
2964  if (!D)
2965  return;
2966  D->setDeclContext(SemaDC);
2967  D->setLexicalDeclContext(LexDC);
2968  };
2969 
2970  FixSemaDC(NewD);
2971  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2972  FixSemaDC(FD->getDescribedFunctionTemplate());
2973  else if (auto *VD = dyn_cast<VarDecl>(NewD))
2974  FixSemaDC(VD->getDescribedVarTemplate());
2975 }
2976 
2977 /// MergeFunctionDecl - We just parsed a function 'New' from
2978 /// declarator D which has the same name and scope as a previous
2979 /// declaration 'Old'. Figure out how to resolve this situation,
2980 /// merging decls or emitting diagnostics as appropriate.
2981 ///
2982 /// In C++, New and Old must be declarations that are not
2983 /// overloaded. Use IsOverload to determine whether New and Old are
2984 /// overloaded, and to select the Old declaration that New should be
2985 /// merged with.
2986 ///
2987 /// Returns true if there was an error, false otherwise.
2989  Scope *S, bool MergeTypeWithOld) {
2990  // Verify the old decl was also a function.
2991  FunctionDecl *Old = OldD->getAsFunction();
2992  if (!Old) {
2993  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2994  if (New->getFriendObjectKind()) {
2995  Diag(New->getLocation(), diag::err_using_decl_friend);
2996  Diag(Shadow->getTargetDecl()->getLocation(),
2997  diag::note_using_decl_target);
2998  Diag(Shadow->getUsingDecl()->getLocation(),
2999  diag::note_using_decl) << 0;
3000  return true;
3001  }
3002 
3003  // Check whether the two declarations might declare the same function.
3004  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3005  return true;
3006  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3007  } else {
3008  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3009  << New->getDeclName();
3010  notePreviousDefinition(OldD, New->getLocation());
3011  return true;
3012  }
3013  }
3014 
3015  // If the old declaration is invalid, just give up here.
3016  if (Old->isInvalidDecl())
3017  return true;
3018 
3019  // Disallow redeclaration of some builtins.
3020  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3021  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3022  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3023  << Old << Old->getType();
3024  return true;
3025  }
3026 
3027  diag::kind PrevDiag;
3028  SourceLocation OldLocation;
3029  std::tie(PrevDiag, OldLocation) =
3031 
3032  // Don't complain about this if we're in GNU89 mode and the old function
3033  // is an extern inline function.
3034  // Don't complain about specializations. They are not supposed to have
3035  // storage classes.
3036  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3037  New->getStorageClass() == SC_Static &&
3038  Old->hasExternalFormalLinkage() &&
3040  !canRedefineFunction(Old, getLangOpts())) {
3041  if (getLangOpts().MicrosoftExt) {
3042  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3043  Diag(OldLocation, PrevDiag);
3044  } else {
3045  Diag(New->getLocation(), diag::err_static_non_static) << New;
3046  Diag(OldLocation, PrevDiag);
3047  return true;
3048  }
3049  }
3050 
3051  if (New->hasAttr<InternalLinkageAttr>() &&
3052  !Old->hasAttr<InternalLinkageAttr>()) {
3053  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3054  << New->getDeclName();
3055  notePreviousDefinition(Old, New->getLocation());
3056  New->dropAttr<InternalLinkageAttr>();
3057  }
3058 
3059  if (CheckRedeclarationModuleOwnership(New, Old))
3060  return true;
3061 
3062  if (!getLangOpts().CPlusPlus) {
3063  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3064  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3065  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3066  << New << OldOvl;
3067 
3068  // Try our best to find a decl that actually has the overloadable
3069  // attribute for the note. In most cases (e.g. programs with only one
3070  // broken declaration/definition), this won't matter.
3071  //
3072  // FIXME: We could do this if we juggled some extra state in
3073  // OverloadableAttr, rather than just removing it.
3074  const Decl *DiagOld = Old;
3075  if (OldOvl) {
3076  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3077  const auto *A = D->getAttr<OverloadableAttr>();
3078  return A && !A->isImplicit();
3079  });
3080  // If we've implicitly added *all* of the overloadable attrs to this
3081  // chain, emitting a "previous redecl" note is pointless.
3082  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3083  }
3084 
3085  if (DiagOld)
3086  Diag(DiagOld->getLocation(),
3087  diag::note_attribute_overloadable_prev_overload)
3088  << OldOvl;
3089 
3090  if (OldOvl)
3091  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3092  else
3093  New->dropAttr<OverloadableAttr>();
3094  }
3095  }
3096 
3097  // If a function is first declared with a calling convention, but is later
3098  // declared or defined without one, all following decls assume the calling
3099  // convention of the first.
3100  //
3101  // It's OK if a function is first declared without a calling convention,
3102  // but is later declared or defined with the default calling convention.
3103  //
3104  // To test if either decl has an explicit calling convention, we look for
3105  // AttributedType sugar nodes on the type as written. If they are missing or
3106  // were canonicalized away, we assume the calling convention was implicit.
3107  //
3108  // Note also that we DO NOT return at this point, because we still have
3109  // other tests to run.
3110  QualType OldQType = Context.getCanonicalType(Old->getType());
3111  QualType NewQType = Context.getCanonicalType(New->getType());
3112  const FunctionType *OldType = cast<FunctionType>(OldQType);
3113  const FunctionType *NewType = cast<FunctionType>(NewQType);
3114  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3115  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3116  bool RequiresAdjustment = false;
3117 
3118  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3119  FunctionDecl *First = Old->getFirstDecl();
3120  const FunctionType *FT =
3122  FunctionType::ExtInfo FI = FT->getExtInfo();
3123  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3124  if (!NewCCExplicit) {
3125  // Inherit the CC from the previous declaration if it was specified
3126  // there but not here.
3127  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3128  RequiresAdjustment = true;
3129  } else {
3130  // Calling conventions aren't compatible, so complain.
3131  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3132  Diag(New->getLocation(), diag::err_cconv_change)
3133  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3134  << !FirstCCExplicit
3135  << (!FirstCCExplicit ? "" :
3136  FunctionType::getNameForCallConv(FI.getCC()));
3137 
3138  // Put the note on the first decl, since it is the one that matters.
3139  Diag(First->getLocation(), diag::note_previous_declaration);
3140  return true;
3141  }
3142  }
3143 
3144  // FIXME: diagnose the other way around?
3145  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3146  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3147  RequiresAdjustment = true;
3148  }
3149 
3150  // Merge regparm attribute.
3151  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3152  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3153  if (NewTypeInfo.getHasRegParm()) {
3154  Diag(New->getLocation(), diag::err_regparm_mismatch)
3155  << NewType->getRegParmType()
3156  << OldType->getRegParmType();
3157  Diag(OldLocation, diag::note_previous_declaration);
3158  return true;
3159  }
3160 
3161  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3162  RequiresAdjustment = true;
3163  }
3164 
3165  // Merge ns_returns_retained attribute.
3166  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3167  if (NewTypeInfo.getProducesResult()) {
3168  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3169  << "'ns_returns_retained'";
3170  Diag(OldLocation, diag::note_previous_declaration);
3171  return true;
3172  }
3173 
3174  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3175  RequiresAdjustment = true;
3176  }
3177 
3178  if (OldTypeInfo.getNoCallerSavedRegs() !=
3179  NewTypeInfo.getNoCallerSavedRegs()) {
3180  if (NewTypeInfo.getNoCallerSavedRegs()) {
3181  AnyX86NoCallerSavedRegistersAttr *Attr =
3182  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3183  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3184  Diag(OldLocation, diag::note_previous_declaration);
3185  return true;
3186  }
3187 
3188  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3189  RequiresAdjustment = true;
3190  }
3191 
3192  if (RequiresAdjustment) {
3193  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3194  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3195 
3196  QualType AdjustedQT = QualType(AdjustedType, 0);
3197  LangAS AS = Old->getType().getAddressSpace();
3198  AdjustedQT = Context.getAddrSpaceQualType(AdjustedQT, AS);
3199 
3200  New->setType(AdjustedQT);
3201  NewQType = Context.getCanonicalType(New->getType());
3202  NewType = cast<FunctionType>(NewQType);
3203  }
3204 
3205  // If this redeclaration makes the function inline, we may need to add it to
3206  // UndefinedButUsed.
3207  if (!Old->isInlined() && New->isInlined() &&
3208  !New->hasAttr<GNUInlineAttr>() &&
3209  !getLangOpts().GNUInline &&
3210  Old->isUsed(false) &&
3211  !Old->isDefined() && !New->isThisDeclarationADefinition())
3212  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3213  SourceLocation()));
3214 
3215  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3216  // about it.
3217  if (New->hasAttr<GNUInlineAttr>() &&
3218  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3219  UndefinedButUsed.erase(Old->getCanonicalDecl());
3220  }
3221 
3222  // If pass_object_size params don't match up perfectly, this isn't a valid
3223  // redeclaration.
3224  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3225  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3226  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3227  << New->getDeclName();
3228  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3229  return true;
3230  }
3231 
3232  if (getLangOpts().CPlusPlus) {
3233  // C++1z [over.load]p2
3234  // Certain function declarations cannot be overloaded:
3235  // -- Function declarations that differ only in the return type,
3236  // the exception specification, or both cannot be overloaded.
3237 
3238  // Check the exception specifications match. This may recompute the type of
3239  // both Old and New if it resolved exception specifications, so grab the
3240  // types again after this. Because this updates the type, we do this before
3241  // any of the other checks below, which may update the "de facto" NewQType
3242  // but do not necessarily update the type of New.
3243  if (CheckEquivalentExceptionSpec(Old, New))
3244  return true;
3245  OldQType = Context.getCanonicalType(Old->getType());
3246  NewQType = Context.getCanonicalType(New->getType());
3247 
3248  // Go back to the type source info to compare the declared return types,
3249  // per C++1y [dcl.type.auto]p13:
3250  // Redeclarations or specializations of a function or function template
3251  // with a declared return type that uses a placeholder type shall also
3252  // use that placeholder, not a deduced type.
3253  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3254  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3255  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3256  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3257  OldDeclaredReturnType)) {
3258  QualType ResQT;
3259  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3260  OldDeclaredReturnType->isObjCObjectPointerType())
3261  // FIXME: This does the wrong thing for a deduced return type.
3262  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3263  if (ResQT.isNull()) {
3264  if (New->isCXXClassMember() && New->isOutOfLine())
3265  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3266  << New << New->getReturnTypeSourceRange();
3267  else
3268  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3269  << New->getReturnTypeSourceRange();
3270  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3271  << Old->getReturnTypeSourceRange();
3272  return true;
3273  }
3274  else
3275  NewQType = ResQT;
3276  }
3277 
3278  QualType OldReturnType = OldType->getReturnType();
3279  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3280  if (OldReturnType != NewReturnType) {
3281  // If this function has a deduced return type and has already been
3282  // defined, copy the deduced value from the old declaration.
3283  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3284  if (OldAT && OldAT->isDeduced()) {
3285  New->setType(
3286  SubstAutoType(New->getType(),
3287  OldAT->isDependentType() ? Context.DependentTy
3288  : OldAT->getDeducedType()));
3289  NewQType = Context.getCanonicalType(
3290  SubstAutoType(NewQType,
3291  OldAT->isDependentType() ? Context.DependentTy
3292  : OldAT->getDeducedType()));
3293  }
3294  }
3295 
3296  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3297  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3298  if (OldMethod && NewMethod) {
3299  // Preserve triviality.
3300  NewMethod->setTrivial(OldMethod->isTrivial());
3301 
3302  // MSVC allows explicit template specialization at class scope:
3303  // 2 CXXMethodDecls referring to the same function will be injected.
3304  // We don't want a redeclaration error.
3305  bool IsClassScopeExplicitSpecialization =
3306  OldMethod->isFunctionTemplateSpecialization() &&
3307  NewMethod->isFunctionTemplateSpecialization();
3308  bool isFriend = NewMethod->getFriendObjectKind();
3309 
3310  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3311  !IsClassScopeExplicitSpecialization) {
3312  // -- Member function declarations with the same name and the
3313  // same parameter types cannot be overloaded if any of them
3314  // is a static member function declaration.
3315  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3316  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3317  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3318  return true;
3319  }
3320 
3321  // C++ [class.mem]p1:
3322  // [...] A member shall not be declared twice in the
3323  // member-specification, except that a nested class or member
3324  // class template can be declared and then later defined.
3325  if (!inTemplateInstantiation()) {
3326  unsigned NewDiag;
3327  if (isa<CXXConstructorDecl>(OldMethod))
3328  NewDiag = diag::err_constructor_redeclared;
3329  else if (isa<CXXDestructorDecl>(NewMethod))
3330  NewDiag = diag::err_destructor_redeclared;
3331  else if (isa<CXXConversionDecl>(NewMethod))
3332  NewDiag = diag::err_conv_function_redeclared;
3333  else
3334  NewDiag = diag::err_member_redeclared;
3335 
3336  Diag(New->getLocation(), NewDiag);
3337  } else {
3338  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3339  << New << New->getType();
3340  }
3341  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3342  return true;
3343 
3344  // Complain if this is an explicit declaration of a special
3345  // member that was initially declared implicitly.
3346  //
3347  // As an exception, it's okay to befriend such methods in order
3348  // to permit the implicit constructor/destructor/operator calls.
3349  } else if (OldMethod->isImplicit()) {
3350  if (isFriend) {
3351  NewMethod->setImplicit();
3352  } else {
3353  Diag(NewMethod->getLocation(),
3354  diag::err_definition_of_implicitly_declared_member)
3355  << New << getSpecialMember(OldMethod);
3356  return true;
3357  }
3358  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3359  Diag(NewMethod->getLocation(),
3360  diag::err_definition_of_explicitly_defaulted_member)
3361  << getSpecialMember(OldMethod);
3362  return true;
3363  }
3364  }
3365 
3366  // C++11 [dcl.attr.noreturn]p1:
3367  // The first declaration of a function shall specify the noreturn
3368  // attribute if any declaration of that function specifies the noreturn
3369  // attribute.
3370  const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3371  if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3372  Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3373  Diag(Old->getFirstDecl()->getLocation(),
3374  diag::note_noreturn_missing_first_decl);
3375  }
3376 
3377  // C++11 [dcl.attr.depend]p2:
3378  // The first declaration of a function shall specify the
3379  // carries_dependency attribute for its declarator-id if any declaration
3380  // of the function specifies the carries_dependency attribute.
3381  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3382  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3383  Diag(CDA->getLocation(),
3384  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3385  Diag(Old->getFirstDecl()->getLocation(),
3386  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3387  }
3388 
3389  // (C++98 8.3.5p3):
3390  // All declarations for a function shall agree exactly in both the
3391  // return type and the parameter-type-list.
3392  // We also want to respect all the extended bits except noreturn.
3393 
3394  // noreturn should now match unless the old type info didn't have it.
3395  QualType OldQTypeForComparison = OldQType;
3396  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3397  auto *OldType = OldQType->castAs<FunctionProtoType>();
3398  const FunctionType *OldTypeForComparison
3399  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3400  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3401  assert(OldQTypeForComparison.isCanonical());
3402  }
3403 
3404  if (haveIncompatibleLanguageLinkages(Old, New)) {
3405  // As a special case, retain the language linkage from previous
3406  // declarations of a friend function as an extension.
3407  //
3408  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3409  // and is useful because there's otherwise no way to specify language
3410  // linkage within class scope.
3411  //
3412  // Check cautiously as the friend object kind isn't yet complete.
3413  if (New->getFriendObjectKind() != Decl::FOK_None) {
3414  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3415  Diag(OldLocation, PrevDiag);
3416  } else {
3417  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3418  Diag(OldLocation, PrevDiag);
3419  return true;
3420  }
3421  }
3422 
3423  if (OldQTypeForComparison == NewQType)
3424  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3425 
3426  // If the types are imprecise (due to dependent constructs in friends or
3427  // local extern declarations), it's OK if they differ. We'll check again
3428  // during instantiation.
3429  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3430  return false;
3431 
3432  // Fall through for conflicting redeclarations and redefinitions.
3433  }
3434 
3435  // C: Function types need to be compatible, not identical. This handles
3436  // duplicate function decls like "void f(int); void f(enum X);" properly.
3437  if (!getLangOpts().CPlusPlus &&
3438  Context.typesAreCompatible(OldQType, NewQType)) {
3439  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3440  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3441  const FunctionProtoType *OldProto = nullptr;
3442  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3443  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3444  // The old declaration provided a function prototype, but the
3445  // new declaration does not. Merge in the prototype.
3446  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3447  SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3448  NewQType =
3449  Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3450  OldProto->getExtProtoInfo());
3451  New->setType(NewQType);
3452  New->setHasInheritedPrototype();
3453 
3454  // Synthesize parameters with the same types.
3456  for (const auto &ParamType : OldProto->param_types()) {
3457  ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3458  SourceLocation(), nullptr,
3459  ParamType, /*TInfo=*/nullptr,
3460  SC_None, nullptr);
3461  Param->setScopeInfo(0, Params.size());
3462  Param->setImplicit();
3463  Params.push_back(Param);
3464  }
3465 
3466  New->setParams(Params);
3467  }
3468 
3469  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3470  }
3471 
3472  // GNU C permits a K&R definition to follow a prototype declaration
3473  // if the declared types of the parameters in the K&R definition
3474  // match the types in the prototype declaration, even when the
3475  // promoted types of the parameters from the K&R definition differ
3476  // from the types in the prototype. GCC then keeps the types from
3477  // the prototype.
3478  //
3479  // If a variadic prototype is followed by a non-variadic K&R definition,
3480  // the K&R definition becomes variadic. This is sort of an edge case, but
3481  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3482  // C99 6.9.1p8.
3483  if (!getLangOpts().CPlusPlus &&
3484  Old->hasPrototype() && !New->hasPrototype() &&
3485  New->getType()->getAs<FunctionProtoType>() &&
3486  Old->getNumParams() == New->getNumParams()) {
3487  SmallVector<QualType, 16> ArgTypes;
3489  const FunctionProtoType *OldProto
3490  = Old->getType()->getAs<FunctionProtoType>();
3491  const FunctionProtoType *NewProto
3492  = New->getType()->getAs<FunctionProtoType>();
3493 
3494  // Determine whether this is the GNU C extension.
3495  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3496  NewProto->getReturnType());
3497  bool LooseCompatible = !MergedReturn.isNull();
3498  for (unsigned Idx = 0, End = Old->getNumParams();
3499  LooseCompatible && Idx != End; ++Idx) {
3500  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3501  ParmVarDecl *NewParm = New->getParamDecl(Idx);
3502  if (Context.typesAreCompatible(OldParm->getType(),
3503  NewProto->getParamType(Idx))) {
3504  ArgTypes.push_back(NewParm->getType());
3505  } else if (Context.typesAreCompatible(OldParm->getType(),
3506  NewParm->getType(),
3507  /*CompareUnqualified=*/true)) {
3508  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3509  NewProto->getParamType(Idx) };
3510  Warnings.push_back(Warn);
3511  ArgTypes.push_back(NewParm->getType());
3512  } else
3513  LooseCompatible = false;
3514  }
3515 
3516  if (LooseCompatible) {
3517  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3518  Diag(Warnings[Warn].NewParm->getLocation(),
3519  diag::ext_param_promoted_not_compatible_with_prototype)
3520  << Warnings[Warn].PromotedType
3521  << Warnings[Warn].OldParm->getType();
3522  if (Warnings[Warn].OldParm->getLocation().isValid())
3523  Diag(Warnings[Warn].OldParm->getLocation(),
3524  diag::note_previous_declaration);
3525  }
3526 
3527  if (MergeTypeWithOld)
3528  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3529  OldProto->getExtProtoInfo()));
3530  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3531  }
3532 
3533  // Fall through to diagnose conflicting types.
3534  }
3535 
3536  // A function that has already been declared has been redeclared or
3537  // defined with a different type; show an appropriate diagnostic.
3538 
3539  // If the previous declaration was an implicitly-generated builtin
3540  // declaration, then at the very least we should use a specialized note.
3541  unsigned BuiltinID;
3542  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3543  // If it's actually a library-defined builtin function like 'malloc'
3544  // or 'printf', just warn about the incompatible redeclaration.
3545  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3546  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3547  Diag(OldLocation, diag::note_previous_builtin_declaration)
3548  << Old << Old->getType();
3549 
3550  // If this is a global redeclaration, just forget hereafter
3551  // about the "builtin-ness" of the function.
3552  //
3553  // Doing this for local extern declarations is problematic. If
3554  // the builtin declaration remains visible, a second invalid
3555  // local declaration will produce a hard error; if it doesn't
3556  // remain visible, a single bogus local redeclaration (which is
3557  // actually only a warning) could break all the downstream code.
3559  New->getIdentifier()->revertBuiltin();
3560 
3561  return false;
3562  }
3563 
3564  PrevDiag = diag::note_previous_builtin_declaration;
3565  }
3566 
3567  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3568  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3569  return true;
3570 }
3571 
3572 /// Completes the merge of two function declarations that are
3573 /// known to be compatible.
3574 ///
3575 /// This routine handles the merging of attributes and other
3576 /// properties of function declarations from the old declaration to
3577 /// the new declaration, once we know that New is in fact a
3578 /// redeclaration of Old.
3579 ///
3580 /// \returns false
3582  Scope *S, bool MergeTypeWithOld) {
3583  // Merge the attributes
3584  mergeDeclAttributes(New, Old);
3585 
3586  // Merge "pure" flag.
3587  if (Old->isPure())
3588  New->setPure();
3589 
3590  // Merge "used" flag.
3591  if (Old->getMostRecentDecl()->isUsed(false))
3592  New->setIsUsed();
3593 
3594  // Merge attributes from the parameters. These can mismatch with K&R
3595  // declarations.
3596  if (New->getNumParams() == Old->getNumParams())
3597  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3598  ParmVarDecl *NewParam = New->getParamDecl(i);
3599  ParmVarDecl *OldParam = Old->getParamDecl(i);
3600  mergeParamDeclAttributes(NewParam, OldParam, *this);
3601  mergeParamDeclTypes(NewParam, OldParam, *this);
3602  }
3603 
3604  if (getLangOpts().CPlusPlus)
3605  return MergeCXXFunctionDecl(New, Old, S);
3606 
3607  // Merge the function types so the we get the composite types for the return
3608  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3609  // was visible.
3610  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3611  if (!Merged.isNull() && MergeTypeWithOld)
3612  New->setType(Merged);
3613 
3614  return false;
3615 }
3616 
3618  ObjCMethodDecl *oldMethod) {
3619  // Merge the attributes, including deprecated/unavailable
3620  AvailabilityMergeKind MergeKind =
3621  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3622  ? AMK_ProtocolImplementation
3623  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3624  : AMK_Override;
3625 
3626  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3627 
3628  // Merge attributes from the parameters.
3630  oe = oldMethod->param_end();
3632  ni = newMethod->param_begin(), ne = newMethod->param_end();
3633  ni != ne && oi != oe; ++ni, ++oi)
3634  mergeParamDeclAttributes(*ni, *oi, *this);
3635 
3636  CheckObjCMethodOverride(newMethod, oldMethod);
3637 }
3638 
3639 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3640  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3641 
3643  ? diag::err_redefinition_different_type
3644  : diag::err_redeclaration_different_type)
3645  << New->getDeclName() << New->getType() << Old->getType();
3646 
3647  diag::kind PrevDiag;
3648  SourceLocation OldLocation;
3649  std::tie(PrevDiag, OldLocation)
3651  S.Diag(OldLocation, PrevDiag);
3652  New->setInvalidDecl();
3653 }
3654 
3655 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3656 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3657 /// emitting diagnostics as appropriate.
3658 ///
3659 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3660 /// to here in AddInitializerToDecl. We can't check them before the initializer
3661 /// is attached.
3663  bool MergeTypeWithOld) {
3664  if (New->isInvalidDecl() || Old->isInvalidDecl())
3665  return;
3666 
3667  QualType MergedT;
3668  if (getLangOpts().CPlusPlus) {
3669  if (New->getType()->isUndeducedType()) {
3670  // We don't know what the new type is until the initializer is attached.
3671  return;
3672  } else if (Context.hasSameType(New->getType(), Old->getType())) {
3673  // These could still be something that needs exception specs checked.
3674  return MergeVarDeclExceptionSpecs(New, Old);
3675  }
3676  // C++ [basic.link]p10:
3677  // [...] the types specified by all declarations referring to a given
3678  // object or function shall be identical, except that declarations for an
3679  // array object can specify array types that differ by the presence or
3680  // absence of a major array bound (8.3.4).
3681  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3682  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3683  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3684 
3685  // We are merging a variable declaration New into Old. If it has an array
3686  // bound, and that bound differs from Old's bound, we should diagnose the
3687  // mismatch.
3688  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3689  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3690  PrevVD = PrevVD->getPreviousDecl()) {
3691  const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3692  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3693  continue;
3694 
3695  if (!Context.hasSameType(NewArray, PrevVDTy))
3696  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3697  }
3698  }
3699 
3700  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3701  if (Context.hasSameType(OldArray->getElementType(),
3702  NewArray->getElementType()))
3703  MergedT = New->getType();
3704  }
3705  // FIXME: Check visibility. New is hidden but has a complete type. If New
3706  // has no array bound, it should not inherit one from Old, if Old is not
3707  // visible.
3708  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3709  if (Context.hasSameType(OldArray->getElementType(),
3710  NewArray->getElementType()))
3711  MergedT = Old->getType();
3712  }
3713  }
3714  else if (New->getType()->isObjCObjectPointerType() &&
3715  Old->getType()->isObjCObjectPointerType()) {
3716  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3717  Old->getType());
3718  }
3719  } else {
3720  // C 6.2.7p2:
3721  // All declarations that refer to the same object or function shall have
3722  // compatible type.
3723  MergedT = Context.mergeTypes(New->getType(), Old->getType());
3724  }
3725  if (MergedT.isNull()) {
3726  // It's OK if we couldn't merge types if either type is dependent, for a
3727  // block-scope variable. In other cases (static data members of class
3728  // templates, variable templates, ...), we require the types to be
3729  // equivalent.
3730  // FIXME: The C++ standard doesn't say anything about this.
3731  if ((New->getType()->isDependentType() ||
3732  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3733  // If the old type was dependent, we can't merge with it, so the new type
3734  // becomes dependent for now. We'll reproduce the original type when we
3735  // instantiate the TypeSourceInfo for the variable.
3736  if (!New->getType()->isDependentType() && MergeTypeWithOld)
3737  New->setType(Context.DependentTy);
3738  return;
3739  }
3740  return diagnoseVarDeclTypeMismatch(*this, New, Old);
3741  }
3742 
3743  // Don't actually update the type on the new declaration if the old
3744  // declaration was an extern declaration in a different scope.
3745  if (MergeTypeWithOld)
3746  New->setType(MergedT);
3747 }
3748 
3749 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3751  // C11 6.2.7p4:
3752  // For an identifier with internal or external linkage declared
3753  // in a scope in which a prior declaration of that identifier is
3754  // visible, if the prior declaration specifies internal or
3755  // external linkage, the type of the identifier at the later
3756  // declaration becomes the composite type.
3757  //
3758  // If the variable isn't visible, we do not merge with its type.
3759  if (Previous.isShadowed())
3760  return false;
3761 
3762  if (S.getLangOpts().CPlusPlus) {
3763  // C++11 [dcl.array]p3:
3764  // If there is a preceding declaration of the entity in the same
3765  // scope in which the bound was specified, an omitted array bound
3766  // is taken to be the same as in that earlier declaration.
3767  return NewVD->isPreviousDeclInSameBlockScope() ||
3768  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3770  } else {
3771  // If the old declaration was function-local, don't merge with its
3772  // type unless we're in the same function.
3773  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3774  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3775  }
3776 }
3777 
3778 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3779 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3780 /// situation, merging decls or emitting diagnostics as appropriate.
3781 ///
3782 /// Tentative definition rules (C99 6.9.2p2) are checked by
3783 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3784 /// definitions here, since the initializer hasn't been attached.
3785 ///
3787  // If the new decl is already invalid, don't do any other checking.
3788  if (New->isInvalidDecl())
3789  return;
3790 
3791  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3792  return;
3793 
3794  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3795 
3796  // Verify the old decl was also a variable or variable template.
3797  VarDecl *Old = nullptr;
3798  VarTemplateDecl *OldTemplate = nullptr;
3799  if (Previous.isSingleResult()) {
3800  if (NewTemplate) {
3801  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3802  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3803 
3804  if (auto *Shadow =
3805  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3806  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3807  return New->setInvalidDecl();
3808  } else {
3809  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3810 
3811  if (auto *Shadow =
3812  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3813  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3814  return New->setInvalidDecl();
3815  }
3816  }
3817  if (!Old) {
3818  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3819  << New->getDeclName();
3820  notePreviousDefinition(Previous.getRepresentativeDecl(),
3821  New->getLocation());
3822  return New->setInvalidDecl();
3823  }
3824 
3825  // Ensure the template parameters are compatible.
3826  if (NewTemplate &&
3827  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3828  OldTemplate->getTemplateParameters(),
3829  /*Complain=*/true, TPL_TemplateMatch))
3830  return New->setInvalidDecl();
3831 
3832  // C++ [class.mem]p1:
3833  // A member shall not be declared twice in the member-specification [...]
3834  //
3835  // Here, we need only consider static data members.
3836  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3837  Diag(New->getLocation(), diag::err_duplicate_member)
3838  << New->getIdentifier();
3839  Diag(Old->getLocation(), diag::note_previous_declaration);
3840  New->setInvalidDecl();
3841  }
3842 
3843  mergeDeclAttributes(New, Old);
3844  // Warn if an already-declared variable is made a weak_import in a subsequent
3845  // declaration
3846  if (New->hasAttr<WeakImportAttr>() &&
3847  Old->getStorageClass() == SC_None &&
3848  !Old->hasAttr<WeakImportAttr>()) {
3849  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3850  notePreviousDefinition(Old, New->getLocation());
3851  // Remove weak_import attribute on new declaration.
3852  New->dropAttr<WeakImportAttr>();
3853  }
3854 
3855  if (New->hasAttr<InternalLinkageAttr>() &&
3856  !Old->hasAttr<InternalLinkageAttr>()) {
3857  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3858  << New->getDeclName();
3859  notePreviousDefinition(Old, New->getLocation());
3860  New->dropAttr<InternalLinkageAttr>();
3861  }
3862 
3863  // Merge the types.
3864  VarDecl *MostRecent = Old->getMostRecentDecl();
3865  if (MostRecent != Old) {
3866  MergeVarDeclTypes(New, MostRecent,
3867  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3868  if (New->isInvalidDecl())
3869  return;
3870  }
3871 
3872  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3873  if (New->isInvalidDecl())
3874  return;
3875 
3876  diag::kind PrevDiag;
3877  SourceLocation OldLocation;
3878  std::tie(PrevDiag, OldLocation) =
3880 
3881  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3882  if (New->getStorageClass() == SC_Static &&
3883  !New->isStaticDataMember() &&
3884  Old->hasExternalFormalLinkage()) {
3885  if (getLangOpts().MicrosoftExt) {
3886  Diag(New->getLocation(), diag::ext_static_non_static)
3887  << New->getDeclName();
3888  Diag(OldLocation, PrevDiag);
3889  } else {
3890  Diag(New->getLocation(), diag::err_static_non_static)
3891  << New->getDeclName();
3892  Diag(OldLocation, PrevDiag);
3893  return New->setInvalidDecl();
3894  }
3895  }
3896  // C99 6.2.2p4:
3897  // For an identifier declared with the storage-class specifier
3898  // extern in a scope in which a prior declaration of that
3899  // identifier is visible,23) if the prior declaration specifies
3900  // internal or external linkage, the linkage of the identifier at
3901  // the later declaration is the same as the linkage specified at
3902  // the prior declaration. If no prior declaration is visible, or
3903  // if the prior declaration specifies no linkage, then the
3904  // identifier has external linkage.
3905  if (New->hasExternalStorage() && Old->hasLinkage())
3906  /* Okay */;
3907  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3908  !New->isStaticDataMember() &&
3910  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3911  Diag(OldLocation, PrevDiag);
3912  return New->setInvalidDecl();
3913  }
3914 
3915  // Check if extern is followed by non-extern and vice-versa.
3916  if (New->hasExternalStorage() &&
3917  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3918  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3919  Diag(OldLocation, PrevDiag);
3920  return New->setInvalidDecl();
3921  }
3922  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3923  !New->hasExternalStorage()) {
3924  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3925  Diag(OldLocation, PrevDiag);
3926  return New->setInvalidDecl();
3927  }
3928 
3929  if (CheckRedeclarationModuleOwnership(New, Old))
3930  return;
3931 
3932  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3933 
3934  // FIXME: The test for external storage here seems wrong? We still
3935  // need to check for mismatches.
3936  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3937  // Don't complain about out-of-line definitions of static members.
3938  !(Old->getLexicalDeclContext()->isRecord() &&
3939  !New->getLexicalDeclContext()->isRecord())) {
3940  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3941  Diag(OldLocation, PrevDiag);
3942  return New->setInvalidDecl();
3943  }
3944 
3945  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3946  if (VarDecl *Def = Old->getDefinition()) {
3947  // C++1z [dcl.fcn.spec]p4:
3948  // If the definition of a variable appears in a translation unit before
3949  // its first declaration as inline, the program is ill-formed.
3950  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3951  Diag(Def->getLocation(), diag::note_previous_definition);
3952  }
3953  }
3954 
3955  // If this redeclaration makes the variable inline, we may need to add it to
3956  // UndefinedButUsed.
3957  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3958  !Old->getDefinition() && !New->isThisDeclarationADefinition())
3959  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3960  SourceLocation()));
3961 
3962  if (New->getTLSKind() != Old->getTLSKind()) {
3963  if (!Old->getTLSKind()) {
3964  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3965  Diag(OldLocation, PrevDiag);
3966  } else if (!New->getTLSKind()) {
3967  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3968  Diag(OldLocation, PrevDiag);
3969  } else {
3970  // Do not allow redeclaration to change the variable between requiring
3971  // static and dynamic initialization.
3972  // FIXME: GCC allows this, but uses the TLS keyword on the first
3973  // declaration to determine the kind. Do we need to be compatible here?
3974  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3975  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3976  Diag(OldLocation, PrevDiag);
3977  }
3978  }
3979 
3980  // C++ doesn't have tentative definitions, so go right ahead and check here.
3981  if (getLangOpts().CPlusPlus &&
3983  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3984  Old->getCanonicalDecl()->isConstexpr()) {
3985  // This definition won't be a definition any more once it's been merged.
3986  Diag(New->getLocation(),
3987  diag::warn_deprecated_redundant_constexpr_static_def);
3988  } else if (VarDecl *Def = Old->getDefinition()) {
3989  if (checkVarDeclRedefinition(Def, New))
3990  return;
3991  }
3992  }
3993 
3994  if (haveIncompatibleLanguageLinkages(Old, New)) {
3995  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3996  Diag(OldLocation, PrevDiag);
3997  New->setInvalidDecl();
3998  return;
3999  }
4000 
4001  // Merge "used" flag.
4002  if (Old->getMostRecentDecl()->isUsed(false))
4003  New->setIsUsed();
4004 
4005  // Keep a chain of previous declarations.
4006  New->setPreviousDecl(Old);
4007  if (NewTemplate)
4008  NewTemplate->setPreviousDecl(OldTemplate);
4010 
4011  // Inherit access appropriately.
4012  New->setAccess(Old->getAccess());
4013  if (NewTemplate)
4014  NewTemplate->setAccess(New->getAccess());
4015 
4016  if (Old->isInline())
4017  New->setImplicitlyInline();
4018 }
4019 
4021  SourceManager &SrcMgr = getSourceManager();
4022  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4023  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4024  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4025  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4026  auto &HSI = PP.getHeaderSearchInfo();
4027  StringRef HdrFilename =
4028  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4029 
4030  auto noteFromModuleOrInclude = [&](Module *Mod,
4031  SourceLocation IncLoc) -> bool {
4032  // Redefinition errors with modules are common with non modular mapped
4033  // headers, example: a non-modular header H in module A that also gets
4034  // included directly in a TU. Pointing twice to the same header/definition
4035  // is confusing, try to get better diagnostics when modules is on.
4036  if (IncLoc.isValid()) {
4037  if (Mod) {
4038  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4039  << HdrFilename.str() << Mod->getFullModuleName();
4040  if (!Mod->DefinitionLoc.isInvalid())
4041  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4042  << Mod->getFullModuleName();
4043  } else {
4044  Diag(IncLoc, diag::note_redefinition_include_same_file)
4045  << HdrFilename.str();
4046  }
4047  return true;
4048  }
4049 
4050  return false;
4051  };
4052 
4053  // Is it the same file and same offset? Provide more information on why
4054  // this leads to a redefinition error.
4055  bool EmittedDiag = false;
4056  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4057  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4058  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4059  EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4060  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4061 
4062  // If the header has no guards, emit a note suggesting one.
4063  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4064  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4065 
4066  if (EmittedDiag)
4067  return;
4068  }
4069 
4070  // Redefinition coming from different files or couldn't do better above.
4071  if (Old->getLocation().isValid())
4072  Diag(Old->getLocation(), diag::note_previous_definition);
4073 }
4074 
4075 /// We've just determined that \p Old and \p New both appear to be definitions
4076 /// of the same variable. Either diagnose or fix the problem.
4078  if (!hasVisibleDefinition(Old) &&
4079  (New->getFormalLinkage() == InternalLinkage ||
4080  New->isInline() ||
4081  New->getDescribedVarTemplate() ||
4083  New->getDeclContext()->isDependentContext())) {
4084  // The previous definition is hidden, and multiple definitions are
4085  // permitted (in separate TUs). Demote this to a declaration.
4087 
4088  // Make the canonical definition visible.
4089  if (auto *OldTD = Old->getDescribedVarTemplate())
4090  makeMergedDefinitionVisible(OldTD);
4091  makeMergedDefinitionVisible(Old);
4092  return false;
4093  } else {
4094  Diag(New->getLocation(), diag::err_redefinition) << New;
4095  notePreviousDefinition(Old, New->getLocation());
4096  New->setInvalidDecl();
4097  return true;
4098  }
4099 }
4100 
4101 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4102 /// no declarator (e.g. "struct foo;") is parsed.
4103 Decl *
4105  RecordDecl *&AnonRecord) {
4106  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4107  AnonRecord);
4108 }
4109 
4110 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4111 // disambiguate entities defined in different scopes.
4112 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4113 // compatibility.
4114 // We will pick our mangling number depending on which version of MSVC is being
4115 // targeted.
4116 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4118  ? S->getMSCurManglingNumber()
4119  : S->getMSLastManglingNumber();
4120 }
4121 
4122 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4123  if (!Context.getLangOpts().CPlusPlus)
4124  return;
4125 
4126  if (isa<CXXRecordDecl>(Tag->getParent())) {
4127  // If this tag is the direct child of a class, number it if
4128  // it is anonymous.
4129  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4130  return;
4131  MangleNumberingContext &MCtx =
4132  Context.getManglingNumberContext(Tag->getParent());
4133  Context.setManglingNumber(
4134  Tag, MCtx.getManglingNumber(
4135  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4136  return;
4137  }
4138 
4139  // If this tag isn't a direct child of a class, number it if it is local.
4140  Decl *ManglingContextDecl;
4141  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4142  Tag->getDeclContext(), ManglingContextDecl)) {
4143  Context.setManglingNumber(
4144  Tag, MCtx->getManglingNumber(
4145  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4146  }
4147 }
4148 
4150  TypedefNameDecl *NewTD) {
4151  if (TagFromDeclSpec->isInvalidDecl())
4152  return;
4153 
4154  // Do nothing if the tag already has a name for linkage purposes.
4155  if (TagFromDeclSpec->hasNameForLinkage())
4156  return;
4157 
4158  // A well-formed anonymous tag must always be a TUK_Definition.
4159  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4160 
4161  // The type must match the tag exactly; no qualifiers allowed.
4162  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4163  Context.getTagDeclType(TagFromDeclSpec))) {
4164  if (getLangOpts().CPlusPlus)
4165  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4166  return;
4167  }
4168 
4169  // If we've already computed linkage for the anonymous tag, then
4170  // adding a typedef name for the anonymous decl can change that
4171  // linkage, which might be a serious problem. Diagnose this as
4172  // unsupported and ignore the typedef name. TODO: we should
4173  // pursue this as a language defect and establish a formal rule
4174  // for how to handle it.
4175  if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4176  Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4177 
4178  SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4179  tagLoc = getLocForEndOfToken(tagLoc);
4180 
4181  llvm::SmallString<40> textToInsert;
4182  textToInsert += ' ';
4183  textToInsert += NewTD->getIdentifier()->getName();
4184  Diag(tagLoc, diag::note_typedef_changes_linkage)
4185  << FixItHint::CreateInsertion(tagLoc, textToInsert);
4186  return;
4187  }
4188 
4189  // Otherwise, set this is the anon-decl typedef for the tag.
4190  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4191 }
4192 
4194  switch (T) {
4195  case DeclSpec::TST_class:
4196  return 0;
4197  case DeclSpec::TST_struct:
4198  return 1;
4200  return 2;
4201  case DeclSpec::TST_union:
4202  return 3;
4203  case DeclSpec::TST_enum:
4204  return 4;
4205  default:
4206  llvm_unreachable("unexpected type specifier");
4207  }
4208 }
4209 
4210 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4211 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4212 /// parameters to cope with template friend declarations.
4213 Decl *
4215  MultiTemplateParamsArg TemplateParams,
4216  bool IsExplicitInstantiation,
4217  RecordDecl *&AnonRecord) {
4218  Decl *TagD = nullptr;
4219  TagDecl *Tag = nullptr;
4220  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4225  TagD = DS.getRepAsDecl();
4226 
4227  if (!TagD) // We probably had an error
4228  return nullptr;
4229 
4230  // Note that the above type specs guarantee that the
4231  // type rep is a Decl, whereas in many of the others
4232  // it's a Type.
4233  if (isa<TagDecl>(TagD))
4234  Tag = cast<TagDecl>(TagD);
4235  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4236  Tag = CTD->getTemplatedDecl();
4237  }
4238 
4239  if (Tag) {
4240  handleTagNumbering(Tag, S);
4241  Tag->setFreeStanding();
4242  if (Tag->isInvalidDecl())
4243  return Tag;
4244  }
4245 
4246  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4247  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4248  // or incomplete types shall not be restrict-qualified."
4249  if (TypeQuals & DeclSpec::TQ_restrict)
4250  Diag(DS.getRestrictSpecLoc(),
4251  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4252  << DS.getSourceRange();
4253  }
4254 
4255  if (DS.isInlineSpecified())
4256  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4257  << getLangOpts().CPlusPlus17;
4258 
4259  if (DS.isConstexprSpecified()) {
4260  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4261  // and definitions of functions and variables.
4262  if (Tag)
4263  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4265  else
4266  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4267  // Don't emit warnings after this error.
4268  return TagD;
4269  }
4270 
4271  DiagnoseFunctionSpecifiers(DS);
4272 
4273  if (DS.isFriendSpecified()) {
4274  // If we're dealing with a decl but not a TagDecl, assume that
4275  // whatever routines created it handled the friendship aspect.
4276  if (TagD && !Tag)
4277  return nullptr;
4278  return ActOnFriendTypeDecl(S, DS, TemplateParams);
4279  }
4280 
4281  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4282  bool IsExplicitSpecialization =
4283  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4284  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4285  !IsExplicitInstantiation && !IsExplicitSpecialization &&
4286  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4287  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4288  // nested-name-specifier unless it is an explicit instantiation
4289  // or an explicit specialization.
4290  //
4291  // FIXME: We allow class template partial specializations here too, per the
4292  // obvious intent of DR1819.
4293  //
4294  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4295  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4297  return nullptr;
4298  }
4299 
4300  // Track whether this decl-specifier declares anything.
4301  bool DeclaresAnything = true;
4302 
4303  // Handle anonymous struct definitions.
4304  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4305  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4307  if (getLangOpts().CPlusPlus ||
4308  Record->getDeclContext()->isRecord()) {
4309  // If CurContext is a DeclContext that can contain statements,
4310  // RecursiveASTVisitor won't visit the decls that
4311  // BuildAnonymousStructOrUnion() will put into CurContext.
4312  // Also store them here so that they can be part of the
4313  // DeclStmt that gets created in this case.
4314  // FIXME: Also return the IndirectFieldDecls created by
4315  // BuildAnonymousStructOr union, for the same reason?
4316  if (CurContext->isFunctionOrMethod())
4317  AnonRecord = Record;
4318  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4319  Context.getPrintingPolicy());
4320  }
4321 
4322  DeclaresAnything = false;
4323  }
4324  }
4325 
4326  // C11 6.7.2.1p2:
4327  // A struct-declaration that does not declare an anonymous structure or
4328  // anonymous union shall contain a struct-declarator-list.
4329  //
4330  // This rule also existed in C89 and C99; the grammar for struct-declaration
4331  // did not permit a struct-declaration without a struct-declarator-list.
4332  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4334  // Check for Microsoft C extension: anonymous struct/union member.
4335  // Handle 2 kinds of anonymous struct/union:
4336  // struct STRUCT;
4337  // union UNION;
4338  // and
4339  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4340  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4341  if ((Tag && Tag->getDeclName()) ||
4343  RecordDecl *Record = nullptr;
4344  if (Tag)
4345  Record = dyn_cast<RecordDecl>(Tag);
4346  else if (const RecordType *RT =
4348  Record = RT->getDecl();
4349  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4350  Record = UT->getDecl();
4351 
4352  if (Record && getLangOpts().MicrosoftExt) {
4353  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4354  << Record->isUnion() << DS.getSourceRange();
4355  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4356  }
4357 
4358  DeclaresAnything = false;
4359  }
4360  }
4361 
4362  // Skip all the checks below if we have a type error.
4363  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4364  (TagD && TagD->isInvalidDecl()))
4365  return TagD;
4366 
4367  if (getLangOpts().CPlusPlus &&
4369  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4370  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4371  !Enum->getIdentifier() && !Enum->isInvalidDecl())
4372  DeclaresAnything = false;
4373 
4374  if (!DS.isMissingDeclaratorOk()) {
4375  // Customize diagnostic for a typedef missing a name.
4377  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4378  << DS.getSourceRange();
4379  else
4380  DeclaresAnything = false;
4381  }
4382 
4383  if (DS.isModulePrivateSpecified() &&
4384  Tag && Tag->getDeclContext()->isFunctionOrMethod())
4385  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4386  << Tag->getTagKind()
4388 
4389  ActOnDocumentableDecl(TagD);
4390 
4391  // C 6.7/2:
4392  // A declaration [...] shall declare at least a declarator [...], a tag,
4393  // or the members of an enumeration.
4394  // C++ [dcl.dcl]p3:
4395  // [If there are no declarators], and except for the declaration of an
4396  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4397  // names into the program, or shall redeclare a name introduced by a
4398  // previous declaration.
4399  if (!DeclaresAnything) {
4400  // In C, we allow this as a (popular) extension / bug. Don't bother
4401  // producing further diagnostics for redundant qualifiers after this.
4402  Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4403  return TagD;
4404  }
4405 
4406  // C++ [dcl.stc]p1:
4407  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4408  // init-declarator-list of the declaration shall not be empty.
4409  // C++ [dcl.fct.spec]p1:
4410  // If a cv-qualifier appears in a decl-specifier-seq, the
4411  // init-declarator-list of the declaration shall not be empty.
4412  //
4413  // Spurious qualifiers here appear to be valid in C.
4414  unsigned DiagID = diag::warn_standalone_specifier;
4415  if (getLangOpts().CPlusPlus)
4416  DiagID = diag::ext_standalone_specifier;
4417 
4418  // Note that a linkage-specification sets a storage class, but
4419  // 'extern "C" struct foo;' is actually valid and not theoretically
4420  // useless.
4421  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4422  if (SCS == DeclSpec::SCS_mutable)
4423  // Since mutable is not a viable storage class specifier in C, there is
4424  // no reason to treat it as an extension. Instead, diagnose as an error.
4425  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4426  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4427  Diag(DS.getStorageClassSpecLoc(), DiagID)
4429  }
4430 
4431  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4432  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4433  << DeclSpec::getSpecifierName(TSCS);
4434  if (DS.getTypeQualifiers()) {
4436  Diag(DS.getConstSpecLoc(), DiagID) << "const";
4438  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4439  // Restrict is covered above.
4441  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4443  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4444  }
4445 
4446  // Warn about ignored type attributes, for example:
4447  // __attribute__((aligned)) struct A;
4448  // Attributes should be placed after tag to apply to type declaration.
4449  if (!DS.getAttributes().empty()) {
4450  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4451  if (TypeSpecType == DeclSpec::TST_class ||
4452  TypeSpecType == DeclSpec::TST_struct ||
4453  TypeSpecType == DeclSpec::TST_interface ||
4454  TypeSpecType == DeclSpec::TST_union ||
4455  TypeSpecType == DeclSpec::TST_enum) {
4456  for (const ParsedAttr &AL : DS.getAttributes())
4457  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4458  << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4459  }
4460  }
4461 
4462  return TagD;
4463 }
4464 
4465 /// We are trying to inject an anonymous member into the given scope;
4466 /// check if there's an existing declaration that can't be overloaded.
4467 ///
4468 /// \return true if this is a forbidden redeclaration
4469 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4470  Scope *S,
4471  DeclContext *Owner,
4472  DeclarationName Name,
4473  SourceLocation NameLoc,
4474  bool IsUnion) {
4475  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4477  if (!SemaRef.LookupName(R, S)) return false;
4478 
4479  // Pick a representative declaration.
4481  assert(PrevDecl && "Expected a non-null Decl");
4482 
4483  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4484  return false;
4485 
4486  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4487  << IsUnion << Name;
4488  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4489 
4490  return true;
4491 }
4492 
4493 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4494 /// anonymous struct or union AnonRecord into the owning context Owner
4495 /// and scope S. This routine will be invoked just after we realize
4496 /// that an unnamed union or struct is actually an anonymous union or
4497 /// struct, e.g.,
4498 ///
4499 /// @code
4500 /// union {
4501 /// int i;
4502 /// float f;
4503 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4504 /// // f into the surrounding scope.x
4505 /// @endcode
4506 ///
4507 /// This routine is recursive, injecting the names of nested anonymous
4508 /// structs/unions into the owning context and scope as well.
4509 static bool
4511  RecordDecl *AnonRecord, AccessSpecifier AS,
4512  SmallVectorImpl<NamedDecl *> &Chaining) {
4513  bool Invalid = false;
4514 
4515  // Look every FieldDecl and IndirectFieldDecl with a name.
4516  for (auto *D : AnonRecord->decls()) {
4517  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4518  cast<NamedDecl>(D)->getDeclName()) {
4519  ValueDecl *VD = cast<ValueDecl>(D);
4520  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4521  VD->getLocation(),
4522  AnonRecord->isUnion())) {
4523  // C++ [class.union]p2:
4524  // The names of the members of an anonymous union shall be
4525  // distinct from the names of any other entity in the
4526  // scope in which the anonymous union is declared.
4527  Invalid = true;
4528  } else {
4529  // C++ [class.union]p2:
4530  // For the purpose of name lookup, after the anonymous union
4531  // definition, the members of the anonymous union are
4532  // considered to have been defined in the scope in which the
4533  // anonymous union is declared.
4534  unsigned OldChainingSize = Chaining.size();
4535  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4536  Chaining.append(IF->chain_begin(), IF->chain_end());
4537  else
4538  Chaining.push_back(VD);
4539 
4540  assert(Chaining.size() >= 2);
4541  NamedDecl **NamedChain =
4542  new (SemaRef.Context)NamedDecl*[Chaining.size()];
4543  for (unsigned i = 0; i < Chaining.size(); i++)
4544  NamedChain[i] = Chaining[i];
4545 
4547  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4548  VD->getType(), {NamedChain, Chaining.size()});
4549 
4550  for (const auto *Attr : VD->attrs())
4551  IndirectField->addAttr(Attr->clone(SemaRef.Context));
4552 
4553  IndirectField->setAccess(AS);
4554  IndirectField->setImplicit();
4555  SemaRef.PushOnScopeChains(IndirectField, S);
4556 
4557  // That includes picking up the appropriate access specifier.
4558  if (AS != AS_none) IndirectField->setAccess(AS);
4559 
4560  Chaining.resize(OldChainingSize);
4561  }
4562  }
4563  }
4564 
4565  return Invalid;
4566 }
4567 
4568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4569 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4570 /// illegal input values are mapped to SC_None.
4571 static StorageClass
4573  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4574  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4575  "Parser allowed 'typedef' as storage class VarDecl.");
4576  switch (StorageClassSpec) {
4577  case DeclSpec::SCS_unspecified: return SC_None;
4578  case DeclSpec::SCS_extern:
4579  if (DS.isExternInLinkageSpec())
4580  return SC_None;
4581  return SC_Extern;
4582  case DeclSpec::SCS_static: return SC_Static;
4583  case DeclSpec::SCS_auto: return SC_Auto;
4584  case DeclSpec::SCS_register: return SC_Register;
4586  // Illegal SCSs map to None: error reporting is up to the caller.
4587  case DeclSpec::SCS_mutable: // Fall through.
4588  case DeclSpec::SCS_typedef: return SC_None;
4589  }
4590  llvm_unreachable("unknown storage class specifier");
4591 }
4592 
4594  assert(Record->hasInClassInitializer());
4595 
4596  for (const auto *I : Record->decls()) {
4597  const auto *FD = dyn_cast<FieldDecl>(I);
4598  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4599  FD = IFD->getAnonField();
4600  if (FD && FD->hasInClassInitializer())
4601  return FD->getLocation();
4602  }
4603 
4604  llvm_unreachable("couldn't find in-class initializer");
4605 }
4606 
4608  SourceLocation DefaultInitLoc) {
4609  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4610  return;
4611 
4612  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4613  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4614 }
4615 
4617  CXXRecordDecl *AnonUnion) {
4618  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4619  return;
4620 
4621  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4622 }
4623 
4624 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4625 /// anonymous structure or union. Anonymous unions are a C++ feature
4626 /// (C++ [class.union]) and a C11 feature; anonymous structures
4627 /// are a C11 feature and GNU C++ extension.
4629  AccessSpecifier AS,
4630  RecordDecl *Record,
4631  const PrintingPolicy &Policy) {
4632  DeclContext *Owner = Record->getDeclContext();
4633 
4634  // Diagnose whether this anonymous struct/union is an extension.
4635  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4636  Diag(Record->getLocation(), diag::ext_anonymous_union);
4637  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4638  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4639  else if (!Record->isUnion() && !getLangOpts().C11)
4640  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4641 
4642  // C and C++ require different kinds of checks for anonymous
4643  // structs/unions.
4644  bool Invalid = false;
4645  if (getLangOpts().CPlusPlus) {
4646  const char *PrevSpec = nullptr;
4647  unsigned DiagID;
4648  if (Record->isUnion()) {
4649  // C++ [class.union]p6:
4650  // C++17 [class.union.anon]p2:
4651  // Anonymous unions declared in a named namespace or in the
4652  // global namespace shall be declared static.
4653  DeclContext *OwnerScope = Owner->getRedeclContext();
4655  (OwnerScope->isTranslationUnit() ||
4656  (OwnerScope->isNamespace() &&
4657  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4658  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4659  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4660 
4661  // Recover by adding 'static'.
4663  PrevSpec, DiagID, Policy);
4664  }
4665  // C++ [class.union]p6:
4666  // A storage class is not allowed in a declaration of an
4667  // anonymous union in a class scope.
4669  isa<RecordDecl>(Owner)) {
4671  diag::err_anonymous_union_with_storage_spec)
4673 
4674  // Recover by removing the storage specifier.
4676  SourceLocation(),
4677  PrevSpec, DiagID, Context.getPrintingPolicy());
4678  }
4679  }
4680 
4681  // Ignore const/volatile/restrict qualifiers.
4682  if (DS.getTypeQualifiers()) {
4684  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4685  << Record->isUnion() << "const"
4688  Diag(DS.getVolatileSpecLoc(),
4689  diag::ext_anonymous_struct_union_qualified)
4690  << Record->isUnion() << "volatile"
4693  Diag(DS.getRestrictSpecLoc(),
4694  diag::ext_anonymous_struct_union_qualified)
4695  << Record->isUnion() << "restrict"
4698  Diag(DS.getAtomicSpecLoc(),
4699  diag::ext_anonymous_struct_union_qualified)
4700  << Record->isUnion() << "_Atomic"
4704  diag::ext_anonymous_struct_union_qualified)
4705  << Record->isUnion() << "__unaligned"
4707 
4708  DS.ClearTypeQualifiers();
4709  }
4710 
4711  // C++ [class.union]p2:
4712  // The member-specification of an anonymous union shall only
4713  // define non-static data members. [Note: nested types and
4714  // functions cannot be declared within an anonymous union. ]
4715  for (auto *Mem : Record->decls()) {
4716  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4717  // C++ [class.union]p3:
4718  // An anonymous union shall not have private or protected
4719  // members (clause 11).
4720  assert(FD->getAccess() != AS_none);
4721  if (FD->getAccess() != AS_public) {
4722  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4723  << Record->isUnion() << (FD->getAccess() == AS_protected);
4724  Invalid = true;
4725  }
4726 
4727  // C++ [class.union]p1
4728  // An object of a class with a non-trivial constructor, a non-trivial
4729  // copy constructor, a non-trivial destructor, or a non-trivial copy
4730  // assignment operator cannot be a member of a union, nor can an
4731  // array of such objects.
4732  if (CheckNontrivialField(FD))
4733  Invalid = true;
4734  } else if (Mem->isImplicit()) {
4735  // Any implicit members are fine.
4736  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4737  // This is a type that showed up in an
4738  // elaborated-type-specifier inside the anonymous struct or
4739  // union, but which actually declares a type outside of the
4740  // anonymous struct or union. It's okay.
4741  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4742  if (!MemRecord->isAnonymousStructOrUnion() &&
4743  MemRecord->getDeclName()) {
4744  // Visual C++ allows type definition in anonymous struct or union.
4745  if (getLangOpts().MicrosoftExt)
4746  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4747  << Record->isUnion();
4748  else {
4749  // This is a nested type declaration.
4750  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4751  << Record->isUnion();
4752  Invalid = true;
4753  }
4754  } else {
4755  // This is an anonymous type definition within another anonymous type.
4756  // This is a popular extension, provided by Plan9, MSVC and GCC, but
4757  // not part of standard C++.
4758  Diag(MemRecord->getLocation(),
4759  diag::ext_anonymous_record_with_anonymous_type)
4760  << Record->isUnion();
4761  }
4762  } else if (isa<AccessSpecDecl>(Mem)) {
4763  // Any access specifier is fine.
4764  } else if (isa<StaticAssertDecl>(Mem)) {
4765  // In C++1z, static_assert declarations are also fine.
4766  } else {
4767  // We have something that isn't a non-static data
4768  // member. Complain about it.
4769  unsigned DK = diag::err_anonymous_record_bad_member;
4770  if (isa<TypeDecl>(Mem))
4771  DK = diag::err_anonymous_record_with_type;
4772  else if (isa<FunctionDecl>(Mem))
4773  DK = diag::err_anonymous_record_with_function;
4774  else if (isa<VarDecl>(Mem))
4775  DK = diag::err_anonymous_record_with_static;
4776 
4777  // Visual C++ allows type definition in anonymous struct or union.
4778  if (getLangOpts().MicrosoftExt &&
4779  DK == diag::err_anonymous_record_with_type)
4780  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4781  << Record->isUnion();
4782  else {
4783  Diag(Mem->getLocation(), DK) << Record->isUnion();
4784  Invalid = true;
4785  }
4786  }
4787  }
4788 
4789  // C++11 [class.union]p8 (DR1460):
4790  // At most one variant member of a union may have a
4791  // brace-or-equal-initializer.
4792  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4793  Owner->isRecord())
4794  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4795  cast<CXXRecordDecl>(Record));
4796  }
4797 
4798  if (!Record->isUnion() && !Owner->isRecord()) {
4799  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4800  << getLangOpts().CPlusPlus;
4801  Invalid = true;
4802  }
4803 
4804  // Mock up a declarator.
4806  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4807  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4808 
4809  // Create a declaration for this anonymous struct/union.
4810  NamedDecl *Anon = nullptr;
4811  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4812  Anon = FieldDecl::Create(
4813  Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4814  /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4815  /*BitWidth=*/nullptr, /*Mutable=*/false,
4816  /*InitStyle=*/ICIS_NoInit);
4817  Anon->setAccess(AS);
4818  if (getLangOpts().CPlusPlus)
4819  FieldCollector->Add(cast<FieldDecl>(Anon));
4820  } else {
4821  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4823  if (SCSpec == DeclSpec::SCS_mutable) {
4824  // mutable can only appear on non-static class members, so it's always
4825  // an error here
4826  Diag(Record->getLocation(), diag::err_mutable_nonmember);
4827  Invalid = true;
4828  SC = SC_None;
4829  }
4830 
4831  Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4832  Record->getLocation(), /*IdentifierInfo=*/nullptr,
4833  Context.getTypeDeclType(Record), TInfo, SC);
4834 
4835  // Default-initialize the implicit variable. This initialization will be
4836  // trivial in almost all cases, except if a union member has an in-class
4837  // initializer:
4838  // union { int n = 0; };
4839  ActOnUninitializedDecl(Anon);
4840  }
4841  Anon->setImplicit();
4842 
4843  // Mark this as an anonymous struct/union type.
4844  Record->setAnonymousStructOrUnion(true);
4845 
4846  // Add the anonymous struct/union object to the current
4847  // context. We'll be referencing this object when we refer to one of
4848  // its members.
4849  Owner->addDecl(Anon);
4850 
4851  // Inject the members of the anonymous struct/union into the owning
4852  // context and into the identifier resolver chain for name lookup
4853  // purposes.
4855  Chain.push_back(Anon);
4856 
4857  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4858  Invalid = true;
4859 
4860  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4861  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4862  Decl *ManglingContextDecl;
4863  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4864  NewVD->getDeclContext(), ManglingContextDecl)) {
4865  Context.setManglingNumber(
4866  NewVD, MCtx->getManglingNumber(
4867  NewVD, getMSManglingNumber(getLangOpts(), S)));
4868  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4869  }
4870  }
4871  }
4872 
4873  if (Invalid)
4874  Anon->setInvalidDecl();
4875 
4876  return Anon;
4877 }
4878 
4879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4880 /// Microsoft C anonymous structure.
4881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4882 /// Example:
4883 ///
4884 /// struct A { int a; };
4885 /// struct B { struct A; int b; };
4886 ///
4887 /// void foo() {
4888 /// B var;
4889 /// var.a = 3;
4890 /// }
4891 ///
4893  RecordDecl *Record) {
4894  assert(Record && "expected a record!");
4895 
4896  // Mock up a declarator.
4898  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4899  assert(TInfo && "couldn't build declarator info for anonymous struct");
4900 
4901  auto *ParentDecl = cast<RecordDecl>(CurContext);
4902  QualType RecTy = Context.getTypeDeclType(Record);
4903 
4904  // Create a declaration for this anonymous struct.
4905  NamedDecl *Anon =
4906  FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4907  /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4908  /*BitWidth=*/nullptr, /*Mutable=*/false,
4909  /*InitStyle=*/ICIS_NoInit);
4910  Anon->setImplicit();
4911 
4912  // Add the anonymous struct object to the current context.
4913  CurContext->addDecl(Anon);
4914 
4915  // Inject the members of the anonymous struct into the current
4916  // context and into the identifier resolver chain for name lookup
4917  // purposes.
4919  Chain.push_back(Anon);
4920 
4921  RecordDecl *RecordDef = Record->getDefinition();
4922  if (RequireCompleteType(Anon->getLocation(), RecTy,
4923  diag::err_field_incomplete) ||
4924  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4925  AS_none, Chain)) {
4926  Anon->setInvalidDecl();
4927  ParentDecl->setInvalidDecl();
4928  }
4929 
4930  return Anon;
4931 }
4932 
4933 /// GetNameForDeclarator - Determine the full declaration name for the
4934 /// given Declarator.
4936  return GetNameFromUnqualifiedId(D.getName());
4937 }
4938 
4939 /// Retrieves the declaration name from a parsed unqualified-id.
4942  DeclarationNameInfo NameInfo;
4943  NameInfo.setLoc(Name.StartLocation);
4944 
4945  switch (Name.getKind()) {
4946 
4949  NameInfo.setName(Name.Identifier);
4950  return NameInfo;
4951 
4953  // C++ [temp.deduct.guide]p3:
4954  // The simple-template-id shall name a class template specialization.
4955  // The template-name shall be the same identifier as the template-name
4956  // of the simple-template-id.
4957  // These together intend to imply that the template-name shall name a
4958  // class template.
4959  // FIXME: template<typename T> struct X {};
4960  // template<typename T> using Y = X<T>;
4961  // Y(int) -> Y<int>;
4962  // satisfies these rules but does not name a class template.
4963  TemplateName TN = Name.TemplateName.get().get();
4964  auto *Template = TN.getAsTemplateDecl();
4965  if (!Template || !isa<ClassTemplateDecl>(Template)) {
4966  Diag(Name.StartLocation,
4967  diag::err_deduction_guide_name_not_class_template)
4968  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4969  if (Template)
4970  Diag(Template->getLocation(), diag::note_template_decl_here);
4971  return DeclarationNameInfo();
4972  }
4973 
4974  NameInfo.setName(
4975  Context.DeclarationNames.getCXXDeductionGuideName(Template));
4976  return NameInfo;
4977  }
4978 
4980  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4985  = Name.EndLocation.getRawEncoding();
4986  return NameInfo;
4987 
4990  Name.Identifier));
4992  return NameInfo;
4993 
4995  TypeSourceInfo *TInfo;
4996  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4997  if (Ty.isNull())
4998  return DeclarationNameInfo();
5000  Context.getCanonicalType(Ty)));
5001  NameInfo.setNamedTypeInfo(TInfo);
5002  return NameInfo;
5003  }
5004 
5006  TypeSourceInfo *TInfo;
5007  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5008  if (Ty.isNull())
5009  return DeclarationNameInfo();
5011  Context.getCanonicalType(Ty)));
5012  NameInfo.setNamedTypeInfo(TInfo);
5013  return NameInfo;
5014  }
5015 
5017  // In well-formed code, we can only have a constructor
5018  // template-id that refers to the current context, so go there
5019  // to find the actual type being constructed.
5020  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5021  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5022  return DeclarationNameInfo();
5023 
5024  // Determine the type of the class being constructed.
5025  QualType CurClassType = Context.getTypeDeclType(CurClass);
5026 
5027  // FIXME: Check two things: that the template-id names the same type as
5028  // CurClassType, and that the template-id does not occur when the name
5029  // was qualified.
5030 
5032  Context.getCanonicalType(CurClassType)));
5033  // FIXME: should we retrieve TypeSourceInfo?
5034  NameInfo.setNamedTypeInfo(nullptr);
5035  return NameInfo;
5036  }
5037 
5039  TypeSourceInfo *TInfo;
5040  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5041  if (Ty.isNull())
5042  return DeclarationNameInfo();
5044  Context.getCanonicalType(Ty)));
5045  NameInfo.setNamedTypeInfo(TInfo);
5046  return NameInfo;
5047  }
5048 
5050  TemplateName TName = Name.TemplateId->Template.get();
5051  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5052  return Context.getNameForTemplate(TName, TNameLoc);
5053  }
5054 
5055  } // switch (Name.getKind())
5056 
5057  llvm_unreachable("Unknown name kind");
5058 }
5059 
5061  do {
5062  if (Ty->isPointerType() || Ty->isReferenceType())
5063  Ty = Ty->getPointeeType();
5064  else if (Ty->isArrayType())
5065  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5066  else
5067  return Ty.withoutLocalFastQualifiers();
5068  } while (true);
5069 }
5070 
5071 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5072 /// and Definition have "nearly" matching parameters. This heuristic is
5073 /// used to improve diagnostics in the case where an out-of-line function
5074 /// definition doesn't match any declaration within the class or namespace.
5075 /// Also sets Params to the list of indices to the parameters that differ
5076 /// between the declaration and the definition. If hasSimilarParameters
5077 /// returns true and Params is empty, then all of the parameters match.
5078 static bool hasSimilarParameters(ASTContext &Context,
5079  FunctionDecl *Declaration,
5080  FunctionDecl *Definition,
5081  SmallVectorImpl<unsigned> &Params) {
5082  Params.clear();
5083  if (Declaration->param_size() != Definition->param_size())
5084  return false;
5085  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5086  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5087  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5088 
5089  // The parameter types are identical
5090  if (Context.hasSameType(DefParamTy, DeclParamTy))
5091  continue;
5092 
5093  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5094  QualType DefParamBaseTy = getCoreType(DefParamTy);
5095  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5096  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5097 
5098  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5099  (DeclTyName && DeclTyName == DefTyName))
5100  Params.push_back(Idx);
5101  else // The two parameters aren't even close
5102  return false;
5103  }
5104 
5105  return true;
5106 }
5107 
5108 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5109 /// declarator needs to be rebuilt in the current instantiation.
5110 /// Any bits of declarator which appear before the name are valid for
5111 /// consideration here. That's specifically the type in the decl spec
5112 /// and the base type in any member-pointer chunks.
5114  DeclarationName Name) {
5115  // The types we specifically need to rebuild are:
5116  // - typenames, typeofs, and decltypes
5117  // - types which will become injected class names
5118  // Of course, we also need to rebuild any type referencing such a
5119  // type. It's safest to just say "dependent", but we call out a
5120  // few cases here.
5121 
5122  DeclSpec &DS = D.getMutableDeclSpec();
5123  switch (DS.getTypeSpecType()) {
5127  case DeclSpec::TST_atomic: {
5128  // Grab the type from the parser.
5129  TypeSourceInfo *TSI = nullptr;
5130  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5131  if (T.isNull() || !T->isDependentType()) break;
5132 
5133  // Make sure there's a type source info. This isn't really much
5134  // of a waste; most dependent types should have type source info
5135  // attached already.
5136  if (!TSI)
5138 
5139  // Rebuild the type in the current instantiation.
5140  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5141  if (!TSI) return true;
5142 
5143  // Store the new type back in the decl spec.
5144  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5145  DS.UpdateTypeRep(LocType);
5146  break;
5147  }
5148 
5150  case DeclSpec::TST_typeofExpr: {
5151  Expr *E = DS.getRepAsExpr();
5153  if (Result.isInvalid()) return true;
5154  DS.UpdateExprRep(Result.get());
5155  break;
5156  }
5157 
5158  default:
5159  // Nothing to do for these decl specs.
5160  break;
5161  }
5162 
5163  // It doesn't matter what order we do this in.
5164  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5165  DeclaratorChunk &Chunk = D.getTypeObject(I);
5166 
5167  // The only type information in the declarator which can come
5168  // before the declaration name is the base type of a member
5169  // pointer.
5170  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5171  continue;
5172 
5173  // Rebuild the scope specifier in-place.
5174  CXXScopeSpec &SS = Chunk.Mem.Scope();
5176  return true;
5177  }
5178 
5179  return false;
5180 }
5181 
5184  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5185 
5186  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5187  Dcl && Dcl->getDeclContext()->isFileContext())
5189 
5190  if (getLangOpts().OpenCL)
5191  setCurrentOpenCLExtensionForDecl(Dcl);
5192 
5193  return Dcl;
5194 }
5195 
5196 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5197 /// If T is the name of a class, then each of the following shall have a
5198 /// name different from T:
5199 /// - every static data member of class T;
5200 /// - every member function of class T
5201 /// - every member of class T that is itself a type;
5202 /// \returns true if the declaration name violates these rules.
5204  DeclarationNameInfo NameInfo) {
5205  DeclarationName Name = NameInfo.getName();
5206 
5207  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5208  while (Record && Record->isAnonymousStructOrUnion())
5209  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5210  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5211  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5212  return true;
5213  }
5214 
5215  return false;
5216 }
5217 
5218 /// Diagnose a declaration whose declarator-id has the given
5219 /// nested-name-specifier.
5220 ///
5221 /// \param SS The nested-name-specifier of the declarator-id.
5222 ///
5223 /// \param DC The declaration context to which the nested-name-specifier
5224 /// resolves.
5225 ///
5226 /// \param Name The name of the entity being declared.
5227 ///
5228 /// \param Loc The location of the name of the entity being declared.
5229 ///
5230 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5231 /// we're declaring an explicit / partial specialization / instantiation.
5232 ///
5233 /// \returns true if we cannot safely recover from this error, false otherwise.
5235  DeclarationName Name,
5236  SourceLocation Loc, bool IsTemplateId) {
5237  DeclContext *Cur = CurContext;
5238  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5239  Cur = Cur->getParent();
5240 
5241  // If the user provided a superfluous scope specifier that refers back to the
5242  // class in which the entity is already declared, diagnose and ignore it.
5243  //
5244  // class X {
5245  // void X::f();
5246  // };
5247  //
5248  // Note, it was once ill-formed to give redundant qualification in all
5249  // contexts, but that rule was removed by DR482.
5250  if (Cur->Equals(DC)) {
5251  if (Cur->isRecord()) {
5252  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5253  : diag::err_member_extra_qualification)
5254  << Name << FixItHint::CreateRemoval(SS.getRange());
5255  SS.clear();
5256  } else {
5257  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5258  }
5259  return false;
5260  }
5261 
5262  // Check whether the qualifying scope encloses the scope of the original
5263  // declaration. For a template-id, we perform the checks in
5264  // CheckTemplateSpecializationScope.
5265  if (!Cur->Encloses(DC) && !IsTemplateId) {
5266  if (Cur->isRecord())
5267  Diag(Loc, diag::err_member_qualification)
5268  << Name << SS.getRange();
5269  else if (isa<TranslationUnitDecl>(DC))
5270  Diag(Loc, diag::err_invalid_declarator_global_scope)
5271  << Name << SS.getRange();
5272  else if (isa<FunctionDecl>(Cur))
5273  Diag(Loc, diag::err_invalid_declarator_in_function)
5274  << Name << SS.getRange();
5275  else if (isa<BlockDecl>(Cur))
5276  Diag(Loc, diag::err_invalid_declarator_in_block)
5277  << Name << SS.getRange();
5278  else
5279  Diag(Loc, diag::err_invalid_declarator_scope)
5280  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5281 
5282  return true;
5283  }
5284 
5285  if (Cur->isRecord()) {
5286  // Cannot qualify members within a class.
5287  Diag(Loc, diag::err_member_qualification)
5288  << Name << SS.getRange();
5289  SS.clear();
5290 
5291  // C++ constructors and destructors with incorrect scopes can break
5292  // our AST invariants by having the wrong underlying types. If
5293  // that's the case, then drop this declaration entirely.
5296  !Context.hasSameType(Name.getCXXNameType(),
5297  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5298  return true;
5299 
5300  return false;
5301  }
5302 
5303  // C++11 [dcl.meaning]p1:
5304  // [...] "The nested-name-specifier of the qualified declarator-id shall
5305  // not begin with a decltype-specifer"
5306  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5307  while (SpecLoc.getPrefix())
5308  SpecLoc = SpecLoc.getPrefix();
5309  if (dyn_cast_or_null<DecltypeType>(
5310  SpecLoc.getNestedNameSpecifier()->getAsType()))
5311  Diag(Loc, diag::err_decltype_in_declarator)
5312  << SpecLoc.getTypeLoc().getSourceRange();
5313 
5314  return false;
5315 }
5316 
5318  MultiTemplateParamsArg TemplateParamLists) {
5319  // TODO: consider using NameInfo for diagnostic.
5320  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5321  DeclarationName Name = NameInfo.getName();
5322 
5323  // All of these full declarators require an identifier. If it doesn't have
5324  // one, the ParsedFreeStandingDeclSpec action should be used.
5325  if (D.isDecompositionDeclarator()) {
5326  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5327  } else if (!Name) {
5328  if (!D.isInvalidType()) // Reject this if we think it is valid.
5329  Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5330  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5331  return nullptr;
5332  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5333  return nullptr;
5334 
5335  // The scope passed in may not be a decl scope. Zip up the scope tree until
5336  // we find one that is.
5337  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5338  (S->getFlags() & Scope::TemplateParamScope) != 0)
5339  S = S->getParent();
5340 
5341  DeclContext *DC = CurContext;
5342  if (D.getCXXScopeSpec().isInvalid())
5343  D.setInvalidType();
5344  else if (D.getCXXScopeSpec().isSet()) {
5345  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5346  UPPC_DeclarationQualifier))
5347  return nullptr;
5348 
5349  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5350  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5351  if (!DC || isa<EnumDecl>(DC)) {
5352  // If we could not compute the declaration context, it's because the
5353  // declaration context is dependent but does not refer to a class,
5354  // class template, or class template partial specialization. Complain
5355  // and return early, to avoid the coming semantic disaster.
5356  Diag(D.getIdentifierLoc(),
5357  diag::err_template_qualified_declarator_no_match)
5358  << D.getCXXScopeSpec().getScopeRep()
5359  << D.getCXXScopeSpec().getRange();
5360  return nullptr;
5361  }
5362  bool IsDependentContext = DC->isDependentContext();
5363 
5364  if (!IsDependentContext &&
5365  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5366  return nullptr;
5367 
5368  // If a class is incomplete, do not parse entities inside it.
5369  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5370  Diag(D.getIdentifierLoc(),
5371  diag::err_member_def_undefined_record)
5372  << Name << DC << D.getCXXScopeSpec().getRange();
5373  return nullptr;
5374  }
5375  if (!D.getDeclSpec().isFriendSpecified()) {
5376  if (diagnoseQualifiedDeclaration(
5377  D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5379  if (DC->isRecord())
5380  return nullptr;
5381 
5382  D.setInvalidType();
5383  }
5384  }
5385 
5386  // Check whether we need to rebuild the type of the given
5387  // declaration in the current instantiation.
5388  if (EnteringContext && IsDependentContext &&
5389  TemplateParamLists.size() != 0) {
5390  ContextRAII SavedContext(*this, DC);
5391  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5392  D.setInvalidType();
5393  }
5394  }
5395 
5396  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5397  QualType R = TInfo->getType();
5398 
5399  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5400  UPPC_DeclarationType))
5401  D.setInvalidType();
5402 
5403  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5404  forRedeclarationInCurContext());
5405 
5406  // See if this is a redefinition of a variable in the same scope.
5407  if (!D.getCXXScopeSpec().isSet()) {
5408  bool IsLinkageLookup = false;
5409  bool CreateBuiltins = false;
5410 
5411  // If the declaration we're planning to build will be a function
5412  // or object with linkage, then look for another declaration with
5413  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5414  //
5415  // If the declaration we're planning to build will be declared with
5416  // external linkage in the translation unit, create any builtin with
5417  // the same name.
5419  /* Do nothing*/;
5420  else if (CurContext->isFunctionOrMethod() &&
5422  R->isFunctionType())) {
5423  IsLinkageLookup = true;
5424  CreateBuiltins =
5425  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5426  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5428  CreateBuiltins = true;
5429 
5430  if (IsLinkageLookup) {
5431  Previous.clear(LookupRedeclarationWithLinkage);
5432  Previous.setRedeclarationKind(ForExternalRedeclaration);
5433  }
5434 
5435  LookupName(Previous, S, CreateBuiltins);
5436  } else { // Something like "int foo::x;"
5437  LookupQualifiedName(Previous, DC);
5438 
5439  // C++ [dcl.meaning]p1:
5440  // When the declarator-id is qualified, the declaration shall refer to a
5441  // previously declared member of the class or namespace to which the
5442  // qualifier refers (or, in the case of a namespace, of an element of the
5443  // inline namespace set of that namespace (7.3.1)) or to a specialization
5444  // thereof; [...]
5445  //
5446  // Note that we already checked the context above, and that we do not have
5447  // enough information to make sure that Previous contains the declaration
5448  // we want to match. For example, given:
5449  //
5450  // class X {
5451  // void f();
5452  // void f(float);
5453  // };
5454  //
5455  // void X::f(int) { } // ill-formed
5456  //
5457  // In this case, Previous will point to the overload set
5458  // containing the two f's declared in X, but neither of them
5459  // matches.
5460 
5461  // C++ [dcl.meaning]p1:
5462  // [...] the member shall not merely have been introduced by a
5463  // using-declaration in the scope of the class or namespace nominated by
5464  // the nested-name-specifier of the declarator-id.
5465  RemoveUsingDecls(Previous);
5466  }
5467 
5468  if (Previous.isSingleResult() &&
5469  Previous.getFoundDecl()->isTemplateParameter()) {
5470  // Maybe we will complain about the shadowed template parameter.
5471  if (!D.isInvalidType())
5472  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5473  Previous.getFoundDecl());
5474 
5475  // Just pretend that we didn't see the previous declaration.
5476  Previous.clear();
5477  }
5478 
5479  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5480  // Forget that the previous declaration is the injected-class-name.
5481  Previous.clear();
5482 
5483  // In C++, the previous declaration we find might be a tag type
5484  // (class or enum). In this case, the new declaration will hide the
5485  // tag type. Note that this applies to functions, function templates, and
5486  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5487  if (Previous.isSingleTagDecl() &&
5489  (TemplateParamLists.size() == 0 || R->isFunctionType()))
5490  Previous.clear();
5491 
5492  // Check that there are no default arguments other than in the parameters
5493  // of a function declaration (C++ only).
5494  if (getLangOpts().CPlusPlus)
5495  CheckExtraCXXDefaultArguments(D);
5496 
5497  NamedDecl *New;
5498 
5499  bool AddToScope = true;
5501  if (TemplateParamLists.size()) {
5502  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5503  return nullptr;
5504  }
5505 
5506  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5507  } else if (R->isFunctionType()) {
5508  New =