clang 20.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaWasm.h"
58#include "clang/Sema/Template.h"
59#include "llvm/ADT/STLForwardCompat.h"
60#include "llvm/ADT/SmallString.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/TargetParser/Triple.h"
63#include <algorithm>
64#include <cstring>
65#include <functional>
66#include <optional>
67#include <unordered_map>
68
69using namespace clang;
70using namespace sema;
71
73 if (OwnedType) {
74 Decl *Group[2] = { OwnedType, Ptr };
76 }
77
79}
80
81namespace {
82
83class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
84 public:
85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
86 bool AllowTemplates = false,
87 bool AllowNonTemplates = true)
88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
90 WantExpressionKeywords = false;
91 WantCXXNamedCasts = false;
92 WantRemainingKeywords = false;
93 }
94
95 bool ValidateCandidate(const TypoCorrection &candidate) override {
96 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
97 if (!AllowInvalidDecl && ND->isInvalidDecl())
98 return false;
99
100 if (getAsTypeTemplateDecl(ND))
101 return AllowTemplates;
102
103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
104 if (!IsType)
105 return false;
106
107 if (AllowNonTemplates)
108 return true;
109
110 // An injected-class-name of a class template (specialization) is valid
111 // as a template or as a non-template.
112 if (AllowTemplates) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (!RD || !RD->isInjectedClassName())
115 return false;
116 RD = cast<CXXRecordDecl>(RD->getDeclContext());
117 return RD->getDescribedClassTemplate() ||
118 isa<ClassTemplateSpecializationDecl>(RD);
119 }
120
121 return false;
122 }
123
124 return !WantClassName && candidate.isKeyword();
125 }
126
127 std::unique_ptr<CorrectionCandidateCallback> clone() override {
128 return std::make_unique<TypeNameValidatorCCC>(*this);
129 }
130
131 private:
132 bool AllowInvalidDecl;
133 bool WantClassName;
134 bool AllowTemplates;
135 bool AllowNonTemplates;
136};
137
138} // end anonymous namespace
139
140namespace {
141enum class UnqualifiedTypeNameLookupResult {
142 NotFound,
143 FoundNonType,
144 FoundType
145};
146} // end anonymous namespace
147
148/// Tries to perform unqualified lookup of the type decls in bases for
149/// dependent class.
150/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
151/// type decl, \a FoundType if only type decls are found.
152static UnqualifiedTypeNameLookupResult
154 SourceLocation NameLoc,
155 const CXXRecordDecl *RD) {
156 if (!RD->hasDefinition())
157 return UnqualifiedTypeNameLookupResult::NotFound;
158 // Look for type decls in base classes.
159 UnqualifiedTypeNameLookupResult FoundTypeDecl =
160 UnqualifiedTypeNameLookupResult::NotFound;
161 for (const auto &Base : RD->bases()) {
162 const CXXRecordDecl *BaseRD = nullptr;
163 if (auto *BaseTT = Base.getType()->getAs<TagType>())
164 BaseRD = BaseTT->getAsCXXRecordDecl();
165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
166 // Look for type decls in dependent base classes that have known primary
167 // templates.
168 if (!TST || !TST->isDependentType())
169 continue;
170 auto *TD = TST->getTemplateName().getAsTemplateDecl();
171 if (!TD)
172 continue;
173 if (auto *BasePrimaryTemplate =
174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = BasePrimaryTemplate;
177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
179 CTD->findPartialSpecialization(Base.getType()))
180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
181 BaseRD = PS;
182 }
183 }
184 }
185 if (BaseRD) {
186 for (NamedDecl *ND : BaseRD->lookup(&II)) {
187 if (!isa<TypeDecl>(ND))
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190 }
191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
193 case UnqualifiedTypeNameLookupResult::FoundNonType:
194 return UnqualifiedTypeNameLookupResult::FoundNonType;
195 case UnqualifiedTypeNameLookupResult::FoundType:
196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
197 break;
198 case UnqualifiedTypeNameLookupResult::NotFound:
199 break;
200 }
201 }
202 }
203 }
204
205 return FoundTypeDecl;
206}
207
209 const IdentifierInfo &II,
210 SourceLocation NameLoc) {
211 // Lookup in the parent class template context, if any.
212 const CXXRecordDecl *RD = nullptr;
213 UnqualifiedTypeNameLookupResult FoundTypeDecl =
214 UnqualifiedTypeNameLookupResult::NotFound;
215 for (DeclContext *DC = S.CurContext;
216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
217 DC = DC->getParent()) {
218 // Look for type decls in dependent base classes that have known primary
219 // templates.
220 RD = dyn_cast<CXXRecordDecl>(DC);
221 if (RD && RD->getDescribedClassTemplate())
222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
223 }
224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
225 return nullptr;
226
227 // We found some types in dependent base classes. Recover as if the user
228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
229 // lookup during template instantiation.
230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
231
232 ASTContext &Context = S.Context;
233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
234 cast<Type>(Context.getRecordType(RD)));
235 QualType T =
237
238 CXXScopeSpec SS;
239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
240
241 TypeLocBuilder Builder;
242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
243 DepTL.setNameLoc(NameLoc);
245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
247}
248
249/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
251 SourceLocation NameLoc,
252 bool WantNontrivialTypeSourceInfo = true) {
253 switch (T->getTypeClass()) {
254 case Type::DeducedTemplateSpecialization:
255 case Type::Enum:
256 case Type::InjectedClassName:
257 case Type::Record:
258 case Type::Typedef:
259 case Type::UnresolvedUsing:
260 case Type::Using:
261 break;
262 // These can never be qualified so an ElaboratedType node
263 // would carry no additional meaning.
264 case Type::ObjCInterface:
265 case Type::ObjCTypeParam:
266 case Type::TemplateTypeParm:
267 return ParsedType::make(T);
268 default:
269 llvm_unreachable("Unexpected Type Class");
270 }
271
272 if (!SS || SS->isEmpty())
274 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
275
277 if (!WantNontrivialTypeSourceInfo)
278 return ParsedType::make(ElTy);
279
280 TypeLocBuilder Builder;
281 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
286}
287
289 Scope *S, CXXScopeSpec *SS, bool isClassName,
290 bool HasTrailingDot, ParsedType ObjectTypePtr,
291 bool IsCtorOrDtorName,
292 bool WantNontrivialTypeSourceInfo,
293 bool IsClassTemplateDeductionContext,
294 ImplicitTypenameContext AllowImplicitTypename,
295 IdentifierInfo **CorrectedII) {
296 // FIXME: Consider allowing this outside C++1z mode as an extension.
297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
299 !isClassName && !HasTrailingDot;
300
301 // Determine where we will perform name lookup.
302 DeclContext *LookupCtx = nullptr;
303 if (ObjectTypePtr) {
304 QualType ObjectType = ObjectTypePtr.get();
305 if (ObjectType->isRecordType())
306 LookupCtx = computeDeclContext(ObjectType);
307 } else if (SS && SS->isNotEmpty()) {
308 LookupCtx = computeDeclContext(*SS, false);
309
310 if (!LookupCtx) {
311 if (isDependentScopeSpecifier(*SS)) {
312 // C++ [temp.res]p3:
313 // A qualified-id that refers to a type and in which the
314 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // shall be prefixed by the keyword typename to indicate that the
316 // qualified-id denotes a type, forming an
317 // elaborated-type-specifier (7.1.5.3).
318 //
319 // We therefore do not perform any name lookup if the result would
320 // refer to a member of an unknown specialization.
321 // In C++2a, in several contexts a 'typename' is not required. Also
322 // allow this as an extension.
323 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
324 !isClassName && !IsCtorOrDtorName)
325 return nullptr;
326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
327 if (IsImplicitTypename) {
328 SourceLocation QualifiedLoc = SS->getRange().getBegin();
330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
331 else
332 Diag(QualifiedLoc, diag::ext_implicit_typename)
333 << SS->getScopeRep() << II.getName()
334 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
335 }
336
337 // We know from the grammar that this name refers to a type,
338 // so build a dependent node to describe the type.
339 if (WantNontrivialTypeSourceInfo)
340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
341 (ImplicitTypenameContext)IsImplicitTypename)
342 .get();
343
346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
348 SourceLocation(), QualifierLoc, II, NameLoc);
349 return ParsedType::make(T);
350 }
351
352 return nullptr;
353 }
354
355 if (!LookupCtx->isDependentContext() &&
356 RequireCompleteDeclContext(*SS, LookupCtx))
357 return nullptr;
358 }
359
360 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
361 // lookup for class-names.
362 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
364 LookupResult Result(*this, &II, NameLoc, Kind);
365 if (LookupCtx) {
366 // Perform "qualified" name lookup into the declaration context we
367 // computed, which is either the type of the base of a member access
368 // expression or the declaration context associated with a prior
369 // nested-name-specifier.
370 LookupQualifiedName(Result, LookupCtx);
371
372 if (ObjectTypePtr && Result.empty()) {
373 // C++ [basic.lookup.classref]p3:
374 // If the unqualified-id is ~type-name, the type-name is looked up
375 // in the context of the entire postfix-expression. If the type T of
376 // the object expression is of a class type C, the type-name is also
377 // looked up in the scope of class C. At least one of the lookups shall
378 // find a name that refers to (possibly cv-qualified) T.
379 LookupName(Result, S);
380 }
381 } else {
382 // Perform unqualified name lookup.
383 LookupName(Result, S);
384
385 // For unqualified lookup in a class template in MSVC mode, look into
386 // dependent base classes where the primary class template is known.
387 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
388 if (ParsedType TypeInBase =
389 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
390 return TypeInBase;
391 }
392 }
393
394 NamedDecl *IIDecl = nullptr;
395 UsingShadowDecl *FoundUsingShadow = nullptr;
396 switch (Result.getResultKind()) {
398 if (CorrectedII) {
399 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
400 AllowDeducedTemplate);
401 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
402 S, SS, CCC, CTK_ErrorRecovery);
403 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
404 TemplateTy Template;
405 bool MemberOfUnknownSpecialization;
407 TemplateName.setIdentifier(NewII, NameLoc);
409 CXXScopeSpec NewSS, *NewSSPtr = SS;
410 if (SS && NNS) {
411 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
412 NewSSPtr = &NewSS;
413 }
414 if (Correction && (NNS || NewII != &II) &&
415 // Ignore a correction to a template type as the to-be-corrected
416 // identifier is not a template (typo correction for template names
417 // is handled elsewhere).
418 !(getLangOpts().CPlusPlus && NewSSPtr &&
419 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
420 Template, MemberOfUnknownSpecialization))) {
421 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
422 isClassName, HasTrailingDot, ObjectTypePtr,
423 IsCtorOrDtorName,
424 WantNontrivialTypeSourceInfo,
425 IsClassTemplateDeductionContext);
426 if (Ty) {
427 diagnoseTypo(Correction,
428 PDiag(diag::err_unknown_type_or_class_name_suggest)
429 << Result.getLookupName() << isClassName);
430 if (SS && NNS)
431 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
432 *CorrectedII = NewII;
433 return Ty;
434 }
435 }
436 }
437 Result.suppressDiagnostics();
438 return nullptr;
440 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
442 SS->getScopeRep(), &II);
443 TypeLocBuilder TLB;
447 TL.setNameLoc(NameLoc);
449 }
450 [[fallthrough]];
453 Result.suppressDiagnostics();
454 return nullptr;
455
457 // Recover from type-hiding ambiguities by hiding the type. We'll
458 // do the lookup again when looking for an object, and we can
459 // diagnose the error then. If we don't do this, then the error
460 // about hiding the type will be immediately followed by an error
461 // that only makes sense if the identifier was treated like a type.
462 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
463 Result.suppressDiagnostics();
464 return nullptr;
465 }
466
467 // Look to see if we have a type anywhere in the list of results.
468 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
469 Res != ResEnd; ++Res) {
470 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
471 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
472 RealRes) ||
473 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
474 if (!IIDecl ||
475 // Make the selection of the recovery decl deterministic.
476 RealRes->getLocation() < IIDecl->getLocation()) {
477 IIDecl = RealRes;
478 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
479 }
480 }
481 }
482
483 if (!IIDecl) {
484 // None of the entities we found is a type, so there is no way
485 // to even assume that the result is a type. In this case, don't
486 // complain about the ambiguity. The parser will either try to
487 // perform this lookup again (e.g., as an object name), which
488 // will produce the ambiguity, or will complain that it expected
489 // a type name.
490 Result.suppressDiagnostics();
491 return nullptr;
492 }
493
494 // We found a type within the ambiguous lookup; diagnose the
495 // ambiguity and then return that type. This might be the right
496 // answer, or it might not be, but it suppresses any attempt to
497 // perform the name lookup again.
498 break;
499
501 IIDecl = Result.getFoundDecl();
502 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
503 break;
504 }
505
506 assert(IIDecl && "Didn't find decl");
507
508 QualType T;
509 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
510 // C++ [class.qual]p2: A lookup that would find the injected-class-name
511 // instead names the constructors of the class, except when naming a class.
512 // This is ill-formed when we're not actually forming a ctor or dtor name.
513 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
514 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
515 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
516 FoundRD->isInjectedClassName() &&
517 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
518 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
519 << &II << /*Type*/1;
520
521 DiagnoseUseOfDecl(IIDecl, NameLoc);
522
524 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
525 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
526 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
527 if (!HasTrailingDot)
529 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
530 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
531 (void)DiagnoseUseOfDecl(UD, NameLoc);
532 // Recover with 'int'
534 } else if (AllowDeducedTemplate) {
535 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
536 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
538 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
539 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
541 false);
542 // Don't wrap in a further UsingType.
543 FoundUsingShadow = nullptr;
544 }
545 }
546
547 if (T.isNull()) {
548 // If it's not plausibly a type, suppress diagnostics.
549 Result.suppressDiagnostics();
550 return nullptr;
551 }
552
553 if (FoundUsingShadow)
554 T = Context.getUsingType(FoundUsingShadow, T);
555
556 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
557}
558
559// Builds a fake NNS for the given decl context.
560static NestedNameSpecifier *
562 for (;; DC = DC->getLookupParent()) {
563 DC = DC->getPrimaryContext();
564 auto *ND = dyn_cast<NamespaceDecl>(DC);
565 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
566 return NestedNameSpecifier::Create(Context, nullptr, ND);
567 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
568 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
570 else if (isa<TranslationUnitDecl>(DC))
572 }
573 llvm_unreachable("something isn't in TU scope?");
574}
575
576/// Find the parent class with dependent bases of the innermost enclosing method
577/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
578/// up allowing unqualified dependent type names at class-level, which MSVC
579/// correctly rejects.
580static const CXXRecordDecl *
582 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
583 DC = DC->getPrimaryContext();
584 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
585 if (MD->getParent()->hasAnyDependentBases())
586 return MD->getParent();
587 }
588 return nullptr;
589}
590
592 SourceLocation NameLoc,
593 bool IsTemplateTypeArg) {
594 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
595
596 NestedNameSpecifier *NNS = nullptr;
597 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
598 // If we weren't able to parse a default template argument, delay lookup
599 // until instantiation time by making a non-dependent DependentTypeName. We
600 // pretend we saw a NestedNameSpecifier referring to the current scope, and
601 // lookup is retried.
602 // FIXME: This hurts our diagnostic quality, since we get errors like "no
603 // type named 'Foo' in 'current_namespace'" when the user didn't write any
604 // name specifiers.
606 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
607 } else if (const CXXRecordDecl *RD =
609 // Build a DependentNameType that will perform lookup into RD at
610 // instantiation time.
611 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
612 RD->getTypeForDecl());
613
614 // Diagnose that this identifier was undeclared, and retry the lookup during
615 // template instantiation.
616 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
617 << RD;
618 } else {
619 // This is not a situation that we should recover from.
620 return ParsedType();
621 }
622
623 QualType T =
625
626 // Build type location information. We synthesized the qualifier, so we have
627 // to build a fake NestedNameSpecifierLoc.
628 NestedNameSpecifierLocBuilder NNSLocBuilder;
629 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
630 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
631
632 TypeLocBuilder Builder;
633 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
634 DepTL.setNameLoc(NameLoc);
636 DepTL.setQualifierLoc(QualifierLoc);
637 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
638}
639
641 // Do a tag name lookup in this scope.
642 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
643 LookupName(R, S, false);
646 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
647 switch (TD->getTagKind()) {
653 return DeclSpec::TST_union;
655 return DeclSpec::TST_class;
657 return DeclSpec::TST_enum;
658 }
659 }
660
662}
663
665 if (CurContext->isRecord()) {
667 return true;
668
669 const Type *Ty = SS->getScopeRep()->getAsType();
670
671 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672 for (const auto &Base : RD->bases())
673 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674 return true;
675 return S->isFunctionPrototypeScope();
676 }
677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678}
679
681 SourceLocation IILoc,
682 Scope *S,
683 CXXScopeSpec *SS,
684 ParsedType &SuggestedType,
685 bool IsTemplateName) {
686 // Don't report typename errors for editor placeholders.
687 if (II->isEditorPlaceholder())
688 return;
689 // We don't have anything to suggest (yet).
690 SuggestedType = nullptr;
691
692 // There may have been a typo in the name of the type. Look up typo
693 // results, in case we have something that we can suggest.
694 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695 /*AllowTemplates=*/IsTemplateName,
696 /*AllowNonTemplates=*/!IsTemplateName);
697 if (TypoCorrection Corrected =
699 CCC, CTK_ErrorRecovery)) {
700 // FIXME: Support error recovery for the template-name case.
701 bool CanRecover = !IsTemplateName;
702 if (Corrected.isKeyword()) {
703 // We corrected to a keyword.
704 diagnoseTypo(Corrected,
705 PDiag(IsTemplateName ? diag::err_no_template_suggest
706 : diag::err_unknown_typename_suggest)
707 << II);
708 II = Corrected.getCorrectionAsIdentifierInfo();
709 } else {
710 // We found a similarly-named type or interface; suggest that.
711 if (!SS || !SS->isSet()) {
712 diagnoseTypo(Corrected,
713 PDiag(IsTemplateName ? diag::err_no_template_suggest
714 : diag::err_unknown_typename_suggest)
715 << II, CanRecover);
716 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718 bool DroppedSpecifier =
719 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
720 diagnoseTypo(Corrected,
721 PDiag(IsTemplateName
722 ? diag::err_no_member_template_suggest
723 : diag::err_unknown_nested_typename_suggest)
724 << II << DC << DroppedSpecifier << SS->getRange(),
725 CanRecover);
726 } else {
727 llvm_unreachable("could not have corrected a typo here");
728 }
729
730 if (!CanRecover)
731 return;
732
733 CXXScopeSpec tmpSS;
734 if (Corrected.getCorrectionSpecifier())
735 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736 SourceRange(IILoc));
737 // FIXME: Support class template argument deduction here.
738 SuggestedType =
739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741 /*IsCtorOrDtorName=*/false,
742 /*WantNontrivialTypeSourceInfo=*/true);
743 }
744 return;
745 }
746
747 if (getLangOpts().CPlusPlus && !IsTemplateName) {
748 // See if II is a class template that the user forgot to pass arguments to.
749 UnqualifiedId Name;
750 Name.setIdentifier(II, IILoc);
751 CXXScopeSpec EmptySS;
752 TemplateTy TemplateResult;
753 bool MemberOfUnknownSpecialization;
754 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755 Name, nullptr, true, TemplateResult,
756 MemberOfUnknownSpecialization) == TNK_Type_template) {
757 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758 return;
759 }
760 }
761
762 // FIXME: Should we move the logic that tries to recover from a missing tag
763 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764
765 if (!SS || (!SS->isSet() && !SS->isInvalid()))
766 Diag(IILoc, IsTemplateName ? diag::err_no_template
767 : diag::err_unknown_typename)
768 << II;
769 else if (DeclContext *DC = computeDeclContext(*SS, false))
770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771 : diag::err_typename_nested_not_found)
772 << II << DC << SS->getRange();
773 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774 SuggestedType =
775 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776 } else if (isDependentScopeSpecifier(*SS)) {
777 unsigned DiagID = diag::err_typename_missing;
778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779 DiagID = diag::ext_typename_missing;
780
781 Diag(SS->getRange().getBegin(), DiagID)
782 << SS->getScopeRep() << II->getName()
783 << SourceRange(SS->getRange().getBegin(), IILoc)
784 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785 SuggestedType = ActOnTypenameType(S, SourceLocation(),
786 *SS, *II, IILoc).get();
787 } else {
788 assert(SS && SS->isInvalid() &&
789 "Invalid scope specifier has already been diagnosed");
790 }
791}
792
793/// Determine whether the given result set contains either a type name
794/// or
795static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797 NextToken.is(tok::less);
798
799 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801 return true;
802
803 if (CheckTemplate && isa<TemplateDecl>(*I))
804 return true;
805 }
806
807 return false;
808}
809
811 Scope *S, CXXScopeSpec &SS,
812 IdentifierInfo *&Name,
813 SourceLocation NameLoc) {
814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
816 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817 StringRef FixItTagName;
818 switch (Tag->getTagKind()) {
820 FixItTagName = "class ";
821 break;
822
824 FixItTagName = "enum ";
825 break;
826
828 FixItTagName = "struct ";
829 break;
830
832 FixItTagName = "__interface ";
833 break;
834
836 FixItTagName = "union ";
837 break;
838 }
839
840 StringRef TagName = FixItTagName.drop_back();
841 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844
845 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846 I != IEnd; ++I)
847 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848 << Name << TagName;
849
850 // Replace lookup results with just the tag decl.
852 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
853 return true;
854 }
855
856 return false;
857}
858
860 IdentifierInfo *&Name,
861 SourceLocation NameLoc,
862 const Token &NextToken,
864 DeclarationNameInfo NameInfo(Name, NameLoc);
865 ObjCMethodDecl *CurMethod = getCurMethodDecl();
866
867 assert(NextToken.isNot(tok::coloncolon) &&
868 "parse nested name specifiers before calling ClassifyName");
869 if (getLangOpts().CPlusPlus && SS.isSet() &&
870 isCurrentClassName(*Name, S, &SS)) {
871 // Per [class.qual]p2, this names the constructors of SS, not the
872 // injected-class-name. We don't have a classification for that.
873 // There's not much point caching this result, since the parser
874 // will reject it later.
876 }
877
878 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
880 /*AllowBuiltinCreation=*/!CurMethod);
881
882 if (SS.isInvalid())
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension. However, this is not
935 // allowed in all language modes as functions without prototypes may not
936 // be supported.
937 if (getLangOpts().implicitFunctionsAllowed()) {
938 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
940 }
941 }
942
943 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
944 // In C++20 onwards, this could be an ADL-only call to a function
945 // template, and we're required to assume that this is a template name.
946 //
947 // FIXME: Find a way to still do typo correction in this case.
948 TemplateName Template =
951 }
952
953 // In C, we first see whether there is a tag type by the same name, in
954 // which case it's likely that the user just forgot to write "enum",
955 // "struct", or "union".
956 if (!getLangOpts().CPlusPlus && !SecondTry &&
957 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
958 break;
959 }
960
961 // Perform typo correction to determine if there is another name that is
962 // close to this name.
963 if (!SecondTry && CCC) {
964 SecondTry = true;
965 if (TypoCorrection Corrected =
966 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
967 &SS, *CCC, CTK_ErrorRecovery)) {
968 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
969 unsigned QualifiedDiag = diag::err_no_member_suggest;
970
971 NamedDecl *FirstDecl = Corrected.getFoundDecl();
972 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
973 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
974 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
975 UnqualifiedDiag = diag::err_no_template_suggest;
976 QualifiedDiag = diag::err_no_member_template_suggest;
977 } else if (UnderlyingFirstDecl &&
978 (isa<TypeDecl>(UnderlyingFirstDecl) ||
979 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
980 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
981 UnqualifiedDiag = diag::err_unknown_typename_suggest;
982 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
983 }
984
985 if (SS.isEmpty()) {
986 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
987 } else {// FIXME: is this even reachable? Test it.
988 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
989 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
990 Name->getName() == CorrectedStr;
991 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
992 << Name << computeDeclContext(SS, false)
993 << DroppedSpecifier << SS.getRange());
994 }
995
996 // Update the name, so that the caller has the new name.
997 Name = Corrected.getCorrectionAsIdentifierInfo();
998
999 // Typo correction corrected to a keyword.
1000 if (Corrected.isKeyword())
1001 return Name;
1002
1003 // Also update the LookupResult...
1004 // FIXME: This should probably go away at some point
1005 Result.clear();
1006 Result.setLookupName(Corrected.getCorrection());
1007 if (FirstDecl)
1008 Result.addDecl(FirstDecl);
1009
1010 // If we found an Objective-C instance variable, let
1011 // LookupInObjCMethod build the appropriate expression to
1012 // reference the ivar.
1013 // FIXME: This is a gross hack.
1014 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1015 DeclResult R =
1016 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1017 if (R.isInvalid())
1019 if (R.isUsable())
1020 return NameClassification::NonType(Ivar);
1021 }
1022
1023 goto Corrected;
1024 }
1025 }
1026
1027 // We failed to correct; just fall through and let the parser deal with it.
1028 Result.suppressDiagnostics();
1030
1032 // We performed name lookup into the current instantiation, and there were
1033 // dependent bases, so we treat this result the same way as any other
1034 // dependent nested-name-specifier.
1035
1036 // C++ [temp.res]p2:
1037 // A name used in a template declaration or definition and that is
1038 // dependent on a template-parameter is assumed not to name a type
1039 // unless the applicable name lookup finds a type name or the name is
1040 // qualified by the keyword typename.
1041 //
1042 // FIXME: If the next token is '<', we might want to ask the parser to
1043 // perform some heroics to see if we actually have a
1044 // template-argument-list, which would indicate a missing 'template'
1045 // keyword here.
1047 }
1048
1052 break;
1053
1055 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1056 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1057 /*AllowDependent=*/false)) {
1058 // C++ [temp.local]p3:
1059 // A lookup that finds an injected-class-name (10.2) can result in an
1060 // ambiguity in certain cases (for example, if it is found in more than
1061 // one base class). If all of the injected-class-names that are found
1062 // refer to specializations of the same class template, and if the name
1063 // is followed by a template-argument-list, the reference refers to the
1064 // class template itself and not a specialization thereof, and is not
1065 // ambiguous.
1066 //
1067 // This filtering can make an ambiguous result into an unambiguous one,
1068 // so try again after filtering out template names.
1070 if (!Result.isAmbiguous()) {
1071 IsFilteredTemplateName = true;
1072 break;
1073 }
1074 }
1075
1076 // Diagnose the ambiguity and return an error.
1078 }
1079
1080 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1081 (IsFilteredTemplateName ||
1083 Result, /*AllowFunctionTemplates=*/true,
1084 /*AllowDependent=*/false,
1085 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1087 // C++ [temp.names]p3:
1088 // After name lookup (3.4) finds that a name is a template-name or that
1089 // an operator-function-id or a literal- operator-id refers to a set of
1090 // overloaded functions any member of which is a function template if
1091 // this is followed by a <, the < is always taken as the delimiter of a
1092 // template-argument-list and never as the less-than operator.
1093 // C++2a [temp.names]p2:
1094 // A name is also considered to refer to a template if it is an
1095 // unqualified-id followed by a < and name lookup finds either one
1096 // or more functions or finds nothing.
1097 if (!IsFilteredTemplateName)
1099
1100 bool IsFunctionTemplate;
1101 bool IsVarTemplate;
1102 TemplateName Template;
1103 if (Result.end() - Result.begin() > 1) {
1104 IsFunctionTemplate = true;
1105 Template = Context.getOverloadedTemplateName(Result.begin(),
1106 Result.end());
1107 } else if (!Result.empty()) {
1108 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1109 *Result.begin(), /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false));
1111 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1112 IsVarTemplate = isa<VarTemplateDecl>(TD);
1113
1114 UsingShadowDecl *FoundUsingShadow =
1115 dyn_cast<UsingShadowDecl>(*Result.begin());
1116 assert(!FoundUsingShadow ||
1117 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1119 SS.getScopeRep(),
1120 /*TemplateKeyword=*/false,
1121 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1122 } else {
1123 // All results were non-template functions. This is a function template
1124 // name.
1125 IsFunctionTemplate = true;
1126 Template = Context.getAssumedTemplateName(NameInfo.getName());
1127 }
1128
1129 if (IsFunctionTemplate) {
1130 // Function templates always go through overload resolution, at which
1131 // point we'll perform the various checks (e.g., accessibility) we need
1132 // to based on which function we selected.
1133 Result.suppressDiagnostics();
1134
1135 return NameClassification::FunctionTemplate(Template);
1136 }
1137
1138 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1140 }
1141
1142 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1144 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1145 T = Context.getUsingType(USD, T);
1146 return buildNamedType(*this, &SS, T, NameLoc);
1147 };
1148
1149 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1150 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1151 DiagnoseUseOfDecl(Type, NameLoc);
1152 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1153 return BuildTypeFor(Type, *Result.begin());
1154 }
1155
1156 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1157 if (!Class) {
1158 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1159 if (ObjCCompatibleAliasDecl *Alias =
1160 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1161 Class = Alias->getClassInterface();
1162 }
1163
1164 if (Class) {
1165 DiagnoseUseOfDecl(Class, NameLoc);
1166
1167 if (NextToken.is(tok::period)) {
1168 // Interface. <something> is parsed as a property reference expression.
1169 // Just return "unknown" as a fall-through for now.
1170 Result.suppressDiagnostics();
1172 }
1173
1175 return ParsedType::make(T);
1176 }
1177
1178 if (isa<ConceptDecl>(FirstDecl)) {
1179 // We want to preserve the UsingShadowDecl for concepts.
1180 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1183 TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 }
1185
1186 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1187 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1189 }
1190
1191 // We can have a type template here if we're classifying a template argument.
1192 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1193 !isa<VarTemplateDecl>(FirstDecl))
1195 TemplateName(cast<TemplateDecl>(FirstDecl)));
1196
1197 // Check for a tag type hidden by a non-type decl in a few cases where it
1198 // seems likely a type is wanted instead of the non-type that was found.
1199 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1200 if ((NextToken.is(tok::identifier) ||
1201 (NextIsOp &&
1202 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1203 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1204 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1205 DiagnoseUseOfDecl(Type, NameLoc);
1206 return BuildTypeFor(Type, *Result.begin());
1207 }
1208
1209 // If we already know which single declaration is referenced, just annotate
1210 // that declaration directly. Defer resolving even non-overloaded class
1211 // member accesses, as we need to defer certain access checks until we know
1212 // the context.
1213 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1214 if (Result.isSingleResult() && !ADL &&
1215 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1216 return NameClassification::NonType(Result.getRepresentativeDecl());
1217
1218 // Otherwise, this is an overload set that we will need to resolve later.
1219 Result.suppressDiagnostics();
1221 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1222 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1223 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1224}
1225
1228 SourceLocation NameLoc) {
1229 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1230 CXXScopeSpec SS;
1231 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1232 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1233}
1234
1237 IdentifierInfo *Name,
1238 SourceLocation NameLoc,
1239 bool IsAddressOfOperand) {
1240 DeclarationNameInfo NameInfo(Name, NameLoc);
1241 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1242 NameInfo, IsAddressOfOperand,
1243 /*TemplateArgs=*/nullptr);
1244}
1245
1248 SourceLocation NameLoc,
1249 const Token &NextToken) {
1250 if (getCurMethodDecl() && SS.isEmpty())
1251 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1252 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1253
1254 // Reconstruct the lookup result.
1255 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1256 Result.addDecl(Found);
1257 Result.resolveKind();
1258
1259 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1260 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1261}
1262
1264 // For an implicit class member access, transform the result into a member
1265 // access expression if necessary.
1266 auto *ULE = cast<UnresolvedLookupExpr>(E);
1267 if ((*ULE->decls_begin())->isCXXClassMember()) {
1268 CXXScopeSpec SS;
1269 SS.Adopt(ULE->getQualifierLoc());
1270
1271 // Reconstruct the lookup result.
1272 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1274 Result.setNamingClass(ULE->getNamingClass());
1275 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1276 Result.addDecl(*I, I.getAccess());
1277 Result.resolveKind();
1279 nullptr, S);
1280 }
1281
1282 // Otherwise, this is already in the form we needed, and no further checks
1283 // are necessary.
1284 return ULE;
1285}
1286
1289 auto *TD = Name.getAsTemplateDecl();
1290 if (!TD)
1292 if (isa<ClassTemplateDecl>(TD))
1294 if (isa<FunctionTemplateDecl>(TD))
1296 if (isa<VarTemplateDecl>(TD))
1298 if (isa<TypeAliasTemplateDecl>(TD))
1300 if (isa<TemplateTemplateParmDecl>(TD))
1302 if (isa<ConceptDecl>(TD))
1305}
1306
1308 assert(DC->getLexicalParent() == CurContext &&
1309 "The next DeclContext should be lexically contained in the current one.");
1310 CurContext = DC;
1311 S->setEntity(DC);
1312}
1313
1315 assert(CurContext && "DeclContext imbalance!");
1316
1318 assert(CurContext && "Popped translation unit!");
1319}
1320
1322 Decl *D) {
1323 // Unlike PushDeclContext, the context to which we return is not necessarily
1324 // the containing DC of TD, because the new context will be some pre-existing
1325 // TagDecl definition instead of a fresh one.
1326 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1327 CurContext = cast<TagDecl>(D)->getDefinition();
1328 assert(CurContext && "skipping definition of undefined tag");
1329 // Start lookups from the parent of the current context; we don't want to look
1330 // into the pre-existing complete definition.
1331 S->setEntity(CurContext->getLookupParent());
1332 return Result;
1333}
1334
1336 CurContext = static_cast<decltype(CurContext)>(Context);
1337}
1338
1340 // C++0x [basic.lookup.unqual]p13:
1341 // A name used in the definition of a static data member of class
1342 // X (after the qualified-id of the static member) is looked up as
1343 // if the name was used in a member function of X.
1344 // C++0x [basic.lookup.unqual]p14:
1345 // If a variable member of a namespace is defined outside of the
1346 // scope of its namespace then any name used in the definition of
1347 // the variable member (after the declarator-id) is looked up as
1348 // if the definition of the variable member occurred in its
1349 // namespace.
1350 // Both of these imply that we should push a scope whose context
1351 // is the semantic context of the declaration. We can't use
1352 // PushDeclContext here because that context is not necessarily
1353 // lexically contained in the current context. Fortunately,
1354 // the containing scope should have the appropriate information.
1355
1356 assert(!S->getEntity() && "scope already has entity");
1357
1358#ifndef NDEBUG
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1362#endif
1363
1364 CurContext = DC;
1365 S->setEntity(DC);
1366
1367 if (S->getParent()->isTemplateParamScope()) {
1368 // Also set the corresponding entities for all immediately-enclosing
1369 // template parameter scopes.
1370 EnterTemplatedContext(S->getParent(), DC);
1371 }
1372}
1373
1375 assert(S->getEntity() == CurContext && "Context imbalance!");
1376
1377 // Switch back to the lexical context. The safety of this is
1378 // enforced by an assert in EnterDeclaratorContext.
1379 Scope *Ancestor = S->getParent();
1380 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1381 CurContext = Ancestor->getEntity();
1382
1383 // We don't need to do anything with the scope, which is going to
1384 // disappear.
1385}
1386
1388 assert(S->isTemplateParamScope() &&
1389 "expected to be initializing a template parameter scope");
1390
1391 // C++20 [temp.local]p7:
1392 // In the definition of a member of a class template that appears outside
1393 // of the class template definition, the name of a member of the class
1394 // template hides the name of a template-parameter of any enclosing class
1395 // templates (but not a template-parameter of the member if the member is a
1396 // class or function template).
1397 // C++20 [temp.local]p9:
1398 // In the definition of a class template or in the definition of a member
1399 // of such a template that appears outside of the template definition, for
1400 // each non-dependent base class (13.8.2.1), if the name of the base class
1401 // or the name of a member of the base class is the same as the name of a
1402 // template-parameter, the base class name or member name hides the
1403 // template-parameter name (6.4.10).
1404 //
1405 // This means that a template parameter scope should be searched immediately
1406 // after searching the DeclContext for which it is a template parameter
1407 // scope. For example, for
1408 // template<typename T> template<typename U> template<typename V>
1409 // void N::A<T>::B<U>::f(...)
1410 // we search V then B<U> (and base classes) then U then A<T> (and base
1411 // classes) then T then N then ::.
1412 unsigned ScopeDepth = getTemplateDepth(S);
1413 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1414 DeclContext *SearchDCAfterScope = DC;
1415 for (; DC; DC = DC->getLookupParent()) {
1416 if (const TemplateParameterList *TPL =
1417 cast<Decl>(DC)->getDescribedTemplateParams()) {
1418 unsigned DCDepth = TPL->getDepth() + 1;
1419 if (DCDepth > ScopeDepth)
1420 continue;
1421 if (ScopeDepth == DCDepth)
1422 SearchDCAfterScope = DC = DC->getLookupParent();
1423 break;
1424 }
1425 }
1426 S->setLookupEntity(SearchDCAfterScope);
1427 }
1428}
1429
1431 // We assume that the caller has already called
1432 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1433 FunctionDecl *FD = D->getAsFunction();
1434 if (!FD)
1435 return;
1436
1437 // Same implementation as PushDeclContext, but enters the context
1438 // from the lexical parent, rather than the top-level class.
1439 assert(CurContext == FD->getLexicalParent() &&
1440 "The next DeclContext should be lexically contained in the current one.");
1441 CurContext = FD;
1442 S->setEntity(CurContext);
1443
1444 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1445 ParmVarDecl *Param = FD->getParamDecl(P);
1446 // If the parameter has an identifier, then add it to the scope
1447 if (Param->getIdentifier()) {
1448 S->AddDecl(Param);
1449 IdResolver.AddDecl(Param);
1450 }
1451 }
1452}
1453
1455 // Same implementation as PopDeclContext, but returns to the lexical parent,
1456 // rather than the top-level class.
1457 assert(CurContext && "DeclContext imbalance!");
1459 assert(CurContext && "Popped translation unit!");
1460}
1461
1462/// Determine whether overloading is allowed for a new function
1463/// declaration considering prior declarations of the same name.
1464///
1465/// This routine determines whether overloading is possible, not
1466/// whether a new declaration actually overloads a previous one.
1467/// It will return true in C++ (where overloads are always permitted)
1468/// or, as a C extension, when either the new declaration or a
1469/// previous one is declared with the 'overloadable' attribute.
1471 ASTContext &Context,
1472 const FunctionDecl *New) {
1473 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1474 return true;
1475
1476 // Multiversion function declarations are not overloads in the
1477 // usual sense of that term, but lookup will report that an
1478 // overload set was found if more than one multiversion function
1479 // declaration is present for the same name. It is therefore
1480 // inadequate to assume that some prior declaration(s) had
1481 // the overloadable attribute; checking is required. Since one
1482 // declaration is permitted to omit the attribute, it is necessary
1483 // to check at least two; hence the 'any_of' check below. Note that
1484 // the overloadable attribute is implicitly added to declarations
1485 // that were required to have it but did not.
1486 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1487 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1488 return ND->hasAttr<OverloadableAttr>();
1489 });
1490 } else if (Previous.getResultKind() == LookupResult::Found)
1491 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1492
1493 return false;
1494}
1495
1496void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1497 // Move up the scope chain until we find the nearest enclosing
1498 // non-transparent context. The declaration will be introduced into this
1499 // scope.
1500 while (S->getEntity() && S->getEntity()->isTransparentContext())
1501 S = S->getParent();
1502
1503 // Add scoped declarations into their context, so that they can be
1504 // found later. Declarations without a context won't be inserted
1505 // into any context.
1506 if (AddToContext)
1508
1509 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1510 // are function-local declarations.
1511 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1512 return;
1513
1514 // Template instantiations should also not be pushed into scope.
1515 if (isa<FunctionDecl>(D) &&
1516 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1517 return;
1518
1519 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1520 S->AddDecl(D);
1521 return;
1522 }
1523 // If this replaces anything in the current scope,
1524 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1525 IEnd = IdResolver.end();
1526 for (; I != IEnd; ++I) {
1527 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1528 S->RemoveDecl(*I);
1530
1531 // Should only need to replace one decl.
1532 break;
1533 }
1534 }
1535
1536 S->AddDecl(D);
1537
1538 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1539 // Implicitly-generated labels may end up getting generated in an order that
1540 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1541 // the label at the appropriate place in the identifier chain.
1542 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1543 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1544 if (IDC == CurContext) {
1545 if (!S->isDeclScope(*I))
1546 continue;
1547 } else if (IDC->Encloses(CurContext))
1548 break;
1549 }
1550
1552 } else {
1554 }
1556}
1557
1559 bool AllowInlineNamespace) const {
1560 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1561}
1562
1564 DeclContext *TargetDC = DC->getPrimaryContext();
1565 do {
1566 if (DeclContext *ScopeDC = S->getEntity())
1567 if (ScopeDC->getPrimaryContext() == TargetDC)
1568 return S;
1569 } while ((S = S->getParent()));
1570
1571 return nullptr;
1572}
1573
1575 DeclContext*,
1576 ASTContext&);
1577
1579 bool ConsiderLinkage,
1580 bool AllowInlineNamespace) {
1582 while (F.hasNext()) {
1583 NamedDecl *D = F.next();
1584
1585 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586 continue;
1587
1588 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589 continue;
1590
1591 F.erase();
1592 }
1593
1594 F.done();
1595}
1596
1598 // [module.interface]p7:
1599 // A declaration is attached to a module as follows:
1600 // - If the declaration is a non-dependent friend declaration that nominates a
1601 // function with a declarator-id that is a qualified-id or template-id or that
1602 // nominates a class other than with an elaborated-type-specifier with neither
1603 // a nested-name-specifier nor a simple-template-id, it is attached to the
1604 // module to which the friend is attached ([basic.link]).
1605 if (New->getFriendObjectKind() &&
1609 return false;
1610 }
1611
1612 Module *NewM = New->getOwningModule();
1613 Module *OldM = Old->getOwningModule();
1614
1615 if (NewM && NewM->isPrivateModule())
1616 NewM = NewM->Parent;
1617 if (OldM && OldM->isPrivateModule())
1618 OldM = OldM->Parent;
1619
1620 if (NewM == OldM)
1621 return false;
1622
1623 if (NewM && OldM) {
1624 // A module implementation unit has visibility of the decls in its
1625 // implicitly imported interface.
1626 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1627 return false;
1628
1629 // Partitions are part of the module, but a partition could import another
1630 // module, so verify that the PMIs agree.
1631 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1632 getASTContext().isInSameModule(NewM, OldM))
1633 return false;
1634 }
1635
1636 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1637 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1638 if (NewIsModuleInterface || OldIsModuleInterface) {
1639 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1640 // if a declaration of D [...] appears in the purview of a module, all
1641 // other such declarations shall appear in the purview of the same module
1642 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1643 << New
1644 << NewIsModuleInterface
1645 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1646 << OldIsModuleInterface
1647 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1648 Diag(Old->getLocation(), diag::note_previous_declaration);
1649 New->setInvalidDecl();
1650 return true;
1651 }
1652
1653 return false;
1654}
1655
1657 // [module.interface]p1:
1658 // An export-declaration shall inhabit a namespace scope.
1659 //
1660 // So it is meaningless to talk about redeclaration which is not at namespace
1661 // scope.
1662 if (!New->getLexicalDeclContext()
1664 ->isFileContext() ||
1665 !Old->getLexicalDeclContext()
1667 ->isFileContext())
1668 return false;
1669
1670 bool IsNewExported = New->isInExportDeclContext();
1671 bool IsOldExported = Old->isInExportDeclContext();
1672
1673 // It should be irrevelant if both of them are not exported.
1674 if (!IsNewExported && !IsOldExported)
1675 return false;
1676
1677 if (IsOldExported)
1678 return false;
1679
1680 // If the Old declaration are not attached to named modules
1681 // and the New declaration are attached to global module.
1682 // It should be fine to allow the export since it doesn't change
1683 // the linkage of declarations. See
1684 // https://github.com/llvm/llvm-project/issues/98583 for details.
1685 if (!Old->isInNamedModule() && New->getOwningModule() &&
1687 return false;
1688
1689 assert(IsNewExported);
1690
1691 auto Lk = Old->getFormalLinkage();
1692 int S = 0;
1693 if (Lk == Linkage::Internal)
1694 S = 1;
1695 else if (Lk == Linkage::Module)
1696 S = 2;
1697 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698 Diag(Old->getLocation(), diag::note_previous_declaration);
1699 return true;
1700}
1701
1704 return true;
1705
1706 if (CheckRedeclarationExported(New, Old))
1707 return true;
1708
1709 return false;
1710}
1711
1713 const NamedDecl *Old) const {
1714 assert(getASTContext().isSameEntity(New, Old) &&
1715 "New and Old are not the same definition, we should diagnostic it "
1716 "immediately instead of checking it.");
1717 assert(const_cast<Sema *>(this)->isReachable(New) &&
1718 const_cast<Sema *>(this)->isReachable(Old) &&
1719 "We shouldn't see unreachable definitions here.");
1720
1721 Module *NewM = New->getOwningModule();
1722 Module *OldM = Old->getOwningModule();
1723
1724 // We only checks for named modules here. The header like modules is skipped.
1725 // FIXME: This is not right if we import the header like modules in the module
1726 // purview.
1727 //
1728 // For example, assuming "header.h" provides definition for `D`.
1729 // ```C++
1730 // //--- M.cppm
1731 // export module M;
1732 // import "header.h"; // or #include "header.h" but import it by clang modules
1733 // actually.
1734 //
1735 // //--- Use.cpp
1736 // import M;
1737 // import "header.h"; // or uses clang modules.
1738 // ```
1739 //
1740 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1741 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1742 // reject it. But the current implementation couldn't detect the case since we
1743 // don't record the information about the importee modules.
1744 //
1745 // But this might not be painful in practice. Since the design of C++20 Named
1746 // Modules suggests us to use headers in global module fragment instead of
1747 // module purview.
1748 if (NewM && NewM->isHeaderLikeModule())
1749 NewM = nullptr;
1750 if (OldM && OldM->isHeaderLikeModule())
1751 OldM = nullptr;
1752
1753 if (!NewM && !OldM)
1754 return true;
1755
1756 // [basic.def.odr]p14.3
1757 // Each such definition shall not be attached to a named module
1758 // ([module.unit]).
1759 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1760 return true;
1761
1762 // Then New and Old lives in the same TU if their share one same module unit.
1763 if (NewM)
1764 NewM = NewM->getTopLevelModule();
1765 if (OldM)
1766 OldM = OldM->getTopLevelModule();
1767 return OldM == NewM;
1768}
1769
1771 if (D->getDeclContext()->isFileContext())
1772 return false;
1773
1774 return isa<UsingShadowDecl>(D) ||
1775 isa<UnresolvedUsingTypenameDecl>(D) ||
1776 isa<UnresolvedUsingValueDecl>(D);
1777}
1778
1779/// Removes using shadow declarations not at class scope from the lookup
1780/// results.
1783 while (F.hasNext())
1785 F.erase();
1786
1787 F.done();
1788}
1789
1790/// Check for this common pattern:
1791/// @code
1792/// class S {
1793/// S(const S&); // DO NOT IMPLEMENT
1794/// void operator=(const S&); // DO NOT IMPLEMENT
1795/// };
1796/// @endcode
1798 // FIXME: Should check for private access too but access is set after we get
1799 // the decl here.
1800 if (D->doesThisDeclarationHaveABody())
1801 return false;
1802
1803 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1804 return CD->isCopyConstructor();
1805 return D->isCopyAssignmentOperator();
1806}
1807
1808bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1809 const DeclContext *DC = D->getDeclContext();
1810 while (!DC->isTranslationUnit()) {
1811 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1812 if (!RD->hasNameForLinkage())
1813 return true;
1814 }
1815 DC = DC->getParent();
1816 }
1817
1818 return !D->isExternallyVisible();
1819}
1820
1821// FIXME: This needs to be refactored; some other isInMainFile users want
1822// these semantics.
1823static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1825 return false;
1826 return S.SourceMgr.isInMainFile(Loc);
1827}
1828
1830 assert(D);
1831
1832 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1833 return false;
1834
1835 // Ignore all entities declared within templates, and out-of-line definitions
1836 // of members of class templates.
1839 return false;
1840
1841 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1842 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1843 return false;
1844 // A non-out-of-line declaration of a member specialization was implicitly
1845 // instantiated; it's the out-of-line declaration that we're interested in.
1846 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1847 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1848 return false;
1849
1850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1851 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1852 return false;
1853 } else {
1854 // 'static inline' functions are defined in headers; don't warn.
1855 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1856 return false;
1857 }
1858
1859 if (FD->doesThisDeclarationHaveABody() &&
1861 return false;
1862 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1863 // Constants and utility variables are defined in headers with internal
1864 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1865 // like "inline".)
1866 if (!isMainFileLoc(*this, VD->getLocation()))
1867 return false;
1868
1869 if (Context.DeclMustBeEmitted(VD))
1870 return false;
1871
1872 if (VD->isStaticDataMember() &&
1873 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1874 return false;
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1877 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1878 return false;
1879
1880 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1881 return false;
1882 } else {
1883 return false;
1884 }
1885
1886 // Only warn for unused decls internal to the translation unit.
1887 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1888 // for inline functions defined in the main source file, for instance.
1889 return mightHaveNonExternalLinkage(D);
1890}
1891
1893 if (!D)
1894 return;
1895
1896 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1897 const FunctionDecl *First = FD->getFirstDecl();
1899 return; // First should already be in the vector.
1900 }
1901
1902 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1903 const VarDecl *First = VD->getFirstDecl();
1905 return; // First should already be in the vector.
1906 }
1907
1910}
1911
1912static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1913 const NamedDecl *D) {
1914 if (D->isInvalidDecl())
1915 return false;
1916
1917 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1918 // For a decomposition declaration, warn if none of the bindings are
1919 // referenced, instead of if the variable itself is referenced (which
1920 // it is, by the bindings' expressions).
1921 bool IsAllPlaceholders = true;
1922 for (const auto *BD : DD->bindings()) {
1923 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1924 return false;
1925 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1926 }
1927 if (IsAllPlaceholders)
1928 return false;
1929 } else if (!D->getDeclName()) {
1930 return false;
1931 } else if (D->isReferenced() || D->isUsed()) {
1932 return false;
1933 }
1934
1935 if (D->isPlaceholderVar(LangOpts))
1936 return false;
1937
1938 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1939 D->hasAttr<CleanupAttr>())
1940 return false;
1941
1942 if (isa<LabelDecl>(D))
1943 return true;
1944
1945 // Except for labels, we only care about unused decls that are local to
1946 // functions.
1947 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1948 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1949 // For dependent types, the diagnostic is deferred.
1950 WithinFunction =
1951 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1952 if (!WithinFunction)
1953 return false;
1954
1955 if (isa<TypedefNameDecl>(D))
1956 return true;
1957
1958 // White-list anything that isn't a local variable.
1959 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1960 return false;
1961
1962 // Types of valid local variables should be complete, so this should succeed.
1963 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1964
1965 const Expr *Init = VD->getInit();
1966 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1967 Init = Cleanups->getSubExpr();
1968
1969 const auto *Ty = VD->getType().getTypePtr();
1970
1971 // Only look at the outermost level of typedef.
1972 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1973 // Allow anything marked with __attribute__((unused)).
1974 if (TT->getDecl()->hasAttr<UnusedAttr>())
1975 return false;
1976 }
1977
1978 // Warn for reference variables whose initializtion performs lifetime
1979 // extension.
1980 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1981 MTE && MTE->getExtendingDecl()) {
1982 Ty = VD->getType().getNonReferenceType().getTypePtr();
1983 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1984 }
1985
1986 // If we failed to complete the type for some reason, or if the type is
1987 // dependent, don't diagnose the variable.
1988 if (Ty->isIncompleteType() || Ty->isDependentType())
1989 return false;
1990
1991 // Look at the element type to ensure that the warning behaviour is
1992 // consistent for both scalars and arrays.
1993 Ty = Ty->getBaseElementTypeUnsafe();
1994
1995 if (const TagType *TT = Ty->getAs<TagType>()) {
1996 const TagDecl *Tag = TT->getDecl();
1997 if (Tag->hasAttr<UnusedAttr>())
1998 return false;
1999
2000 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2001 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2002 return false;
2003
2004 if (Init) {
2005 const auto *Construct =
2006 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2007 if (Construct && !Construct->isElidable()) {
2008 const CXXConstructorDecl *CD = Construct->getConstructor();
2009 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2010 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2011 return false;
2012 }
2013
2014 // Suppress the warning if we don't know how this is constructed, and
2015 // it could possibly be non-trivial constructor.
2016 if (Init->isTypeDependent()) {
2017 for (const CXXConstructorDecl *Ctor : RD->ctors())
2018 if (!Ctor->isTrivial())
2019 return false;
2020 }
2021
2022 // Suppress the warning if the constructor is unresolved because
2023 // its arguments are dependent.
2024 if (isa<CXXUnresolvedConstructExpr>(Init))
2025 return false;
2026 }
2027 }
2028 }
2029
2030 // TODO: __attribute__((unused)) templates?
2031 }
2032
2033 return true;
2034}
2035
2037 FixItHint &Hint) {
2038 if (isa<LabelDecl>(D)) {
2040 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2041 /*SkipTrailingWhitespaceAndNewline=*/false);
2042 if (AfterColon.isInvalid())
2043 return;
2046 }
2047}
2048
2051 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2052}
2053
2055 DiagReceiverTy DiagReceiver) {
2056 if (D->getTypeForDecl()->isDependentType())
2057 return;
2058
2059 for (auto *TmpD : D->decls()) {
2060 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2061 DiagnoseUnusedDecl(T, DiagReceiver);
2062 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2063 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2064 }
2065}
2066
2069 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2070}
2071
2074 return;
2075
2076 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2077 // typedefs can be referenced later on, so the diagnostics are emitted
2078 // at end-of-translation-unit.
2080 return;
2081 }
2082
2083 FixItHint Hint;
2085
2086 unsigned DiagID;
2087 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2088 DiagID = diag::warn_unused_exception_param;
2089 else if (isa<LabelDecl>(D))
2090 DiagID = diag::warn_unused_label;
2091 else
2092 DiagID = diag::warn_unused_variable;
2093
2094 SourceLocation DiagLoc = D->getLocation();
2095 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2096}
2097
2099 DiagReceiverTy DiagReceiver) {
2100 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2101 // it's not really unused.
2102 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2103 return;
2104
2105 // In C++, `_` variables behave as if they were maybe_unused
2106 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2107 return;
2108
2109 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2110
2111 if (Ty->isReferenceType() || Ty->isDependentType())
2112 return;
2113
2114 if (const TagType *TT = Ty->getAs<TagType>()) {
2115 const TagDecl *Tag = TT->getDecl();
2116 if (Tag->hasAttr<UnusedAttr>())
2117 return;
2118 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2119 // mimic gcc's behavior.
2120 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2121 RD && !RD->hasAttr<WarnUnusedAttr>())
2122 return;
2123 }
2124
2125 // Don't warn about __block Objective-C pointer variables, as they might
2126 // be assigned in the block but not used elsewhere for the purpose of lifetime
2127 // extension.
2128 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2129 return;
2130
2131 // Don't warn about Objective-C pointer variables with precise lifetime
2132 // semantics; they can be used to ensure ARC releases the object at a known
2133 // time, which may mean assignment but no other references.
2134 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2135 return;
2136
2137 auto iter = RefsMinusAssignments.find(VD);
2138 if (iter == RefsMinusAssignments.end())
2139 return;
2140
2141 assert(iter->getSecond() >= 0 &&
2142 "Found a negative number of references to a VarDecl");
2143 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2144 // Assume the given VarDecl is "used" if its ref count stored in
2145 // `RefMinusAssignments` is positive, with one exception.
2146 //
2147 // For a C++ variable whose decl (with initializer) entirely consist the
2148 // condition expression of a if/while/for construct,
2149 // Clang creates a DeclRefExpr for the condition expression rather than a
2150 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2151 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2152 // used in the body of the if/while/for construct.
2153 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2154 if (!UnusedCXXCondDecl)
2155 return;
2156 }
2157
2158 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2159 : diag::warn_unused_but_set_variable;
2160 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2161}
2162
2164 Sema::DiagReceiverTy DiagReceiver) {
2165 // Verify that we have no forward references left. If so, there was a goto
2166 // or address of a label taken, but no definition of it. Label fwd
2167 // definitions are indicated with a null substmt which is also not a resolved
2168 // MS inline assembly label name.
2169 bool Diagnose = false;
2170 if (L->isMSAsmLabel())
2171 Diagnose = !L->isResolvedMSAsmLabel();
2172 else
2173 Diagnose = L->getStmt() == nullptr;
2174 if (Diagnose)
2175 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2176 << L);
2177}
2178
2180 S->applyNRVO();
2181
2182 if (S->decl_empty()) return;
2183 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2184 "Scope shouldn't contain decls!");
2185
2186 /// We visit the decls in non-deterministic order, but we want diagnostics
2187 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2188 /// and sort the diagnostics before emitting them, after we visited all decls.
2189 struct LocAndDiag {
2191 std::optional<SourceLocation> PreviousDeclLoc;
2193 };
2195 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2196 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2197 };
2198 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2199 SourceLocation PreviousDeclLoc,
2200 PartialDiagnostic PD) {
2201 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2202 };
2203
2204 for (auto *TmpD : S->decls()) {
2205 assert(TmpD && "This decl didn't get pushed??");
2206
2207 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2208 NamedDecl *D = cast<NamedDecl>(TmpD);
2209
2210 // Diagnose unused variables in this scope.
2211 if (!S->hasUnrecoverableErrorOccurred()) {
2212 DiagnoseUnusedDecl(D, addDiag);
2213 if (const auto *RD = dyn_cast<RecordDecl>(D))
2214 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2215 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2216 DiagnoseUnusedButSetDecl(VD, addDiag);
2217 RefsMinusAssignments.erase(VD);
2218 }
2219 }
2220
2221 if (!D->getDeclName()) continue;
2222
2223 // If this was a forward reference to a label, verify it was defined.
2224 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2225 CheckPoppedLabel(LD, *this, addDiag);
2226
2227 // Partial translation units that are created in incremental processing must
2228 // not clean up the IdResolver because PTUs should take into account the
2229 // declarations that came from previous PTUs.
2233
2234 // Warn on it if we are shadowing a declaration.
2235 auto ShadowI = ShadowingDecls.find(D);
2236 if (ShadowI != ShadowingDecls.end()) {
2237 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2238 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2239 PDiag(diag::warn_ctor_parm_shadows_field)
2240 << D << FD << FD->getParent());
2241 }
2242 ShadowingDecls.erase(ShadowI);
2243 }
2244 }
2245
2246 llvm::sort(DeclDiags,
2247 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2248 // The particular order for diagnostics is not important, as long
2249 // as the order is deterministic. Using the raw location is going
2250 // to generally be in source order unless there are macro
2251 // expansions involved.
2252 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2253 });
2254 for (const LocAndDiag &D : DeclDiags) {
2255 Diag(D.Loc, D.PD);
2256 if (D.PreviousDeclLoc)
2257 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2258 }
2259}
2260
2262 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2263 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2264 (S->isClassScope() && !getLangOpts().CPlusPlus))
2265 S = S->getParent();
2266 return S;
2267}
2268
2269static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2271 switch (Error) {
2273 return "";
2275 return BuiltinInfo.getHeaderName(ID);
2277 return "stdio.h";
2279 return "setjmp.h";
2281 return "ucontext.h";
2282 }
2283 llvm_unreachable("unhandled error kind");
2284}
2285
2287 unsigned ID, SourceLocation Loc) {
2289
2290 if (getLangOpts().CPlusPlus) {
2293 CLinkageDecl->setImplicit();
2294 Parent->addDecl(CLinkageDecl);
2295 Parent = CLinkageDecl;
2296 }
2297
2300 assert(getLangOpts().CPlusPlus20 &&
2301 "consteval builtins should only be available in C++20 mode");
2302 ConstexprKind = ConstexprSpecKind::Consteval;
2303 }
2304
2306 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2307 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2308 Type->isFunctionProtoType(), ConstexprKind);
2309 New->setImplicit();
2310 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2311
2312 // Create Decl objects for each parameter, adding them to the
2313 // FunctionDecl.
2314 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2318 Context, New, SourceLocation(), SourceLocation(), nullptr,
2319 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2320 parm->setScopeInfo(0, i);
2321 Params.push_back(parm);
2322 }
2323 New->setParams(Params);
2324 }
2325
2327 return New;
2328}
2329
2331 Scope *S, bool ForRedeclaration,
2334
2336 QualType R = Context.GetBuiltinType(ID, Error);
2337 if (Error) {
2338 if (!ForRedeclaration)
2339 return nullptr;
2340
2341 // If we have a builtin without an associated type we should not emit a
2342 // warning when we were not able to find a type for it.
2343 if (Error == ASTContext::GE_Missing_type ||
2345 return nullptr;
2346
2347 // If we could not find a type for setjmp it is because the jmp_buf type was
2348 // not defined prior to the setjmp declaration.
2349 if (Error == ASTContext::GE_Missing_setjmp) {
2350 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2352 return nullptr;
2353 }
2354
2355 // Generally, we emit a warning that the declaration requires the
2356 // appropriate header.
2357 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2358 << getHeaderName(Context.BuiltinInfo, ID, Error)
2360 return nullptr;
2361 }
2362
2363 if (!ForRedeclaration &&
2366 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2367 : diag::ext_implicit_lib_function_decl)
2368 << Context.BuiltinInfo.getName(ID) << R;
2369 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2370 Diag(Loc, diag::note_include_header_or_declare)
2371 << Header << Context.BuiltinInfo.getName(ID);
2372 }
2373
2374 if (R.isNull())
2375 return nullptr;
2376
2377 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2379
2380 // TUScope is the translation-unit scope to insert this function into.
2381 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2382 // relate Scopes to DeclContexts, and probably eliminate CurContext
2383 // entirely, but we're not there yet.
2384 DeclContext *SavedContext = CurContext;
2385 CurContext = New->getDeclContext();
2387 CurContext = SavedContext;
2388 return New;
2389}
2390
2391/// Typedef declarations don't have linkage, but they still denote the same
2392/// entity if their types are the same.
2393/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2394/// isSameEntity.
2395static void
2398 // This is only interesting when modules are enabled.
2399 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2400 return;
2401
2402 // Empty sets are uninteresting.
2403 if (Previous.empty())
2404 return;
2405
2406 LookupResult::Filter Filter = Previous.makeFilter();
2407 while (Filter.hasNext()) {
2408 NamedDecl *Old = Filter.next();
2409
2410 // Non-hidden declarations are never ignored.
2411 if (S.isVisible(Old))
2412 continue;
2413
2414 // Declarations of the same entity are not ignored, even if they have
2415 // different linkages.
2416 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2417 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2418 Decl->getUnderlyingType()))
2419 continue;
2420
2421 // If both declarations give a tag declaration a typedef name for linkage
2422 // purposes, then they declare the same entity.
2423 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2424 Decl->getAnonDeclWithTypedefName())
2425 continue;
2426 }
2427
2428 Filter.erase();
2429 }
2430
2431 Filter.done();
2432}
2433
2435 QualType OldType;
2436 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2437 OldType = OldTypedef->getUnderlyingType();
2438 else
2439 OldType = Context.getTypeDeclType(Old);
2440 QualType NewType = New->getUnderlyingType();
2441
2442 if (NewType->isVariablyModifiedType()) {
2443 // Must not redefine a typedef with a variably-modified type.
2444 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2445 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2446 << Kind << NewType;
2447 if (Old->getLocation().isValid())
2449 New->setInvalidDecl();
2450 return true;
2451 }
2452
2453 if (OldType != NewType &&
2454 !OldType->isDependentType() &&
2455 !NewType->isDependentType() &&
2456 !Context.hasSameType(OldType, NewType)) {
2457 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2458 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2459 << Kind << NewType << OldType;
2460 if (Old->getLocation().isValid())
2462 New->setInvalidDecl();
2463 return true;
2464 }
2465 return false;
2466}
2467
2469 LookupResult &OldDecls) {
2470 // If the new decl is known invalid already, don't bother doing any
2471 // merging checks.
2472 if (New->isInvalidDecl()) return;
2473
2474 // Allow multiple definitions for ObjC built-in typedefs.
2475 // FIXME: Verify the underlying types are equivalent!
2476 if (getLangOpts().ObjC) {
2477 const IdentifierInfo *TypeID = New->getIdentifier();
2478 switch (TypeID->getLength()) {
2479 default: break;
2480 case 2:
2481 {
2482 if (!TypeID->isStr("id"))
2483 break;
2484 QualType T = New->getUnderlyingType();
2485 if (!T->isPointerType())
2486 break;
2487 if (!T->isVoidPointerType()) {
2489 if (!PT->isStructureType())
2490 break;
2491 }
2493 // Install the built-in type for 'id', ignoring the current definition.
2495 return;
2496 }
2497 case 5:
2498 if (!TypeID->isStr("Class"))
2499 break;
2501 // Install the built-in type for 'Class', ignoring the current definition.
2503 return;
2504 case 3:
2505 if (!TypeID->isStr("SEL"))
2506 break;
2508 // Install the built-in type for 'SEL', ignoring the current definition.
2510 return;
2511 }
2512 // Fall through - the typedef name was not a builtin type.
2513 }
2514
2515 // Verify the old decl was also a type.
2516 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2517 if (!Old) {
2518 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2519 << New->getDeclName();
2520
2521 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2522 if (OldD->getLocation().isValid())
2523 notePreviousDefinition(OldD, New->getLocation());
2524
2525 return New->setInvalidDecl();
2526 }
2527
2528 // If the old declaration is invalid, just give up here.
2529 if (Old->isInvalidDecl())
2530 return New->setInvalidDecl();
2531
2532 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2533 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2534 auto *NewTag = New->getAnonDeclWithTypedefName();
2535 NamedDecl *Hidden = nullptr;
2536 if (OldTag && NewTag &&
2537 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2538 !hasVisibleDefinition(OldTag, &Hidden)) {
2539 // There is a definition of this tag, but it is not visible. Use it
2540 // instead of our tag.
2541 New->setTypeForDecl(OldTD->getTypeForDecl());
2542 if (OldTD->isModed())
2543 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2544 OldTD->getUnderlyingType());
2545 else
2546 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2547
2548 // Make the old tag definition visible.
2550
2551 // If this was an unscoped enumeration, yank all of its enumerators
2552 // out of the scope.
2553 if (isa<EnumDecl>(NewTag)) {
2554 Scope *EnumScope = getNonFieldDeclScope(S);
2555 for (auto *D : NewTag->decls()) {
2556 auto *ED = cast<EnumConstantDecl>(D);
2557 assert(EnumScope->isDeclScope(ED));
2558 EnumScope->RemoveDecl(ED);
2560 ED->getLexicalDeclContext()->removeDecl(ED);
2561 }
2562 }
2563 }
2564 }
2565
2566 // If the typedef types are not identical, reject them in all languages and
2567 // with any extensions enabled.
2568 if (isIncompatibleTypedef(Old, New))
2569 return;
2570
2571 // The types match. Link up the redeclaration chain and merge attributes if
2572 // the old declaration was a typedef.
2573 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2574 New->setPreviousDecl(Typedef);
2575 mergeDeclAttributes(New, Old);
2576 }
2577
2578 if (getLangOpts().MicrosoftExt)
2579 return;
2580
2581 if (getLangOpts().CPlusPlus) {
2582 // C++ [dcl.typedef]p2:
2583 // In a given non-class scope, a typedef specifier can be used to
2584 // redefine the name of any type declared in that scope to refer
2585 // to the type to which it already refers.
2586 if (!isa<CXXRecordDecl>(CurContext))
2587 return;
2588
2589 // C++0x [dcl.typedef]p4:
2590 // In a given class scope, a typedef specifier can be used to redefine
2591 // any class-name declared in that scope that is not also a typedef-name
2592 // to refer to the type to which it already refers.
2593 //
2594 // This wording came in via DR424, which was a correction to the
2595 // wording in DR56, which accidentally banned code like:
2596 //
2597 // struct S {
2598 // typedef struct A { } A;
2599 // };
2600 //
2601 // in the C++03 standard. We implement the C++0x semantics, which
2602 // allow the above but disallow
2603 //
2604 // struct S {
2605 // typedef int I;
2606 // typedef int I;
2607 // };
2608 //
2609 // since that was the intent of DR56.
2610 if (!isa<TypedefNameDecl>(Old))
2611 return;
2612
2613 Diag(New->getLocation(), diag::err_redefinition)
2614 << New->getDeclName();
2616 return New->setInvalidDecl();
2617 }
2618
2619 // Modules always permit redefinition of typedefs, as does C11.
2620 if (getLangOpts().Modules || getLangOpts().C11)
2621 return;
2622
2623 // If we have a redefinition of a typedef in C, emit a warning. This warning
2624 // is normally mapped to an error, but can be controlled with
2625 // -Wtypedef-redefinition. If either the original or the redefinition is
2626 // in a system header, don't emit this for compatibility with GCC.
2627 if (getDiagnostics().getSuppressSystemWarnings() &&
2628 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2629 (Old->isImplicit() ||
2632 return;
2633
2634 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2635 << New->getDeclName();
2637}
2638
2639/// DeclhasAttr - returns true if decl Declaration already has the target
2640/// attribute.
2641static bool DeclHasAttr(const Decl *D, const Attr *A) {
2642 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2643 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2644 for (const auto *i : D->attrs())
2645 if (i->getKind() == A->getKind()) {
2646 if (Ann) {
2647 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2648 return true;
2649 continue;
2650 }
2651 // FIXME: Don't hardcode this check
2652 if (OA && isa<OwnershipAttr>(i))
2653 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2654 return true;
2655 }
2656
2657 return false;
2658}
2659
2661 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2662 return VD->isThisDeclarationADefinition();
2663 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2664 return TD->isCompleteDefinition() || TD->isBeingDefined();
2665 return true;
2666}
2667
2668/// Merge alignment attributes from \p Old to \p New, taking into account the
2669/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2670///
2671/// \return \c true if any attributes were added to \p New.
2672static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2673 // Look for alignas attributes on Old, and pick out whichever attribute
2674 // specifies the strictest alignment requirement.
2675 AlignedAttr *OldAlignasAttr = nullptr;
2676 AlignedAttr *OldStrictestAlignAttr = nullptr;
2677 unsigned OldAlign = 0;
2678 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2679 // FIXME: We have no way of representing inherited dependent alignments
2680 // in a case like:
2681 // template<int A, int B> struct alignas(A) X;
2682 // template<int A, int B> struct alignas(B) X {};
2683 // For now, we just ignore any alignas attributes which are not on the
2684 // definition in such a case.
2685 if (I->isAlignmentDependent())
2686 return false;
2687
2688 if (I->isAlignas())
2689 OldAlignasAttr = I;
2690
2691 unsigned Align = I->getAlignment(S.Context);
2692 if (Align > OldAlign) {
2693 OldAlign = Align;
2694 OldStrictestAlignAttr = I;
2695 }
2696 }
2697
2698 // Look for alignas attributes on New.
2699 AlignedAttr *NewAlignasAttr = nullptr;
2700 unsigned NewAlign = 0;
2701 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2702 if (I->isAlignmentDependent())
2703 return false;
2704
2705 if (I->isAlignas())
2706 NewAlignasAttr = I;
2707
2708 unsigned Align = I->getAlignment(S.Context);
2709 if (Align > NewAlign)
2710 NewAlign = Align;
2711 }
2712
2713 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2714 // Both declarations have 'alignas' attributes. We require them to match.
2715 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2716 // fall short. (If two declarations both have alignas, they must both match
2717 // every definition, and so must match each other if there is a definition.)
2718
2719 // If either declaration only contains 'alignas(0)' specifiers, then it
2720 // specifies the natural alignment for the type.
2721 if (OldAlign == 0 || NewAlign == 0) {
2722 QualType Ty;
2723 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2724 Ty = VD->getType();
2725 else
2726 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2727
2728 if (OldAlign == 0)
2729 OldAlign = S.Context.getTypeAlign(Ty);
2730 if (NewAlign == 0)
2731 NewAlign = S.Context.getTypeAlign(Ty);
2732 }
2733
2734 if (OldAlign != NewAlign) {
2735 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2738 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2739 }
2740 }
2741
2742 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2743 // C++11 [dcl.align]p6:
2744 // if any declaration of an entity has an alignment-specifier,
2745 // every defining declaration of that entity shall specify an
2746 // equivalent alignment.
2747 // C11 6.7.5/7:
2748 // If the definition of an object does not have an alignment
2749 // specifier, any other declaration of that object shall also
2750 // have no alignment specifier.
2751 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2752 << OldAlignasAttr;
2753 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2754 << OldAlignasAttr;
2755 }
2756
2757 bool AnyAdded = false;
2758
2759 // Ensure we have an attribute representing the strictest alignment.
2760 if (OldAlign > NewAlign) {
2761 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2762 Clone->setInherited(true);
2763 New->addAttr(Clone);
2764 AnyAdded = true;
2765 }
2766
2767 // Ensure we have an alignas attribute if the old declaration had one.
2768 if (OldAlignasAttr && !NewAlignasAttr &&
2769 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2770 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2771 Clone->setInherited(true);
2772 New->addAttr(Clone);
2773 AnyAdded = true;
2774 }
2775
2776 return AnyAdded;
2777}
2778
2779#define WANT_DECL_MERGE_LOGIC
2780#include "clang/Sema/AttrParsedAttrImpl.inc"
2781#undef WANT_DECL_MERGE_LOGIC
2782
2784 const InheritableAttr *Attr,
2786 // Diagnose any mutual exclusions between the attribute that we want to add
2787 // and attributes that already exist on the declaration.
2788 if (!DiagnoseMutualExclusions(S, D, Attr))
2789 return false;
2790
2791 // This function copies an attribute Attr from a previous declaration to the
2792 // new declaration D if the new declaration doesn't itself have that attribute
2793 // yet or if that attribute allows duplicates.
2794 // If you're adding a new attribute that requires logic different from
2795 // "use explicit attribute on decl if present, else use attribute from
2796 // previous decl", for example if the attribute needs to be consistent
2797 // between redeclarations, you need to call a custom merge function here.
2798 InheritableAttr *NewAttr = nullptr;
2799 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2800 NewAttr = S.mergeAvailabilityAttr(
2801 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2802 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2803 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2804 AA->getPriority(), AA->getEnvironment());
2805 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2806 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2807 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2808 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2809 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2810 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2811 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2812 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2813 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2814 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2815 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2816 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2817 FA->getFirstArg());
2818 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2819 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2820 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2821 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2822 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2823 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2824 IA->getInheritanceModel());
2825 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2826 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2827 &S.Context.Idents.get(AA->getSpelling()));
2828 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2829 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2830 isa<CUDAGlobalAttr>(Attr))) {
2831 // CUDA target attributes are part of function signature for
2832 // overloading purposes and must not be merged.
2833 return false;
2834 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2835 NewAttr = S.mergeMinSizeAttr(D, *MA);
2836 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2837 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2838 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2839 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2840 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2841 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2842 else if (isa<AlignedAttr>(Attr))
2843 // AlignedAttrs are handled separately, because we need to handle all
2844 // such attributes on a declaration at the same time.
2845 NewAttr = nullptr;
2846 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2847 (AMK == Sema::AMK_Override ||
2850 NewAttr = nullptr;
2851 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2852 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2853 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2854 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2855 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2856 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2857 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2858 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2859 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2860 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2861 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2862 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2863 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2864 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2865 NT->getZ());
2866 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2867 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2868 else if (isa<SuppressAttr>(Attr))
2869 // Do nothing. Each redeclaration should be suppressed separately.
2870 NewAttr = nullptr;
2871 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2872 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2873
2874 if (NewAttr) {
2875 NewAttr->setInherited(true);
2876 D->addAttr(NewAttr);
2877 if (isa<MSInheritanceAttr>(NewAttr))
2878 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2879 return true;
2880 }
2881
2882 return false;
2883}
2884
2885static const NamedDecl *getDefinition(const Decl *D) {
2886 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2887 return TD->getDefinition();
2888 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2889 const VarDecl *Def = VD->getDefinition();
2890 if (Def)
2891 return Def;
2892 return VD->getActingDefinition();
2893 }
2894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2895 const FunctionDecl *Def = nullptr;
2896 if (FD->isDefined(Def, true))
2897 return Def;
2898 }
2899 return nullptr;
2900}
2901
2902static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2903 for (const auto *Attribute : D->attrs())
2904 if (Attribute->getKind() == Kind)
2905 return true;
2906 return false;
2907}
2908
2909/// checkNewAttributesAfterDef - If we already have a definition, check that
2910/// there are no new attributes in this declaration.
2911static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2912 if (!New->hasAttrs())
2913 return;
2914
2915 const NamedDecl *Def = getDefinition(Old);
2916 if (!Def || Def == New)
2917 return;
2918
2919 AttrVec &NewAttributes = New->getAttrs();
2920 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2921 const Attr *NewAttribute = NewAttributes[I];
2922
2923 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2924 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2925 SkipBodyInfo SkipBody;
2926 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2927
2928 // If we're skipping this definition, drop the "alias" attribute.
2929 if (SkipBody.ShouldSkip) {
2930 NewAttributes.erase(NewAttributes.begin() + I);
2931 --E;
2932 continue;
2933 }
2934 } else {
2935 VarDecl *VD = cast<VarDecl>(New);
2936 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2938 ? diag::err_alias_after_tentative
2939 : diag::err_redefinition;
2940 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2941 if (Diag == diag::err_redefinition)
2942 S.notePreviousDefinition(Def, VD->getLocation());
2943 else
2944 S.Diag(Def->getLocation(), diag::note_previous_definition);
2945 VD->setInvalidDecl();
2946 }
2947 ++I;
2948 continue;
2949 }
2950
2951 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2952 // Tentative definitions are only interesting for the alias check above.
2953 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2954 ++I;
2955 continue;
2956 }
2957 }
2958
2959 if (hasAttribute(Def, NewAttribute->getKind())) {
2960 ++I;
2961 continue; // regular attr merging will take care of validating this.
2962 }
2963
2964 if (isa<C11NoReturnAttr>(NewAttribute)) {
2965 // C's _Noreturn is allowed to be added to a function after it is defined.
2966 ++I;
2967 continue;
2968 } else if (isa<UuidAttr>(NewAttribute)) {
2969 // msvc will allow a subsequent definition to add an uuid to a class
2970 ++I;
2971 continue;
2972 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2973 if (AA->isAlignas()) {
2974 // C++11 [dcl.align]p6:
2975 // if any declaration of an entity has an alignment-specifier,
2976 // every defining declaration of that entity shall specify an
2977 // equivalent alignment.
2978 // C11 6.7.5/7:
2979 // If the definition of an object does not have an alignment
2980 // specifier, any other declaration of that object shall also
2981 // have no alignment specifier.
2982 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2983 << AA;
2984 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2985 << AA;
2986 NewAttributes.erase(NewAttributes.begin() + I);
2987 --E;
2988 continue;
2989 }
2990 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2991 // If there is a C definition followed by a redeclaration with this
2992 // attribute then there are two different definitions. In C++, prefer the
2993 // standard diagnostics.
2994 if (!S.getLangOpts().CPlusPlus) {
2995 S.Diag(NewAttribute->getLocation(),
2996 diag::err_loader_uninitialized_redeclaration);
2997 S.Diag(Def->getLocation(), diag::note_previous_definition);
2998 NewAttributes.erase(NewAttributes.begin() + I);
2999 --E;
3000 continue;
3001 }
3002 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3003 cast<VarDecl>(New)->isInline() &&
3004 !cast<VarDecl>(New)->isInlineSpecified()) {
3005 // Don't warn about applying selectany to implicitly inline variables.
3006 // Older compilers and language modes would require the use of selectany
3007 // to make such variables inline, and it would have no effect if we
3008 // honored it.
3009 ++I;
3010 continue;
3011 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3012 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3013 // declarations after definitions.
3014 ++I;
3015 continue;
3016 }
3017
3018 S.Diag(NewAttribute->getLocation(),
3019 diag::warn_attribute_precede_definition);
3020 S.Diag(Def->getLocation(), diag::note_previous_definition);
3021 NewAttributes.erase(NewAttributes.begin() + I);
3022 --E;
3023 }
3024}
3025
3026static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3027 const ConstInitAttr *CIAttr,
3028 bool AttrBeforeInit) {
3029 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3030
3031 // Figure out a good way to write this specifier on the old declaration.
3032 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3033 // enough of the attribute list spelling information to extract that without
3034 // heroics.
3035 std::string SuitableSpelling;
3036 if (S.getLangOpts().CPlusPlus20)
3037 SuitableSpelling = std::string(
3038 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3039 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3040 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3041 InsertLoc, {tok::l_square, tok::l_square,
3042 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3043 S.PP.getIdentifierInfo("require_constant_initialization"),
3044 tok::r_square, tok::r_square}));
3045 if (SuitableSpelling.empty())
3046 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3047 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3048 S.PP.getIdentifierInfo("require_constant_initialization"),
3049 tok::r_paren, tok::r_paren}));
3050 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3051 SuitableSpelling = "constinit";
3052 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3053 SuitableSpelling = "[[clang::require_constant_initialization]]";
3054 if (SuitableSpelling.empty())
3055 SuitableSpelling = "__attribute__((require_constant_initialization))";
3056 SuitableSpelling += " ";
3057
3058 if (AttrBeforeInit) {
3059 // extern constinit int a;
3060 // int a = 0; // error (missing 'constinit'), accepted as extension
3061 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3062 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3063 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3064 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3065 } else {
3066 // int a = 0;
3067 // constinit extern int a; // error (missing 'constinit')
3068 S.Diag(CIAttr->getLocation(),
3069 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3070 : diag::warn_require_const_init_added_too_late)
3071 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3072 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3073 << CIAttr->isConstinit()
3074 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3075 }
3076}
3077
3080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3081 UsedAttr *NewAttr = OldAttr->clone(Context);
3082 NewAttr->setInherited(true);
3083 New->addAttr(NewAttr);
3084 }
3085 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3086 RetainAttr *NewAttr = OldAttr->clone(Context);
3087 NewAttr->setInherited(true);
3088 New->addAttr(NewAttr);
3089 }
3090
3091 if (!Old->hasAttrs() && !New->hasAttrs())
3092 return;
3093
3094 // [dcl.constinit]p1:
3095 // If the [constinit] specifier is applied to any declaration of a
3096 // variable, it shall be applied to the initializing declaration.
3097 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3098 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3099 if (bool(OldConstInit) != bool(NewConstInit)) {
3100 const auto *OldVD = cast<VarDecl>(Old);
3101 auto *NewVD = cast<VarDecl>(New);
3102
3103 // Find the initializing declaration. Note that we might not have linked
3104 // the new declaration into the redeclaration chain yet.
3105 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3106 if (!InitDecl &&
3107 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3108 InitDecl = NewVD;
3109
3110 if (InitDecl == NewVD) {
3111 // This is the initializing declaration. If it would inherit 'constinit',
3112 // that's ill-formed. (Note that we do not apply this to the attribute
3113 // form).
3114 if (OldConstInit && OldConstInit->isConstinit())
3115 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3116 /*AttrBeforeInit=*/true);
3117 } else if (NewConstInit) {
3118 // This is the first time we've been told that this declaration should
3119 // have a constant initializer. If we already saw the initializing
3120 // declaration, this is too late.
3121 if (InitDecl && InitDecl != NewVD) {
3122 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3123 /*AttrBeforeInit=*/false);
3124 NewVD->dropAttr<ConstInitAttr>();
3125 }
3126 }
3127 }
3128
3129 // Attributes declared post-definition are currently ignored.
3130 checkNewAttributesAfterDef(*this, New, Old);
3131
3132 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3133 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3134 if (!OldA->isEquivalent(NewA)) {
3135 // This redeclaration changes __asm__ label.
3136 Diag(New->getLocation(), diag::err_different_asm_label);
3137 Diag(OldA->getLocation(), diag::note_previous_declaration);
3138 }
3139 } else if (Old->isUsed()) {
3140 // This redeclaration adds an __asm__ label to a declaration that has
3141 // already been ODR-used.
3142 Diag(New->getLocation(), diag::err_late_asm_label_name)
3143 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3144 }
3145 }
3146
3147 // Re-declaration cannot add abi_tag's.
3148 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3149 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3150 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3151 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3152 Diag(NewAbiTagAttr->getLocation(),
3153 diag::err_new_abi_tag_on_redeclaration)
3154 << NewTag;
3155 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3156 }
3157 }
3158 } else {
3159 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3160 Diag(Old->getLocation(), diag::note_previous_declaration);
3161 }
3162 }
3163
3164 // This redeclaration adds a section attribute.
3165 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3166 if (auto *VD = dyn_cast<VarDecl>(New)) {
3167 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3168 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3169 Diag(Old->getLocation(), diag::note_previous_declaration);
3170 }
3171 }
3172 }
3173
3174 // Redeclaration adds code-seg attribute.
3175 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3176 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3177 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3178 Diag(New->getLocation(), diag::warn_mismatched_section)
3179 << 0 /*codeseg*/;
3180 Diag(Old->getLocation(), diag::note_previous_declaration);
3181 }
3182
3183 if (!Old->hasAttrs())
3184 return;
3185
3186 bool foundAny = New->hasAttrs();
3187
3188 // Ensure that any moving of objects within the allocated map is done before
3189 // we process them.
3190 if (!foundAny) New->setAttrs(AttrVec());
3191
3192 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3193 // Ignore deprecated/unavailable/availability attributes if requested.
3195 if (isa<DeprecatedAttr>(I) ||
3196 isa<UnavailableAttr>(I) ||
3197 isa<AvailabilityAttr>(I)) {
3198 switch (AMK) {
3199 case AMK_None:
3200 continue;
3201
3202 case AMK_Redeclaration:
3203 case AMK_Override:
3206 LocalAMK = AMK;
3207 break;
3208 }
3209 }
3210
3211 // Already handled.
3212 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3213 continue;
3214
3215 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3216 foundAny = true;
3217 }
3218
3219 if (mergeAlignedAttrs(*this, New, Old))
3220 foundAny = true;
3221
3222 if (!foundAny) New->dropAttrs();
3223}
3224
3225/// mergeParamDeclAttributes - Copy attributes from the old parameter
3226/// to the new one.
3228 const ParmVarDecl *oldDecl,
3229 Sema &S) {
3230 // C++11 [dcl.attr.depend]p2:
3231 // The first declaration of a function shall specify the
3232 // carries_dependency attribute for its declarator-id if any declaration
3233 // of the function specifies the carries_dependency attribute.
3234 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3235 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3236 S.Diag(CDA->getLocation(),
3237 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3238 // Find the first declaration of the parameter.
3239 // FIXME: Should we build redeclaration chains for function parameters?
3240 const FunctionDecl *FirstFD =
3241 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3242 const ParmVarDecl *FirstVD =
3243 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3244 S.Diag(FirstVD->getLocation(),
3245 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3246 }
3247
3248 // HLSL parameter declarations for inout and out must match between
3249 // declarations. In HLSL inout and out are ambiguous at the call site, but
3250 // have different calling behavior, so you cannot overload a method based on a
3251 // difference between inout and out annotations.
3252 if (S.getLangOpts().HLSL) {
3253 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3254 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3255 // We don't need to cover the case where one declaration doesn't have an
3256 // attribute. The only possible case there is if one declaration has an `in`
3257 // attribute and the other declaration has no attribute. This case is
3258 // allowed since parameters are `in` by default.
3259 if (NDAttr && ODAttr &&
3260 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3261 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3262 << NDAttr << newDecl;
3263 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3264 << ODAttr;
3265 }
3266 }
3267
3268 if (!oldDecl->hasAttrs())
3269 return;
3270
3271 bool foundAny = newDecl->hasAttrs();
3272
3273 // Ensure that any moving of objects within the allocated map is
3274 // done before we process them.
3275 if (!foundAny) newDecl->setAttrs(AttrVec());
3276
3277 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3278 if (!DeclHasAttr(newDecl, I)) {
3279 InheritableAttr *newAttr =
3280 cast<InheritableParamAttr>(I->clone(S.Context));
3281 newAttr->setInherited(true);
3282 newDecl->addAttr(newAttr);
3283 foundAny = true;
3284 }
3285 }
3286
3287 if (!foundAny) newDecl->dropAttrs();
3288}
3289
3291 const ASTContext &Ctx) {
3292
3293 auto NoSizeInfo = [&Ctx](QualType Ty) {
3294 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3295 return true;
3296 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3297 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3298 return false;
3299 };
3300
3301 // `type[]` is equivalent to `type *` and `type[*]`.
3302 if (NoSizeInfo(Old) && NoSizeInfo(New))
3303 return true;
3304
3305 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3306 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3307 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3308 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3309 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3310 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3311 return false;
3312 return true;
3313 }
3314
3315 // Only compare size, ignore Size modifiers and CVR.
3316 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3317 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3318 Ctx.getAsConstantArrayType(New)->getSize();
3319 }
3320
3321 // Don't try to compare dependent sized array
3323 return true;
3324 }
3325
3326 return Old == New;
3327}
3328
3329static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3330 const ParmVarDecl *OldParam,
3331 Sema &S) {
3332 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3333 if (auto Newnullability = NewParam->getType()->getNullability()) {
3334 if (*Oldnullability != *Newnullability) {
3335 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3337 *Newnullability,
3339 != 0))
3341 *Oldnullability,
3343 != 0));
3344 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3345 }
3346 } else {
3347 QualType NewT = NewParam->getType();
3348 NewT = S.Context.getAttributedType(
3350 NewT, NewT);
3351 NewParam->setType(NewT);
3352 }
3353 }
3354 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3355 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3356 if (OldParamDT && NewParamDT &&
3357 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3358 QualType OldParamOT = OldParamDT->getOriginalType();
3359 QualType NewParamOT = NewParamDT->getOriginalType();
3360 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3361 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3362 << NewParam << NewParamOT;
3363 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3364 << OldParamOT;
3365 }
3366 }
3367}
3368
3369namespace {
3370
3371/// Used in MergeFunctionDecl to keep track of function parameters in
3372/// C.
3373struct GNUCompatibleParamWarning {
3374 ParmVarDecl *OldParm;
3375 ParmVarDecl *NewParm;
3376 QualType PromotedType;
3377};
3378
3379} // end anonymous namespace
3380
3381// Determine whether the previous declaration was a definition, implicit
3382// declaration, or a declaration.
3383template <typename T>
3384static std::pair<diag::kind, SourceLocation>
3385getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3386 diag::kind PrevDiag;
3387 SourceLocation OldLocation = Old->getLocation();
3388 if (Old->isThisDeclarationADefinition())
3389 PrevDiag = diag::note_previous_definition;
3390 else if (Old->isImplicit()) {
3391 PrevDiag = diag::note_previous_implicit_declaration;
3392 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3393 if (FD->getBuiltinID())
3394 PrevDiag = diag::note_previous_builtin_declaration;
3395 }
3396 if (OldLocation.isInvalid())
3397 OldLocation = New->getLocation();
3398 } else
3399 PrevDiag = diag::note_previous_declaration;
3400 return std::make_pair(PrevDiag, OldLocation);
3401}
3402
3403/// canRedefineFunction - checks if a function can be redefined. Currently,
3404/// only extern inline functions can be redefined, and even then only in
3405/// GNU89 mode.
3406static bool canRedefineFunction(const FunctionDecl *FD,
3407 const LangOptions& LangOpts) {
3408 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3409 !LangOpts.CPlusPlus &&
3410 FD->isInlineSpecified() &&
3411 FD->getStorageClass() == SC_Extern);
3412}
3413
3415 const AttributedType *AT = T->getAs<AttributedType>();
3416 while (AT && !AT->isCallingConv())
3417 AT = AT->getModifiedType()->getAs<AttributedType>();
3418 return AT;
3419}
3420
3421template <typename T>
3422static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3423 const DeclContext *DC = Old->getDeclContext();
3424 if (DC->isRecord())
3425 return false;
3426
3427 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3428 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3429 return true;
3430 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3431 return true;
3432 return false;
3433}
3434
3435template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3436static bool isExternC(VarTemplateDecl *) { return false; }
3437static bool isExternC(FunctionTemplateDecl *) { return false; }
3438
3439/// Check whether a redeclaration of an entity introduced by a
3440/// using-declaration is valid, given that we know it's not an overload
3441/// (nor a hidden tag declaration).
3442template<typename ExpectedDecl>
3444 ExpectedDecl *New) {
3445 // C++11 [basic.scope.declarative]p4:
3446 // Given a set of declarations in a single declarative region, each of
3447 // which specifies the same unqualified name,
3448 // -- they shall all refer to the same entity, or all refer to functions
3449 // and function templates; or
3450 // -- exactly one declaration shall declare a class name or enumeration
3451 // name that is not a typedef name and the other declarations shall all
3452 // refer to the same variable or enumerator, or all refer to functions
3453 // and function templates; in this case the class name or enumeration
3454 // name is hidden (3.3.10).
3455
3456 // C++11 [namespace.udecl]p14:
3457 // If a function declaration in namespace scope or block scope has the
3458 // same name and the same parameter-type-list as a function introduced
3459 // by a using-declaration, and the declarations do not declare the same
3460 // function, the program is ill-formed.
3461
3462 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3463 if (Old &&
3464 !Old->getDeclContext()->getRedeclContext()->Equals(
3465 New->getDeclContext()->getRedeclContext()) &&
3466 !(isExternC(Old) && isExternC(New)))
3467 Old = nullptr;
3468
3469 if (!Old) {
3470 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3471 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3472 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3473 return true;
3474 }
3475 return false;
3476}
3477
3479 const FunctionDecl *B) {
3480 assert(A->getNumParams() == B->getNumParams());
3481
3482 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3483 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3484 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3485 if (AttrA == AttrB)
3486 return true;
3487 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3488 AttrA->isDynamic() == AttrB->isDynamic();
3489 };
3490
3491 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3492}
3493
3494/// If necessary, adjust the semantic declaration context for a qualified
3495/// declaration to name the correct inline namespace within the qualifier.
3497 DeclaratorDecl *OldD) {
3498 // The only case where we need to update the DeclContext is when
3499 // redeclaration lookup for a qualified name finds a declaration
3500 // in an inline namespace within the context named by the qualifier:
3501 //
3502 // inline namespace N { int f(); }
3503 // int ::f(); // Sema DC needs adjusting from :: to N::.
3504 //
3505 // For unqualified declarations, the semantic context *can* change
3506 // along the redeclaration chain (for local extern declarations,
3507 // extern "C" declarations, and friend declarations in particular).
3508 if (!NewD->getQualifier())
3509 return;
3510
3511 // NewD is probably already in the right context.
3512 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3513 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3514 if (NamedDC->Equals(SemaDC))
3515 return;
3516
3517 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3518 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3519 "unexpected context for redeclaration");
3520
3521 auto *LexDC = NewD->getLexicalDeclContext();
3522 auto FixSemaDC = [=](NamedDecl *D) {
3523 if (!D)
3524 return;
3525 D->setDeclContext(SemaDC);
3526 D->setLexicalDeclContext(LexDC);
3527 };
3528
3529 FixSemaDC(NewD);
3530 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3531 FixSemaDC(FD->getDescribedFunctionTemplate());
3532 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3533 FixSemaDC(VD->getDescribedVarTemplate());
3534}
3535
3537 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3538 // Verify the old decl was also a function.
3539 FunctionDecl *Old = OldD->getAsFunction();
3540 if (!Old) {
3541 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3542 if (New->getFriendObjectKind()) {
3543 Diag(New->getLocation(), diag::err_using_decl_friend);
3544 Diag(Shadow->getTargetDecl()->getLocation(),
3545 diag::note_using_decl_target);
3546 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3547 << 0;
3548 return true;
3549 }
3550
3551 // Check whether the two declarations might declare the same function or
3552 // function template.
3553 if (FunctionTemplateDecl *NewTemplate =
3555 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3556 NewTemplate))
3557 return true;
3558 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3559 ->getAsFunction();
3560 } else {
3561 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3562 return true;
3563 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3564 }
3565 } else {
3566 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3567 << New->getDeclName();
3568 notePreviousDefinition(OldD, New->getLocation());
3569 return true;
3570 }
3571 }
3572
3573 // If the old declaration was found in an inline namespace and the new
3574 // declaration was qualified, update the DeclContext to match.
3576
3577 // If the old declaration is invalid, just give up here.
3578 if (Old->isInvalidDecl())
3579 return true;
3580
3581 // Disallow redeclaration of some builtins.
3582 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3583 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3584 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3585 << Old << Old->getType();
3586 return true;
3587 }
3588
3589 diag::kind PrevDiag;
3590 SourceLocation OldLocation;
3591 std::tie(PrevDiag, OldLocation) =
3593
3594 // Don't complain about this if we're in GNU89 mode and the old function
3595 // is an extern inline function.
3596 // Don't complain about specializations. They are not supposed to have
3597 // storage classes.
3598 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3599 New->getStorageClass() == SC_Static &&
3600 Old->hasExternalFormalLinkage() &&
3603 if (getLangOpts().MicrosoftExt) {
3604 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3605 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3606 } else {
3607 Diag(New->getLocation(), diag::err_static_non_static) << New;
3608 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3609 return true;
3610 }
3611 }
3612
3613 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3614 if (!Old->hasAttr<InternalLinkageAttr>()) {
3615 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3616 << ILA;
3617 Diag(Old->getLocation(), diag::note_previous_declaration);
3618 New->dropAttr<InternalLinkageAttr>();
3619 }
3620
3621 if (auto *EA = New->getAttr<ErrorAttr>()) {
3622 if (!Old->hasAttr<ErrorAttr>()) {
3623 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3624 Diag(Old->getLocation(), diag::note_previous_declaration);
3625 New->dropAttr<ErrorAttr>();
3626 }
3627 }
3628
3629 if (CheckRedeclarationInModule(New, Old))
3630 return true;
3631
3632 if (!getLangOpts().CPlusPlus) {
3633 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3634 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3635 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3636 << New << OldOvl;
3637
3638 // Try our best to find a decl that actually has the overloadable
3639 // attribute for the note. In most cases (e.g. programs with only one
3640 // broken declaration/definition), this won't matter.
3641 //
3642 // FIXME: We could do this if we juggled some extra state in
3643 // OverloadableAttr, rather than just removing it.
3644 const Decl *DiagOld = Old;
3645 if (OldOvl) {
3646 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3647 const auto *A = D->getAttr<OverloadableAttr>();
3648 return A && !A->isImplicit();
3649 });
3650 // If we've implicitly added *all* of the overloadable attrs to this
3651 // chain, emitting a "previous redecl" note is pointless.
3652 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3653 }
3654
3655 if (DiagOld)
3656 Diag(DiagOld->getLocation(),
3657 diag::note_attribute_overloadable_prev_overload)
3658 << OldOvl;
3659
3660 if (OldOvl)
3661 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3662 else
3663 New->dropAttr<OverloadableAttr>();
3664 }
3665 }
3666
3667 // It is not permitted to redeclare an SME function with different SME
3668 // attributes.
3669 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3670 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3671 << New->getType() << Old->getType();
3672 Diag(OldLocation, diag::note_previous_declaration);
3673 return true;
3674 }
3675
3676 // If a function is first declared with a calling convention, but is later
3677 // declared or defined without one, all following decls assume the calling
3678 // convention of the first.
3679 //
3680 // It's OK if a function is first declared without a calling convention,
3681 // but is later declared or defined with the default calling convention.
3682 //
3683 // To test if either decl has an explicit calling convention, we look for
3684 // AttributedType sugar nodes on the type as written. If they are missing or
3685 // were canonicalized away, we assume the calling convention was implicit.
3686 //
3687 // Note also that we DO NOT return at this point, because we still have
3688 // other tests to run.
3689 QualType OldQType = Context.getCanonicalType(Old->getType());
3690 QualType NewQType = Context.getCanonicalType(New->getType());
3691 const FunctionType *OldType = cast<FunctionType>(OldQType);
3692 const FunctionType *NewType = cast<FunctionType>(NewQType);
3693 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3694 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3695 bool RequiresAdjustment = false;
3696
3697 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3699 const FunctionType *FT =
3700 First->getType().getCanonicalType()->castAs<FunctionType>();
3702 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3703 if (!NewCCExplicit) {
3704 // Inherit the CC from the previous declaration if it was specified
3705 // there but not here.
3706 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3707 RequiresAdjustment = true;
3708 } else if (Old->getBuiltinID()) {
3709 // Builtin attribute isn't propagated to the new one yet at this point,
3710 // so we check if the old one is a builtin.
3711
3712 // Calling Conventions on a Builtin aren't really useful and setting a
3713 // default calling convention and cdecl'ing some builtin redeclarations is
3714 // common, so warn and ignore the calling convention on the redeclaration.
3715 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3716 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3718 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3719 RequiresAdjustment = true;
3720 } else {
3721 // Calling conventions aren't compatible, so complain.
3722 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3723 Diag(New->getLocation(), diag::err_cconv_change)
3724 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3725 << !FirstCCExplicit
3726 << (!FirstCCExplicit ? "" :
3728
3729 // Put the note on the first decl, since it is the one that matters.
3730 Diag(First->getLocation(), diag::note_previous_declaration);
3731 return true;
3732 }
3733 }
3734
3735 // FIXME: diagnose the other way around?
3736 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3737 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3738 RequiresAdjustment = true;
3739 }
3740
3741 // Merge regparm attribute.
3742 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3743 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3744 if (NewTypeInfo.getHasRegParm()) {
3745 Diag(New->getLocation(), diag::err_regparm_mismatch)
3746 << NewType->getRegParmType()
3747 << OldType->getRegParmType();
3748 Diag(OldLocation, diag::note_previous_declaration);
3749 return true;
3750 }
3751
3752 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3753 RequiresAdjustment = true;
3754 }
3755
3756 // Merge ns_returns_retained attribute.
3757 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3758 if (NewTypeInfo.getProducesResult()) {
3759 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3760 << "'ns_returns_retained'";
3761 Diag(OldLocation, diag::note_previous_declaration);
3762 return true;
3763 }
3764
3765 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3766 RequiresAdjustment = true;
3767 }
3768
3769 if (OldTypeInfo.getNoCallerSavedRegs() !=
3770 NewTypeInfo.getNoCallerSavedRegs()) {
3771 if (NewTypeInfo.getNoCallerSavedRegs()) {
3772 AnyX86NoCallerSavedRegistersAttr *Attr =
3773 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3774 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3775 Diag(OldLocation, diag::note_previous_declaration);
3776 return true;
3777 }
3778
3779 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3780 RequiresAdjustment = true;
3781 }
3782
3783 if (RequiresAdjustment) {
3786 New->setType(QualType(AdjustedType, 0));
3787 NewQType = Context.getCanonicalType(New->getType());
3788 }
3789
3790 // If this redeclaration makes the function inline, we may need to add it to
3791 // UndefinedButUsed.
3792 if (!Old->isInlined() && New->isInlined() &&
3793 !New->hasAttr<GNUInlineAttr>() &&
3794 !getLangOpts().GNUInline &&
3795 Old->isUsed(false) &&
3796 !Old->isDefined() && !New->isThisDeclarationADefinition())
3797 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798 SourceLocation()));
3799
3800 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3801 // about it.
3802 if (New->hasAttr<GNUInlineAttr>() &&
3803 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3804 UndefinedButUsed.erase(Old->getCanonicalDecl());
3805 }
3806
3807 // If pass_object_size params don't match up perfectly, this isn't a valid
3808 // redeclaration.
3809 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3811 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3812 << New->getDeclName();
3813 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3814 return true;
3815 }
3816
3817 QualType OldQTypeForComparison = OldQType;
3819 const auto OldFX = Old->getFunctionEffects();
3820 const auto NewFX = New->getFunctionEffects();
3821 if (OldFX != NewFX) {
3822 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
3823 for (const auto &Diff : Diffs) {
3824 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3825 Diag(New->getLocation(),
3826 diag::warn_mismatched_func_effect_redeclaration)
3827 << Diff.effectName();
3828 Diag(Old->getLocation(), diag::note_previous_declaration);
3829 }
3830 }
3831 // Following a warning, we could skip merging effects from the previous
3832 // declaration, but that would trigger an additional "conflicting types"
3833 // error.
3834 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3836 FunctionEffectSet MergedFX =
3837 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3838 if (!MergeErrs.empty())
3840 Old->getLocation());
3841
3842 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3843 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3844 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3845 NewFPT->getParamTypes(), EPI);
3846
3847 New->setType(ModQT);
3848 NewQType = New->getType();
3849
3850 // Revise OldQTForComparison to include the merged effects,
3851 // so as not to fail due to differences later.
3852 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3853 EPI = OldFPT->getExtProtoInfo();
3854 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3855 OldQTypeForComparison = Context.getFunctionType(
3856 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3857 }
3858 }
3859 }
3860 }
3861
3862 if (getLangOpts().CPlusPlus) {
3863 OldQType = Context.getCanonicalType(Old->getType());
3864 NewQType = Context.getCanonicalType(New->getType());
3865
3866 // Go back to the type source info to compare the declared return types,
3867 // per C++1y [dcl.type.auto]p13:
3868 // Redeclarations or specializations of a function or function template
3869 // with a declared return type that uses a placeholder type shall also
3870 // use that placeholder, not a deduced type.
3871 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3872 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3873 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3874 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3875 OldDeclaredReturnType)) {
3876 QualType ResQT;
3877 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3878 OldDeclaredReturnType->isObjCObjectPointerType())
3879 // FIXME: This does the wrong thing for a deduced return type.
3880 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3881 if (ResQT.isNull()) {
3882 if (New->isCXXClassMember() && New->isOutOfLine())
3883 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3884 << New << New->getReturnTypeSourceRange();
3885 else
3886 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3887 << New->getReturnTypeSourceRange();
3888 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3889 << Old->getReturnTypeSourceRange();
3890 return true;
3891 }
3892 else
3893 NewQType = ResQT;
3894 }
3895
3896 QualType OldReturnType = OldType->getReturnType();
3897 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3898 if (OldReturnType != NewReturnType) {
3899 // If this function has a deduced return type and has already been
3900 // defined, copy the deduced value from the old declaration.
3901 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3902 if (OldAT && OldAT->isDeduced()) {
3903 QualType DT = OldAT->getDeducedType();
3904 if (DT.isNull()) {
3906 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3907 } else {
3908 New->setType(SubstAutoType(New->getType(), DT));
3909 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3910 }
3911 }
3912 }
3913
3914 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3915 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3916 if (OldMethod && NewMethod) {
3917 // Preserve triviality.
3918 NewMethod->setTrivial(OldMethod->isTrivial());
3919
3920 // MSVC allows explicit template specialization at class scope:
3921 // 2 CXXMethodDecls referring to the same function will be injected.
3922 // We don't want a redeclaration error.
3923 bool IsClassScopeExplicitSpecialization =
3924 OldMethod->isFunctionTemplateSpecialization() &&
3926 bool isFriend = NewMethod->getFriendObjectKind();
3927
3928 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3929 !IsClassScopeExplicitSpecialization) {
3930 // -- Member function declarations with the same name and the
3931 // same parameter types cannot be overloaded if any of them
3932 // is a static member function declaration.
3933 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3934 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3935 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3936 return true;
3937 }
3938
3939 // C++ [class.mem]p1:
3940 // [...] A member shall not be declared twice in the
3941 // member-specification, except that a nested class or member
3942 // class template can be declared and then later defined.
3943 if (!inTemplateInstantiation()) {
3944 unsigned NewDiag;
3945 if (isa<CXXConstructorDecl>(OldMethod))
3946 NewDiag = diag::err_constructor_redeclared;
3947 else if (isa<CXXDestructorDecl>(NewMethod))
3948 NewDiag = diag::err_destructor_redeclared;
3949 else if (isa<CXXConversionDecl>(NewMethod))
3950 NewDiag = diag::err_conv_function_redeclared;
3951 else
3952 NewDiag = diag::err_member_redeclared;
3953
3954 Diag(New->getLocation(), NewDiag);
3955 } else {
3956 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3957 << New << New->getType();
3958 }
3959 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3960 return true;
3961
3962 // Complain if this is an explicit declaration of a special
3963 // member that was initially declared implicitly.
3964 //
3965 // As an exception, it's okay to befriend such methods in order
3966 // to permit the implicit constructor/destructor/operator calls.
3967 } else if (OldMethod->isImplicit()) {
3968 if (isFriend) {
3969 NewMethod->setImplicit();
3970 } else {
3971 Diag(NewMethod->getLocation(),
3972 diag::err_definition_of_implicitly_declared_member)
3973 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3974 return true;
3975 }
3976 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3977 Diag(NewMethod->getLocation(),
3978 diag::err_definition_of_explicitly_defaulted_member)
3979 << llvm::to_underlying(getSpecialMember(OldMethod));
3980 return true;
3981 }
3982 }
3983
3984 // C++1z [over.load]p2
3985 // Certain function declarations cannot be overloaded:
3986 // -- Function declarations that differ only in the return type,
3987 // the exception specification, or both cannot be overloaded.
3988
3989 // Check the exception specifications match. This may recompute the type of
3990 // both Old and New if it resolved exception specifications, so grab the
3991 // types again after this. Because this updates the type, we do this before
3992 // any of the other checks below, which may update the "de facto" NewQType
3993 // but do not necessarily update the type of New.
3994 if (CheckEquivalentExceptionSpec(Old, New))
3995 return true;
3996
3997 // C++11 [dcl.attr.noreturn]p1:
3998 // The first declaration of a function shall specify the noreturn
3999 // attribute if any declaration of that function specifies the noreturn
4000 // attribute.
4001 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4002 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4003 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4004 << NRA;
4005 Diag(Old->getLocation(), diag::note_previous_declaration);
4006 }
4007
4008 // C++11 [dcl.attr.depend]p2:
4009 // The first declaration of a function shall specify the
4010 // carries_dependency attribute for its declarator-id if any declaration
4011 // of the function specifies the carries_dependency attribute.
4012 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4013 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4014 Diag(CDA->getLocation(),
4015 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4016 Diag(Old->getFirstDecl()->getLocation(),
4017 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4018 }
4019
4020 // (C++98 8.3.5p3):
4021 // All declarations for a function shall agree exactly in both the
4022 // return type and the parameter-type-list.
4023 // We also want to respect all the extended bits except noreturn.
4024
4025 // noreturn should now match unless the old type info didn't have it.
4026 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4027 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4028 const FunctionType *OldTypeForComparison
4029 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4030 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4031 assert(OldQTypeForComparison.isCanonical());
4032 }
4033
4034 if (haveIncompatibleLanguageLinkages(Old, New)) {
4035 // As a special case, retain the language linkage from previous
4036 // declarations of a friend function as an extension.
4037 //
4038 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4039 // and is useful because there's otherwise no way to specify language
4040 // linkage within class scope.
4041 //
4042 // Check cautiously as the friend object kind isn't yet complete.
4043 if (New->getFriendObjectKind() != Decl::FOK_None) {
4044 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4045 Diag(OldLocation, PrevDiag);
4046 } else {
4047 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4048 Diag(OldLocation, PrevDiag);
4049 return true;
4050 }
4051 }
4052
4053 // If the function types are compatible, merge the declarations. Ignore the
4054 // exception specifier because it was already checked above in
4055 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4056 // about incompatible types under -fms-compatibility.
4057 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4058 NewQType))
4059 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4060
4061 // If the types are imprecise (due to dependent constructs in friends or
4062 // local extern declarations), it's OK if they differ. We'll check again
4063 // during instantiation.
4064 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4065 return false;
4066
4067 // Fall through for conflicting redeclarations and redefinitions.
4068 }
4069
4070 // C: Function types need to be compatible, not identical. This handles
4071 // duplicate function decls like "void f(int); void f(enum X);" properly.
4072 if (!getLangOpts().CPlusPlus) {
4073 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4074 // type is specified by a function definition that contains a (possibly
4075 // empty) identifier list, both shall agree in the number of parameters
4076 // and the type of each parameter shall be compatible with the type that
4077 // results from the application of default argument promotions to the
4078 // type of the corresponding identifier. ...
4079 // This cannot be handled by ASTContext::typesAreCompatible() because that
4080 // doesn't know whether the function type is for a definition or not when
4081 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4082 // we need to cover here is that the number of arguments agree as the
4083 // default argument promotion rules were already checked by
4084 // ASTContext::typesAreCompatible().
4085 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4086 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4087 if (Old->hasInheritedPrototype())
4088 Old = Old->getCanonicalDecl();
4089 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4090 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4091 return true;
4092 }
4093
4094 // If we are merging two functions where only one of them has a prototype,
4095 // we may have enough information to decide to issue a diagnostic that the
4096 // function without a prototype will change behavior in C23. This handles
4097 // cases like:
4098 // void i(); void i(int j);
4099 // void i(int j); void i();
4100 // void i(); void i(int j) {}
4101 // See ActOnFinishFunctionBody() for other cases of the behavior change
4102 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4103 // type without a prototype.
4104 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4105 !New->isImplicit() && !Old->isImplicit()) {
4106 const FunctionDecl *WithProto, *WithoutProto;
4107 if (New->hasWrittenPrototype()) {
4108 WithProto = New;
4109 WithoutProto = Old;
4110 } else {
4111 WithProto = Old;
4112 WithoutProto = New;
4113 }
4114
4115 if (WithProto->getNumParams() != 0) {
4116 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4117 // The one without the prototype will be changing behavior in C23, so
4118 // warn about that one so long as it's a user-visible declaration.
4119 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4120 if (WithoutProto == New)
4121 IsWithoutProtoADef = NewDeclIsDefn;
4122 else
4123 IsWithProtoADef = NewDeclIsDefn;
4124 Diag(WithoutProto->getLocation(),
4125 diag::warn_non_prototype_changes_behavior)
4126 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4127 << (WithoutProto == Old) << IsWithProtoADef;
4128
4129 // The reason the one without the prototype will be changing behavior
4130 // is because of the one with the prototype, so note that so long as
4131 // it's a user-visible declaration. There is one exception to this:
4132 // when the new declaration is a definition without a prototype, the
4133 // old declaration with a prototype is not the cause of the issue,
4134 // and that does not need to be noted because the one with a
4135 // prototype will not change behavior in C23.
4136 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4137 !IsWithoutProtoADef)
4138 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4139 }
4140 }
4141 }
4142
4143 if (Context.typesAreCompatible(OldQType, NewQType)) {
4144 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4145 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4146 const FunctionProtoType *OldProto = nullptr;
4147 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4148 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4149 // The old declaration provided a function prototype, but the
4150 // new declaration does not. Merge in the prototype.
4151 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4152 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4153 OldProto->getParamTypes(),
4154 OldProto->getExtProtoInfo());
4155 New->setType(NewQType);
4157
4158 // Synthesize parameters with the same types.
4160 for (const auto &ParamType : OldProto->param_types()) {
4162 Context, New, SourceLocation(), SourceLocation(), nullptr,
4163 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4164 Param->setScopeInfo(0, Params.size());
4165 Param->setImplicit();
4166 Params.push_back(Param);
4167 }
4168
4169 New->setParams(Params);
4170 }
4171
4172 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4173 }
4174 }
4175
4176 // Check if the function types are compatible when pointer size address
4177 // spaces are ignored.
4178 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4179 return false;
4180
4181 // GNU C permits a K&R definition to follow a prototype declaration
4182 // if the declared types of the parameters in the K&R definition
4183 // match the types in the prototype declaration, even when the
4184 // promoted types of the parameters from the K&R definition differ
4185 // from the types in the prototype. GCC then keeps the types from
4186 // the prototype.
4187 //
4188 // If a variadic prototype is followed by a non-variadic K&R definition,
4189 // the K&R definition becomes variadic. This is sort of an edge case, but
4190 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4191 // C99 6.9.1p8.
4192 if (!getLangOpts().CPlusPlus &&
4193 Old->hasPrototype() && !New->hasPrototype() &&
4194 New->getType()->getAs<FunctionProtoType>() &&
4195 Old->getNumParams() == New->getNumParams()) {
4198 const FunctionProtoType *OldProto
4199 = Old->getType()->getAs<FunctionProtoType>();
4200 const FunctionProtoType *NewProto
4201 = New->getType()->getAs<FunctionProtoType>();
4202
4203 // Determine whether this is the GNU C extension.
4204 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4205 NewProto->getReturnType());
4206 bool LooseCompatible = !MergedReturn.isNull();
4207 for (unsigned Idx = 0, End = Old->getNumParams();
4208 LooseCompatible && Idx != End; ++Idx) {
4209 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4210 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4211 if (Context.typesAreCompatible(OldParm->getType(),
4212 NewProto->getParamType(Idx))) {
4213 ArgTypes.push_back(NewParm->getType());
4214 } else if (Context.typesAreCompatible(OldParm->getType(),
4215 NewParm->getType(),
4216 /*CompareUnqualified=*/true)) {
4217 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4218 NewProto->getParamType(Idx) };
4219 Warnings.push_back(Warn);
4220 ArgTypes.push_back(NewParm->getType());
4221 } else
4222 LooseCompatible = false;
4223 }
4224
4225 if (LooseCompatible) {
4226 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4227 Diag(Warnings[Warn].NewParm->getLocation(),
4228 diag::ext_param_promoted_not_compatible_with_prototype)
4229 << Warnings[Warn].PromotedType
4230 << Warnings[Warn].OldParm->getType();
4231 if (Warnings[Warn].OldParm->getLocation().isValid())
4232 Diag(Warnings[Warn].OldParm->getLocation(),
4233 diag::note_previous_declaration);
4234 }
4235
4236 if (MergeTypeWithOld)
4237 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4238 OldProto->getExtProtoInfo()));
4239 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4240 }
4241
4242 // Fall through to diagnose conflicting types.
4243 }
4244
4245 // A function that has already been declared has been redeclared or
4246 // defined with a different type; show an appropriate diagnostic.
4247
4248 // If the previous declaration was an implicitly-generated builtin
4249 // declaration, then at the very least we should use a specialized note.
4250 unsigned BuiltinID;
4251 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4252 // If it's actually a library-defined builtin function like 'malloc'
4253 // or 'printf', just warn about the incompatible redeclaration.
4255 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4256 Diag(OldLocation, diag::note_previous_builtin_declaration)
4257 << Old << Old->getType();
4258 return false;
4259 }
4260
4261 PrevDiag = diag::note_previous_builtin_declaration;
4262 }
4263
4264 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4265 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4266 return true;
4267}
4268
4270 Scope *S, bool MergeTypeWithOld) {
4271 // Merge the attributes
4272 mergeDeclAttributes(New, Old);
4273
4274 // Merge "pure" flag.
4275 if (Old->isPureVirtual())
4276 New->setIsPureVirtual();
4277
4278 // Merge "used" flag.
4279 if (Old->getMostRecentDecl()->isUsed(false))
4280 New->setIsUsed();
4281
4282 // Merge attributes from the parameters. These can mismatch with K&R
4283 // declarations.
4284 if (New->getNumParams() == Old->getNumParams())
4285 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4286 ParmVarDecl *NewParam = New->getParamDecl(i);
4287 ParmVarDecl *OldParam = Old->getParamDecl(i);
4288 mergeParamDeclAttributes(NewParam, OldParam, *this);
4289 mergeParamDeclTypes(NewParam, OldParam, *this);
4290 }
4291
4292 if (getLangOpts().CPlusPlus)
4293 return MergeCXXFunctionDecl(New, Old, S);
4294
4295 // Merge the function types so the we get the composite types for the return
4296 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4297 // was visible.
4298 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4299 if (!Merged.isNull() && MergeTypeWithOld)
4300 New->setType(Merged);
4301
4302 return false;
4303}
4304
4306 ObjCMethodDecl *oldMethod) {
4307 // Merge the attributes, including deprecated/unavailable
4308 AvailabilityMergeKind MergeKind =
4309 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4312 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4313 : AMK_Override;
4314
4315 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4316
4317 // Merge attributes from the parameters.
4319 oe = oldMethod->param_end();
4321 ni = newMethod->param_begin(), ne = newMethod->param_end();
4322 ni != ne && oi != oe; ++ni, ++oi)
4323 mergeParamDeclAttributes(*ni, *oi, *this);
4324
4325 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4326}
4327
4329 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4330
4332 ? diag::err_redefinition_different_type
4333 : diag::err_redeclaration_different_type)
4334 << New->getDeclName() << New->getType() << Old->getType();
4335
4336 diag::kind PrevDiag;
4337 SourceLocation OldLocation;
4338 std::tie(PrevDiag, OldLocation)
4340 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4341 New->setInvalidDecl();
4342}
4343
4345 bool MergeTypeWithOld) {
4346 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4347 return;
4348
4349 QualType MergedT;
4350 if (getLangOpts().CPlusPlus) {
4351 if (New->getType()->isUndeducedType()) {
4352 // We don't know what the new type is until the initializer is attached.
4353 return;
4354 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4355 // These could still be something that needs exception specs checked.
4356 return MergeVarDeclExceptionSpecs(New, Old);
4357 }
4358 // C++ [basic.link]p10:
4359 // [...] the types specified by all declarations referring to a given
4360 // object or function shall be identical, except that declarations for an
4361 // array object can specify array types that differ by the presence or
4362 // absence of a major array bound (8.3.4).
4363 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4364 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4365 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4366
4367 // We are merging a variable declaration New into Old. If it has an array
4368 // bound, and that bound differs from Old's bound, we should diagnose the
4369 // mismatch.
4370 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4371 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4372 PrevVD = PrevVD->getPreviousDecl()) {
4373 QualType PrevVDTy = PrevVD->getType();
4374 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4375 continue;
4376
4377 if (!Context.hasSameType(New->getType(), PrevVDTy))
4378 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4379 }
4380 }
4381
4382 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4383 if (Context.hasSameType(OldArray->getElementType(),
4384 NewArray->getElementType()))
4385 MergedT = New->getType();
4386 }
4387 // FIXME: Check visibility. New is hidden but has a complete type. If New
4388 // has no array bound, it should not inherit one from Old, if Old is not
4389 // visible.
4390 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4391 if (Context.hasSameType(OldArray->getElementType(),
4392 NewArray->getElementType()))
4393 MergedT = Old->getType();
4394 }
4395 }
4396 else if (New->getType()->isObjCObjectPointerType() &&
4397 Old->getType()->isObjCObjectPointerType()) {
4398 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4399 Old->getType());
4400 }
4401 } else {
4402 // C 6.2.7p2:
4403 // All declarations that refer to the same object or function shall have
4404 // compatible type.
4405 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4406 }
4407 if (MergedT.isNull()) {
4408 // It's OK if we couldn't merge types if either type is dependent, for a
4409 // block-scope variable. In other cases (static data members of class
4410 // templates, variable templates, ...), we require the types to be
4411 // equivalent.
4412 // FIXME: The C++ standard doesn't say anything about this.
4413 if ((New->getType()->isDependentType() ||
4414 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4415 // If the old type was dependent, we can't merge with it, so the new type
4416 // becomes dependent for now. We'll reproduce the original type when we
4417 // instantiate the TypeSourceInfo for the variable.
4418 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4420 return;
4421 }
4422 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4423 }
4424
4425 // Don't actually update the type on the new declaration if the old
4426 // declaration was an extern declaration in a different scope.
4427 if (MergeTypeWithOld)
4428 New->setType(MergedT);
4429}
4430
4431static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4433 // C11 6.2.7p4:
4434 // For an identifier with internal or external linkage declared
4435 // in a scope in which a prior declaration of that identifier is
4436 // visible, if the prior declaration specifies internal or
4437 // external linkage, the type of the identifier at the later
4438 // declaration becomes the composite type.
4439 //
4440 // If the variable isn't visible, we do not merge with its type.
4441 if (Previous.isShadowed())
4442 return false;
4443
4444 if (S.getLangOpts().CPlusPlus) {
4445 // C++11 [dcl.array]p3:
4446 // If there is a preceding declaration of the entity in the same
4447 // scope in which the bound was specified, an omitted array bound
4448 // is taken to be the same as in that earlier declaration.
4449 return NewVD->isPreviousDeclInSameBlockScope() ||
4452 } else {
4453 // If the old declaration was function-local, don't merge with its
4454 // type unless we're in the same function.
4455 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4456 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4457 }
4458}
4459
4461 // If the new decl is already invalid, don't do any other checking.
4462 if (New->isInvalidDecl())
4463 return;
4464
4465 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4466 return;
4467
4468 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4469
4470 // Verify the old decl was also a variable or variable template.
4471 VarDecl *Old = nullptr;
4472 VarTemplateDecl *OldTemplate = nullptr;
4473 if (Previous.isSingleResult()) {
4474 if (NewTemplate) {
4475 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4476 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4477
4478 if (auto *Shadow =
4479 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4480 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4481 return New->setInvalidDecl();
4482 } else {
4483 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4484
4485 if (auto *Shadow =
4486 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4487 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4488 return New->setInvalidDecl();
4489 }
4490 }
4491 if (!Old) {
4492 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4493 << New->getDeclName();
4494 notePreviousDefinition(Previous.getRepresentativeDecl(),
4495 New->getLocation());
4496 return New->setInvalidDecl();
4497 }
4498
4499 // If the old declaration was found in an inline namespace and the new
4500 // declaration was qualified, update the DeclContext to match.
4502
4503 // Ensure the template parameters are compatible.
4504 if (NewTemplate &&
4506 OldTemplate->getTemplateParameters(),
4507 /*Complain=*/true, TPL_TemplateMatch))
4508 return New->setInvalidDecl();
4509
4510 // C++ [class.mem]p1:
4511 // A member shall not be declared twice in the member-specification [...]
4512 //
4513 // Here, we need only consider static data members.
4514 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4515 Diag(New->getLocation(), diag::err_duplicate_member)
4516 << New->getIdentifier();
4517 Diag(Old->getLocation(), diag::note_previous_declaration);
4518 New->setInvalidDecl();
4519 }
4520
4521 mergeDeclAttributes(New, Old);
4522 // Warn if an already-defined variable is made a weak_import in a subsequent
4523 // declaration
4524 if (New->hasAttr<WeakImportAttr>())
4525 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4526 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4527 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4528 Diag(D->getLocation(), diag::note_previous_definition);
4529 // Remove weak_import attribute on new declaration.
4530 New->dropAttr<WeakImportAttr>();
4531 break;
4532 }
4533 }
4534
4535 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4536 if (!Old->hasAttr<InternalLinkageAttr>()) {
4537 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4538 << ILA;
4539 Diag(Old->getLocation(), diag::note_previous_declaration);
4540 New->dropAttr<InternalLinkageAttr>();
4541 }
4542
4543 // Merge the types.
4544 VarDecl *MostRecent = Old->getMostRecentDecl();
4545 if (MostRecent != Old) {
4546 MergeVarDeclTypes(New, MostRecent,
4547 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4548 if (New->isInvalidDecl())
4549 return;
4550 }
4551
4552 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4553 if (New->isInvalidDecl())
4554 return;
4555
4556 diag::kind PrevDiag;
4557 SourceLocation OldLocation;
4558 std::tie(PrevDiag, OldLocation) =
4560
4561 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4562 if (New->getStorageClass() == SC_Static &&
4563 !New->isStaticDataMember() &&
4564 Old->hasExternalFormalLinkage()) {
4565 if (getLangOpts().MicrosoftExt) {
4566 Diag(New->getLocation(), diag::ext_static_non_static)
4567 << New->getDeclName();
4568 Diag(OldLocation, PrevDiag);
4569 } else {
4570 Diag(New->getLocation(), diag::err_static_non_static)
4571 << New->getDeclName();
4572 Diag(OldLocation, PrevDiag);
4573 return New->setInvalidDecl();
4574 }
4575 }
4576 // C99 6.2.2p4:
4577 // For an identifier declared with the storage-class specifier
4578 // extern in a scope in which a prior declaration of that
4579 // identifier is visible,23) if the prior declaration specifies
4580 // internal or external linkage, the linkage of the identifier at
4581 // the later declaration is the same as the linkage specified at
4582 // the prior declaration. If no prior declaration is visible, or
4583 // if the prior declaration specifies no linkage, then the
4584 // identifier has external linkage.
4585 if (New->hasExternalStorage() && Old->hasLinkage())
4586 /* Okay */;
4587 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4588 !New->isStaticDataMember() &&
4590 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4591 Diag(OldLocation, PrevDiag);
4592 return New->setInvalidDecl();
4593 }
4594
4595 // Check if extern is followed by non-extern and vice-versa.
4596 if (New->hasExternalStorage() &&
4597 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4598 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4599 Diag(OldLocation, PrevDiag);
4600 return New->setInvalidDecl();
4601 }
4602 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4603 !New->hasExternalStorage()) {
4604 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4605 Diag(OldLocation, PrevDiag);
4606 return New->setInvalidDecl();
4607 }
4608
4609 if (CheckRedeclarationInModule(New, Old))
4610 return;
4611
4612 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4613
4614 // FIXME: The test for external storage here seems wrong? We still
4615 // need to check for mismatches.
4616 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4617 // Don't complain about out-of-line definitions of static members.
4618 !(Old->getLexicalDeclContext()->isRecord() &&
4619 !New->getLexicalDeclContext()->isRecord())) {
4620 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4621 Diag(OldLocation, PrevDiag);
4622 return New->setInvalidDecl();
4623 }
4624
4625 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4626 if (VarDecl *Def = Old->getDefinition()) {
4627 // C++1z [dcl.fcn.spec]p4:
4628 // If the definition of a variable appears in a translation unit before
4629 // its first declaration as inline, the program is ill-formed.
4630 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4631 Diag(Def->getLocation(), diag::note_previous_definition);
4632 }
4633 }
4634
4635 // If this redeclaration makes the variable inline, we may need to add it to
4636 // UndefinedButUsed.
4637 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4639 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4640 SourceLocation()));
4641
4642 if (New->getTLSKind() != Old->getTLSKind()) {
4643 if (!Old->getTLSKind()) {
4644 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4645 Diag(OldLocation, PrevDiag);
4646 } else if (!New->getTLSKind()) {
4647 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4648 Diag(OldLocation, PrevDiag);
4649 } else {
4650 // Do not allow redeclaration to change the variable between requiring
4651 // static and dynamic initialization.
4652 // FIXME: GCC allows this, but uses the TLS keyword on the first
4653 // declaration to determine the kind. Do we need to be compatible here?
4654 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4655 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4656 Diag(OldLocation, PrevDiag);
4657 }
4658 }
4659
4660 // C++ doesn't have tentative definitions, so go right ahead and check here.
4661 if (getLangOpts().CPlusPlus) {
4662 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4663 Old->getCanonicalDecl()->isConstexpr()) {
4664 // This definition won't be a definition any more once it's been merged.
4665 Diag(New->getLocation(),
4666 diag::warn_deprecated_redundant_constexpr_static_def);
4668 VarDecl *Def = Old->getDefinition();
4669 if (Def && checkVarDeclRedefinition(Def, New))
4670 return;
4671 }
4672 }
4673
4674 if (haveIncompatibleLanguageLinkages(Old, New)) {
4675 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4676 Diag(OldLocation, PrevDiag);
4677 New->setInvalidDecl();
4678 return;
4679 }
4680
4681 // Merge "used" flag.
4682 if (Old->getMostRecentDecl()->isUsed(false))
4683 New->setIsUsed();
4684
4685 // Keep a chain of previous declarations.
4686 New->setPreviousDecl(Old);
4687 if (NewTemplate)
4688 NewTemplate->setPreviousDecl(OldTemplate);
4689
4690 // Inherit access appropriately.
4691 New->setAccess(Old->getAccess());
4692 if (NewTemplate)
4693 NewTemplate->setAccess(New->getAccess());
4694
4695 if (Old->isInline())
4696 New->setImplicitlyInline();
4697}
4698
4700 SourceManager &SrcMgr = getSourceManager();
4701 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4702 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4703 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4704 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4705 auto &HSI = PP.getHeaderSearchInfo();
4706 StringRef HdrFilename =
4707 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4708
4709 auto noteFromModuleOrInclude = [&](Module *Mod,
4710 SourceLocation IncLoc) -> bool {
4711 // Redefinition errors with modules are common with non modular mapped
4712 // headers, example: a non-modular header H in module A that also gets
4713 // included directly in a TU. Pointing twice to the same header/definition
4714 // is confusing, try to get better diagnostics when modules is on.
4715 if (IncLoc.isValid()) {
4716 if (Mod) {
4717 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4718 << HdrFilename.str() << Mod->getFullModuleName();
4719 if (!Mod->DefinitionLoc.isInvalid())
4720 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4721 << Mod->getFullModuleName();
4722 } else {
4723 Diag(IncLoc, diag::note_redefinition_include_same_file)
4724 << HdrFilename.str();
4725 }
4726 return true;
4727 }
4728
4729 return false;
4730 };
4731
4732 // Is it the same file and same offset? Provide more information on why
4733 // this leads to a redefinition error.
4734 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4735 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4736 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4737 bool EmittedDiag =
4738 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4739 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4740
4741 // If the header has no guards, emit a note suggesting one.
4742 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4743 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4744
4745 if (EmittedDiag)
4746 return;
4747 }
4748
4749 // Redefinition coming from different files or couldn't do better above.
4750 if (Old->getLocation().isValid())
4751 Diag(Old->getLocation(), diag::note_previous_definition);
4752}
4753
4755 if (!hasVisibleDefinition(Old) &&
4756 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4757 isa<VarTemplateSpecializationDecl>(New) ||
4760 // The previous definition is hidden, and multiple definitions are
4761 // permitted (in separate TUs). Demote this to a declaration.
4763
4764 // Make the canonical definition visible.
4765 if (auto *OldTD = Old->getDescribedVarTemplate())
4768 return false;
4769 } else {
4770 Diag(New->getLocation(), diag::err_redefinition) << New;
4772 New->setInvalidDecl();
4773 return true;
4774 }
4775}
4776
4778 DeclSpec &DS,
4779 const ParsedAttributesView &DeclAttrs,
4780 RecordDecl *&AnonRecord) {
4782 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4783}
4784
4785// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4786// disambiguate entities defined in different scopes.
4787// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4788// compatibility.
4789// We will pick our mangling number depending on which version of MSVC is being
4790// targeted.
4791static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4793 ? S->getMSCurManglingNumber()
4794 : S->getMSLastManglingNumber();
4795}
4796
4797void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4798 if (!Context.getLangOpts().CPlusPlus)
4799 return;
4800
4801 if (isa<CXXRecordDecl>(Tag->getParent())) {
4802 // If this tag is the direct child of a class, number it if
4803 // it is anonymous.
4804 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4805 return;
4807 Context.getManglingNumberContext(Tag->getParent());
4809 Tag, MCtx.getManglingNumber(
4810 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4811 return;
4812 }
4813
4814 // If this tag isn't a direct child of a class, number it if it is local.