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