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