1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/TargetParser/Triple.h"
55 #include <unordered_map>
57 using namespace clang
;
60 Sema::DeclGroupPtrTy
Sema::ConvertDeclToDeclGroup(Decl
*Ptr
, Decl
*OwnedType
) {
62 Decl
*Group
[2] = { OwnedType
, Ptr
};
63 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context
, Group
, 2));
66 return DeclGroupPtrTy::make(DeclGroupRef(Ptr
));
71 class TypeNameValidatorCCC final
: public CorrectionCandidateCallback
{
73 TypeNameValidatorCCC(bool AllowInvalid
, bool WantClass
= false,
74 bool AllowTemplates
= false,
75 bool AllowNonTemplates
= true)
76 : AllowInvalidDecl(AllowInvalid
), WantClassName(WantClass
),
77 AllowTemplates(AllowTemplates
), AllowNonTemplates(AllowNonTemplates
) {
78 WantExpressionKeywords
= false;
79 WantCXXNamedCasts
= false;
80 WantRemainingKeywords
= false;
83 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
84 if (NamedDecl
*ND
= candidate
.getCorrectionDecl()) {
85 if (!AllowInvalidDecl
&& ND
->isInvalidDecl())
88 if (getAsTypeTemplateDecl(ND
))
89 return AllowTemplates
;
91 bool IsType
= isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
95 if (AllowNonTemplates
)
98 // An injected-class-name of a class template (specialization) is valid
99 // as a template or as a non-template.
100 if (AllowTemplates
) {
101 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
102 if (!RD
|| !RD
->isInjectedClassName())
104 RD
= cast
<CXXRecordDecl
>(RD
->getDeclContext());
105 return RD
->getDescribedClassTemplate() ||
106 isa
<ClassTemplateSpecializationDecl
>(RD
);
112 return !WantClassName
&& candidate
.isKeyword();
115 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
116 return std::make_unique
<TypeNameValidatorCCC
>(*this);
120 bool AllowInvalidDecl
;
123 bool AllowNonTemplates
;
126 } // end anonymous namespace
128 /// Determine whether the token kind starts a simple-type-specifier.
129 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind
) const {
131 // FIXME: Take into account the current language when deciding whether a
132 // token kind is a valid type specifier
135 case tok::kw___int64
:
136 case tok::kw___int128
:
138 case tok::kw_unsigned
:
146 case tok::kw__Float16
:
147 case tok::kw___float128
:
148 case tok::kw___ibm128
:
149 case tok::kw_wchar_t
:
151 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152 #include "clang/Basic/TransformTypeTraits.def"
153 case tok::kw___auto_type
:
156 case tok::annot_typename
:
157 case tok::kw_char16_t
:
158 case tok::kw_char32_t
:
160 case tok::annot_decltype
:
161 case tok::kw_decltype
:
162 return getLangOpts().CPlusPlus
;
164 case tok::kw_char8_t
:
165 return getLangOpts().Char8
;
175 enum class UnqualifiedTypeNameLookupResult
{
180 } // end anonymous namespace
182 /// Tries to perform unqualified lookup of the type decls in bases for
184 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185 /// type decl, \a FoundType if only type decls are found.
186 static UnqualifiedTypeNameLookupResult
187 lookupUnqualifiedTypeNameInBase(Sema
&S
, const IdentifierInfo
&II
,
188 SourceLocation NameLoc
,
189 const CXXRecordDecl
*RD
) {
190 if (!RD
->hasDefinition())
191 return UnqualifiedTypeNameLookupResult::NotFound
;
192 // Look for type decls in base classes.
193 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
194 UnqualifiedTypeNameLookupResult::NotFound
;
195 for (const auto &Base
: RD
->bases()) {
196 const CXXRecordDecl
*BaseRD
= nullptr;
197 if (auto *BaseTT
= Base
.getType()->getAs
<TagType
>())
198 BaseRD
= BaseTT
->getAsCXXRecordDecl();
199 else if (auto *TST
= Base
.getType()->getAs
<TemplateSpecializationType
>()) {
200 // Look for type decls in dependent base classes that have known primary
202 if (!TST
|| !TST
->isDependentType())
204 auto *TD
= TST
->getTemplateName().getAsTemplateDecl();
207 if (auto *BasePrimaryTemplate
=
208 dyn_cast_or_null
<CXXRecordDecl
>(TD
->getTemplatedDecl())) {
209 if (BasePrimaryTemplate
->getCanonicalDecl() != RD
->getCanonicalDecl())
210 BaseRD
= BasePrimaryTemplate
;
211 else if (auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
)) {
212 if (const ClassTemplatePartialSpecializationDecl
*PS
=
213 CTD
->findPartialSpecialization(Base
.getType()))
214 if (PS
->getCanonicalDecl() != RD
->getCanonicalDecl())
220 for (NamedDecl
*ND
: BaseRD
->lookup(&II
)) {
221 if (!isa
<TypeDecl
>(ND
))
222 return UnqualifiedTypeNameLookupResult::FoundNonType
;
223 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
225 if (FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
) {
226 switch (lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, BaseRD
)) {
227 case UnqualifiedTypeNameLookupResult::FoundNonType
:
228 return UnqualifiedTypeNameLookupResult::FoundNonType
;
229 case UnqualifiedTypeNameLookupResult::FoundType
:
230 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
232 case UnqualifiedTypeNameLookupResult::NotFound
:
239 return FoundTypeDecl
;
242 static ParsedType
recoverFromTypeInKnownDependentBase(Sema
&S
,
243 const IdentifierInfo
&II
,
244 SourceLocation NameLoc
) {
245 // Lookup in the parent class template context, if any.
246 const CXXRecordDecl
*RD
= nullptr;
247 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
248 UnqualifiedTypeNameLookupResult::NotFound
;
249 for (DeclContext
*DC
= S
.CurContext
;
250 DC
&& FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
;
251 DC
= DC
->getParent()) {
252 // Look for type decls in dependent base classes that have known primary
254 RD
= dyn_cast
<CXXRecordDecl
>(DC
);
255 if (RD
&& RD
->getDescribedClassTemplate())
256 FoundTypeDecl
= lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, RD
);
258 if (FoundTypeDecl
!= UnqualifiedTypeNameLookupResult::FoundType
)
261 // We found some types in dependent base classes. Recover as if the user
262 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
263 // lookup during template instantiation.
264 S
.Diag(NameLoc
, diag::ext_found_in_dependent_base
) << &II
;
266 ASTContext
&Context
= S
.Context
;
267 auto *NNS
= NestedNameSpecifier::Create(Context
, nullptr, false,
268 cast
<Type
>(Context
.getRecordType(RD
)));
270 Context
.getDependentNameType(ElaboratedTypeKeyword::Typename
, NNS
, &II
);
273 SS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
275 TypeLocBuilder Builder
;
276 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
277 DepTL
.setNameLoc(NameLoc
);
278 DepTL
.setElaboratedKeywordLoc(SourceLocation());
279 DepTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
280 return S
.CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
283 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
284 static ParsedType
buildNamedType(Sema
&S
, const CXXScopeSpec
*SS
, QualType T
,
285 SourceLocation NameLoc
,
286 bool WantNontrivialTypeSourceInfo
= true) {
287 switch (T
->getTypeClass()) {
288 case Type::DeducedTemplateSpecialization
:
290 case Type::InjectedClassName
:
293 case Type::UnresolvedUsing
:
296 // These can never be qualified so an ElaboratedType node
297 // would carry no additional meaning.
298 case Type::ObjCInterface
:
299 case Type::ObjCTypeParam
:
300 case Type::TemplateTypeParm
:
301 return ParsedType::make(T
);
303 llvm_unreachable("Unexpected Type Class");
306 if (!SS
|| SS
->isEmpty())
307 return ParsedType::make(S
.Context
.getElaboratedType(
308 ElaboratedTypeKeyword::None
, nullptr, T
, nullptr));
310 QualType ElTy
= S
.getElaboratedType(ElaboratedTypeKeyword::None
, *SS
, T
);
311 if (!WantNontrivialTypeSourceInfo
)
312 return ParsedType::make(ElTy
);
314 TypeLocBuilder Builder
;
315 Builder
.pushTypeSpec(T
).setNameLoc(NameLoc
);
316 ElaboratedTypeLoc ElabTL
= Builder
.push
<ElaboratedTypeLoc
>(ElTy
);
317 ElabTL
.setElaboratedKeywordLoc(SourceLocation());
318 ElabTL
.setQualifierLoc(SS
->getWithLocInContext(S
.Context
));
319 return S
.CreateParsedType(ElTy
, Builder
.getTypeSourceInfo(S
.Context
, ElTy
));
322 /// If the identifier refers to a type name within this scope,
323 /// return the declaration of that type.
325 /// This routine performs ordinary name lookup of the identifier II
326 /// within the given scope, with optional C++ scope specifier SS, to
327 /// determine whether the name refers to a type. If so, returns an
328 /// opaque pointer (actually a QualType) corresponding to that
329 /// type. Otherwise, returns NULL.
330 ParsedType
Sema::getTypeName(const IdentifierInfo
&II
, SourceLocation NameLoc
,
331 Scope
*S
, CXXScopeSpec
*SS
, bool isClassName
,
332 bool HasTrailingDot
, ParsedType ObjectTypePtr
,
333 bool IsCtorOrDtorName
,
334 bool WantNontrivialTypeSourceInfo
,
335 bool IsClassTemplateDeductionContext
,
336 ImplicitTypenameContext AllowImplicitTypename
,
337 IdentifierInfo
**CorrectedII
) {
338 // FIXME: Consider allowing this outside C++1z mode as an extension.
339 bool AllowDeducedTemplate
= IsClassTemplateDeductionContext
&&
340 getLangOpts().CPlusPlus17
&& !IsCtorOrDtorName
&&
341 !isClassName
&& !HasTrailingDot
;
343 // Determine where we will perform name lookup.
344 DeclContext
*LookupCtx
= nullptr;
346 QualType ObjectType
= ObjectTypePtr
.get();
347 if (ObjectType
->isRecordType())
348 LookupCtx
= computeDeclContext(ObjectType
);
349 } else if (SS
&& SS
->isNotEmpty()) {
350 LookupCtx
= computeDeclContext(*SS
, false);
353 if (isDependentScopeSpecifier(*SS
)) {
355 // A qualified-id that refers to a type and in which the
356 // nested-name-specifier depends on a template-parameter (14.6.2)
357 // shall be prefixed by the keyword typename to indicate that the
358 // qualified-id denotes a type, forming an
359 // elaborated-type-specifier (7.1.5.3).
361 // We therefore do not perform any name lookup if the result would
362 // refer to a member of an unknown specialization.
363 // In C++2a, in several contexts a 'typename' is not required. Also
364 // allow this as an extension.
365 if (AllowImplicitTypename
== ImplicitTypenameContext::No
&&
366 !isClassName
&& !IsCtorOrDtorName
)
368 bool IsImplicitTypename
= !isClassName
&& !IsCtorOrDtorName
;
369 if (IsImplicitTypename
) {
370 SourceLocation QualifiedLoc
= SS
->getRange().getBegin();
371 if (getLangOpts().CPlusPlus20
)
372 Diag(QualifiedLoc
, diag::warn_cxx17_compat_implicit_typename
);
374 Diag(QualifiedLoc
, diag::ext_implicit_typename
)
375 << SS
->getScopeRep() << II
.getName()
376 << FixItHint::CreateInsertion(QualifiedLoc
, "typename ");
379 // We know from the grammar that this name refers to a type,
380 // so build a dependent node to describe the type.
381 if (WantNontrivialTypeSourceInfo
)
382 return ActOnTypenameType(S
, SourceLocation(), *SS
, II
, NameLoc
,
383 (ImplicitTypenameContext
)IsImplicitTypename
)
386 NestedNameSpecifierLoc QualifierLoc
= SS
->getWithLocInContext(Context
);
387 QualType T
= CheckTypenameType(
388 IsImplicitTypename
? ElaboratedTypeKeyword::Typename
389 : ElaboratedTypeKeyword::None
,
390 SourceLocation(), QualifierLoc
, II
, NameLoc
);
391 return ParsedType::make(T
);
397 if (!LookupCtx
->isDependentContext() &&
398 RequireCompleteDeclContext(*SS
, LookupCtx
))
402 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
403 // lookup for class-names.
404 LookupNameKind Kind
= isClassName
? LookupNestedNameSpecifierName
:
406 LookupResult
Result(*this, &II
, NameLoc
, Kind
);
408 // Perform "qualified" name lookup into the declaration context we
409 // computed, which is either the type of the base of a member access
410 // expression or the declaration context associated with a prior
411 // nested-name-specifier.
412 LookupQualifiedName(Result
, LookupCtx
);
414 if (ObjectTypePtr
&& Result
.empty()) {
415 // C++ [basic.lookup.classref]p3:
416 // If the unqualified-id is ~type-name, the type-name is looked up
417 // in the context of the entire postfix-expression. If the type T of
418 // the object expression is of a class type C, the type-name is also
419 // looked up in the scope of class C. At least one of the lookups shall
420 // find a name that refers to (possibly cv-qualified) T.
421 LookupName(Result
, S
);
424 // Perform unqualified name lookup.
425 LookupName(Result
, S
);
427 // For unqualified lookup in a class template in MSVC mode, look into
428 // dependent base classes where the primary class template is known.
429 if (Result
.empty() && getLangOpts().MSVCCompat
&& (!SS
|| SS
->isEmpty())) {
430 if (ParsedType TypeInBase
=
431 recoverFromTypeInKnownDependentBase(*this, II
, NameLoc
))
436 NamedDecl
*IIDecl
= nullptr;
437 UsingShadowDecl
*FoundUsingShadow
= nullptr;
438 switch (Result
.getResultKind()) {
439 case LookupResult::NotFound
:
440 case LookupResult::NotFoundInCurrentInstantiation
:
442 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/true, isClassName
,
443 AllowDeducedTemplate
);
444 TypoCorrection Correction
= CorrectTypo(Result
.getLookupNameInfo(), Kind
,
445 S
, SS
, CCC
, CTK_ErrorRecovery
);
446 IdentifierInfo
*NewII
= Correction
.getCorrectionAsIdentifierInfo();
448 bool MemberOfUnknownSpecialization
;
449 UnqualifiedId TemplateName
;
450 TemplateName
.setIdentifier(NewII
, NameLoc
);
451 NestedNameSpecifier
*NNS
= Correction
.getCorrectionSpecifier();
452 CXXScopeSpec NewSS
, *NewSSPtr
= SS
;
454 NewSS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
457 if (Correction
&& (NNS
|| NewII
!= &II
) &&
458 // Ignore a correction to a template type as the to-be-corrected
459 // identifier is not a template (typo correction for template names
460 // is handled elsewhere).
461 !(getLangOpts().CPlusPlus
&& NewSSPtr
&&
462 isTemplateName(S
, *NewSSPtr
, false, TemplateName
, nullptr, false,
463 Template
, MemberOfUnknownSpecialization
))) {
464 ParsedType Ty
= getTypeName(*NewII
, NameLoc
, S
, NewSSPtr
,
465 isClassName
, HasTrailingDot
, ObjectTypePtr
,
467 WantNontrivialTypeSourceInfo
,
468 IsClassTemplateDeductionContext
);
470 diagnoseTypo(Correction
,
471 PDiag(diag::err_unknown_type_or_class_name_suggest
)
472 << Result
.getLookupName() << isClassName
);
474 SS
->MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
475 *CorrectedII
= NewII
;
480 // If typo correction failed or was not performed, fall through
482 case LookupResult::FoundOverloaded
:
483 case LookupResult::FoundUnresolvedValue
:
484 Result
.suppressDiagnostics();
487 case LookupResult::Ambiguous
:
488 // Recover from type-hiding ambiguities by hiding the type. We'll
489 // do the lookup again when looking for an object, and we can
490 // diagnose the error then. If we don't do this, then the error
491 // about hiding the type will be immediately followed by an error
492 // that only makes sense if the identifier was treated like a type.
493 if (Result
.getAmbiguityKind() == LookupResult::AmbiguousTagHiding
) {
494 Result
.suppressDiagnostics();
498 // Look to see if we have a type anywhere in the list of results.
499 for (LookupResult::iterator Res
= Result
.begin(), ResEnd
= Result
.end();
500 Res
!= ResEnd
; ++Res
) {
501 NamedDecl
*RealRes
= (*Res
)->getUnderlyingDecl();
502 if (isa
<TypeDecl
, ObjCInterfaceDecl
, UnresolvedUsingIfExistsDecl
>(
504 (AllowDeducedTemplate
&& getAsTypeTemplateDecl(RealRes
))) {
506 // Make the selection of the recovery decl deterministic.
507 RealRes
->getLocation() < IIDecl
->getLocation()) {
509 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Res
);
515 // None of the entities we found is a type, so there is no way
516 // to even assume that the result is a type. In this case, don't
517 // complain about the ambiguity. The parser will either try to
518 // perform this lookup again (e.g., as an object name), which
519 // will produce the ambiguity, or will complain that it expected
521 Result
.suppressDiagnostics();
525 // We found a type within the ambiguous lookup; diagnose the
526 // ambiguity and then return that type. This might be the right
527 // answer, or it might not be, but it suppresses any attempt to
528 // perform the name lookup again.
531 case LookupResult::Found
:
532 IIDecl
= Result
.getFoundDecl();
533 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Result
.begin());
537 assert(IIDecl
&& "Didn't find decl");
540 if (TypeDecl
*TD
= dyn_cast
<TypeDecl
>(IIDecl
)) {
541 // C++ [class.qual]p2: A lookup that would find the injected-class-name
542 // instead names the constructors of the class, except when naming a class.
543 // This is ill-formed when we're not actually forming a ctor or dtor name.
544 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(LookupCtx
);
545 auto *FoundRD
= dyn_cast
<CXXRecordDecl
>(TD
);
546 if (!isClassName
&& !IsCtorOrDtorName
&& LookupRD
&& FoundRD
&&
547 FoundRD
->isInjectedClassName() &&
548 declaresSameEntity(LookupRD
, cast
<Decl
>(FoundRD
->getParent())))
549 Diag(NameLoc
, diag::err_out_of_line_qualified_id_type_names_constructor
)
552 DiagnoseUseOfDecl(IIDecl
, NameLoc
);
554 T
= Context
.getTypeDeclType(TD
);
555 MarkAnyDeclReferenced(TD
->getLocation(), TD
, /*OdrUse=*/false);
556 } else if (ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(IIDecl
)) {
557 (void)DiagnoseUseOfDecl(IDecl
, NameLoc
);
559 T
= Context
.getObjCInterfaceType(IDecl
);
560 FoundUsingShadow
= nullptr; // FIXME: Target must be a TypeDecl.
561 } else if (auto *UD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(IIDecl
)) {
562 (void)DiagnoseUseOfDecl(UD
, NameLoc
);
563 // Recover with 'int'
564 return ParsedType::make(Context
.IntTy
);
565 } else if (AllowDeducedTemplate
) {
566 if (auto *TD
= getAsTypeTemplateDecl(IIDecl
)) {
567 assert(!FoundUsingShadow
|| FoundUsingShadow
->getTargetDecl() == TD
);
568 TemplateName Template
=
569 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
570 T
= Context
.getDeducedTemplateSpecializationType(Template
, QualType(),
572 // Don't wrap in a further UsingType.
573 FoundUsingShadow
= nullptr;
578 // If it's not plausibly a type, suppress diagnostics.
579 Result
.suppressDiagnostics();
583 if (FoundUsingShadow
)
584 T
= Context
.getUsingType(FoundUsingShadow
, T
);
586 return buildNamedType(*this, SS
, T
, NameLoc
, WantNontrivialTypeSourceInfo
);
589 // Builds a fake NNS for the given decl context.
590 static NestedNameSpecifier
*
591 synthesizeCurrentNestedNameSpecifier(ASTContext
&Context
, DeclContext
*DC
) {
592 for (;; DC
= DC
->getLookupParent()) {
593 DC
= DC
->getPrimaryContext();
594 auto *ND
= dyn_cast
<NamespaceDecl
>(DC
);
595 if (ND
&& !ND
->isInline() && !ND
->isAnonymousNamespace())
596 return NestedNameSpecifier::Create(Context
, nullptr, ND
);
597 else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
598 return NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
599 RD
->getTypeForDecl());
600 else if (isa
<TranslationUnitDecl
>(DC
))
601 return NestedNameSpecifier::GlobalSpecifier(Context
);
603 llvm_unreachable("something isn't in TU scope?");
606 /// Find the parent class with dependent bases of the innermost enclosing method
607 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
608 /// up allowing unqualified dependent type names at class-level, which MSVC
609 /// correctly rejects.
610 static const CXXRecordDecl
*
611 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext
*DC
) {
612 for (; DC
&& DC
->isDependentContext(); DC
= DC
->getLookupParent()) {
613 DC
= DC
->getPrimaryContext();
614 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
615 if (MD
->getParent()->hasAnyDependentBases())
616 return MD
->getParent();
621 ParsedType
Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo
&II
,
622 SourceLocation NameLoc
,
623 bool IsTemplateTypeArg
) {
624 assert(getLangOpts().MSVCCompat
&& "shouldn't be called in non-MSVC mode");
626 NestedNameSpecifier
*NNS
= nullptr;
627 if (IsTemplateTypeArg
&& getCurScope()->isTemplateParamScope()) {
628 // If we weren't able to parse a default template argument, delay lookup
629 // until instantiation time by making a non-dependent DependentTypeName. We
630 // pretend we saw a NestedNameSpecifier referring to the current scope, and
631 // lookup is retried.
632 // FIXME: This hurts our diagnostic quality, since we get errors like "no
633 // type named 'Foo' in 'current_namespace'" when the user didn't write any
635 NNS
= synthesizeCurrentNestedNameSpecifier(Context
, CurContext
);
636 Diag(NameLoc
, diag::ext_ms_delayed_template_argument
) << &II
;
637 } else if (const CXXRecordDecl
*RD
=
638 findRecordWithDependentBasesOfEnclosingMethod(CurContext
)) {
639 // Build a DependentNameType that will perform lookup into RD at
640 // instantiation time.
641 NNS
= NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
642 RD
->getTypeForDecl());
644 // Diagnose that this identifier was undeclared, and retry the lookup during
645 // template instantiation.
646 Diag(NameLoc
, diag::ext_undeclared_unqual_id_with_dependent_base
) << &II
649 // This is not a situation that we should recover from.
654 Context
.getDependentNameType(ElaboratedTypeKeyword::None
, NNS
, &II
);
656 // Build type location information. We synthesized the qualifier, so we have
657 // to build a fake NestedNameSpecifierLoc.
658 NestedNameSpecifierLocBuilder NNSLocBuilder
;
659 NNSLocBuilder
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
660 NestedNameSpecifierLoc QualifierLoc
= NNSLocBuilder
.getWithLocInContext(Context
);
662 TypeLocBuilder Builder
;
663 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
664 DepTL
.setNameLoc(NameLoc
);
665 DepTL
.setElaboratedKeywordLoc(SourceLocation());
666 DepTL
.setQualifierLoc(QualifierLoc
);
667 return CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
670 /// isTagName() - This method is called *for error recovery purposes only*
671 /// to determine if the specified name is a valid tag name ("struct foo"). If
672 /// so, this returns the TST for the tag corresponding to it (TST_enum,
673 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
674 /// cases in C where the user forgot to specify the tag.
675 DeclSpec::TST
Sema::isTagName(IdentifierInfo
&II
, Scope
*S
) {
676 // Do a tag name lookup in this scope.
677 LookupResult
R(*this, &II
, SourceLocation(), LookupTagName
);
678 LookupName(R
, S
, false);
679 R
.suppressDiagnostics();
680 if (R
.getResultKind() == LookupResult::Found
)
681 if (const TagDecl
*TD
= R
.getAsSingle
<TagDecl
>()) {
682 switch (TD
->getTagKind()) {
683 case TTK_Struct
: return DeclSpec::TST_struct
;
684 case TTK_Interface
: return DeclSpec::TST_interface
;
685 case TTK_Union
: return DeclSpec::TST_union
;
686 case TTK_Class
: return DeclSpec::TST_class
;
687 case TTK_Enum
: return DeclSpec::TST_enum
;
691 return DeclSpec::TST_unspecified
;
694 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
695 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
696 /// then downgrade the missing typename error to a warning.
697 /// This is needed for MSVC compatibility; Example:
699 /// template<class T> class A {
701 /// typedef int TYPE;
703 /// template<class T> class B : public A<T> {
705 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
708 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec
*SS
, Scope
*S
) {
709 if (CurContext
->isRecord()) {
710 if (SS
->getScopeRep()->getKind() == NestedNameSpecifier::Super
)
713 const Type
*Ty
= SS
->getScopeRep()->getAsType();
715 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(CurContext
);
716 for (const auto &Base
: RD
->bases())
717 if (Ty
&& Context
.hasSameUnqualifiedType(QualType(Ty
, 1), Base
.getType()))
719 return S
->isFunctionPrototypeScope();
721 return CurContext
->isFunctionOrMethod() || S
->isFunctionPrototypeScope();
724 void Sema::DiagnoseUnknownTypeName(IdentifierInfo
*&II
,
725 SourceLocation IILoc
,
728 ParsedType
&SuggestedType
,
729 bool IsTemplateName
) {
730 // Don't report typename errors for editor placeholders.
731 if (II
->isEditorPlaceholder())
733 // We don't have anything to suggest (yet).
734 SuggestedType
= nullptr;
736 // There may have been a typo in the name of the type. Look up typo
737 // results, in case we have something that we can suggest.
738 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
739 /*AllowTemplates=*/IsTemplateName
,
740 /*AllowNonTemplates=*/!IsTemplateName
);
741 if (TypoCorrection Corrected
=
742 CorrectTypo(DeclarationNameInfo(II
, IILoc
), LookupOrdinaryName
, S
, SS
,
743 CCC
, CTK_ErrorRecovery
)) {
744 // FIXME: Support error recovery for the template-name case.
745 bool CanRecover
= !IsTemplateName
;
746 if (Corrected
.isKeyword()) {
747 // We corrected to a keyword.
748 diagnoseTypo(Corrected
,
749 PDiag(IsTemplateName
? diag::err_no_template_suggest
750 : diag::err_unknown_typename_suggest
)
752 II
= Corrected
.getCorrectionAsIdentifierInfo();
754 // We found a similarly-named type or interface; suggest that.
755 if (!SS
|| !SS
->isSet()) {
756 diagnoseTypo(Corrected
,
757 PDiag(IsTemplateName
? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest
)
760 } else if (DeclContext
*DC
= computeDeclContext(*SS
, false)) {
761 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
762 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
763 II
->getName().equals(CorrectedStr
);
764 diagnoseTypo(Corrected
,
766 ? diag::err_no_member_template_suggest
767 : diag::err_unknown_nested_typename_suggest
)
768 << II
<< DC
<< DroppedSpecifier
<< SS
->getRange(),
771 llvm_unreachable("could not have corrected a typo here");
778 if (Corrected
.getCorrectionSpecifier())
779 tmpSS
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
781 // FIXME: Support class template argument deduction here.
783 getTypeName(*Corrected
.getCorrectionAsIdentifierInfo(), IILoc
, S
,
784 tmpSS
.isSet() ? &tmpSS
: SS
, false, false, nullptr,
785 /*IsCtorOrDtorName=*/false,
786 /*WantNontrivialTypeSourceInfo=*/true);
791 if (getLangOpts().CPlusPlus
&& !IsTemplateName
) {
792 // See if II is a class template that the user forgot to pass arguments to.
794 Name
.setIdentifier(II
, IILoc
);
795 CXXScopeSpec EmptySS
;
796 TemplateTy TemplateResult
;
797 bool MemberOfUnknownSpecialization
;
798 if (isTemplateName(S
, SS
? *SS
: EmptySS
, /*hasTemplateKeyword=*/false,
799 Name
, nullptr, true, TemplateResult
,
800 MemberOfUnknownSpecialization
) == TNK_Type_template
) {
801 diagnoseMissingTemplateArguments(TemplateResult
.get(), IILoc
);
806 // FIXME: Should we move the logic that tries to recover from a missing tag
807 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
809 if (!SS
|| (!SS
->isSet() && !SS
->isInvalid()))
810 Diag(IILoc
, IsTemplateName
? diag::err_no_template
811 : diag::err_unknown_typename
)
813 else if (DeclContext
*DC
= computeDeclContext(*SS
, false))
814 Diag(IILoc
, IsTemplateName
? diag::err_no_member_template
815 : diag::err_typename_nested_not_found
)
816 << II
<< DC
<< SS
->getRange();
817 else if (SS
->isValid() && SS
->getScopeRep()->containsErrors()) {
819 ActOnTypenameType(S
, SourceLocation(), *SS
, *II
, IILoc
).get();
820 } else if (isDependentScopeSpecifier(*SS
)) {
821 unsigned DiagID
= diag::err_typename_missing
;
822 if (getLangOpts().MSVCCompat
&& isMicrosoftMissingTypename(SS
, S
))
823 DiagID
= diag::ext_typename_missing
;
825 Diag(SS
->getRange().getBegin(), DiagID
)
826 << SS
->getScopeRep() << II
->getName()
827 << SourceRange(SS
->getRange().getBegin(), IILoc
)
828 << FixItHint::CreateInsertion(SS
->getRange().getBegin(), "typename ");
829 SuggestedType
= ActOnTypenameType(S
, SourceLocation(),
830 *SS
, *II
, IILoc
).get();
832 assert(SS
&& SS
->isInvalid() &&
833 "Invalid scope specifier has already been diagnosed");
837 /// Determine whether the given result set contains either a type name
839 static bool isResultTypeOrTemplate(LookupResult
&R
, const Token
&NextToken
) {
840 bool CheckTemplate
= R
.getSema().getLangOpts().CPlusPlus
&&
841 NextToken
.is(tok::less
);
843 for (LookupResult::iterator I
= R
.begin(), IEnd
= R
.end(); I
!= IEnd
; ++I
) {
844 if (isa
<TypeDecl
>(*I
) || isa
<ObjCInterfaceDecl
>(*I
))
847 if (CheckTemplate
&& isa
<TemplateDecl
>(*I
))
854 static bool isTagTypeWithMissingTag(Sema
&SemaRef
, LookupResult
&Result
,
855 Scope
*S
, CXXScopeSpec
&SS
,
856 IdentifierInfo
*&Name
,
857 SourceLocation NameLoc
) {
858 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupTagName
);
859 SemaRef
.LookupParsedName(R
, S
, &SS
);
860 if (TagDecl
*Tag
= R
.getAsSingle
<TagDecl
>()) {
861 StringRef FixItTagName
;
862 switch (Tag
->getTagKind()) {
864 FixItTagName
= "class ";
868 FixItTagName
= "enum ";
872 FixItTagName
= "struct ";
876 FixItTagName
= "__interface ";
880 FixItTagName
= "union ";
884 StringRef TagName
= FixItTagName
.drop_back();
885 SemaRef
.Diag(NameLoc
, diag::err_use_of_tag_name_without_tag
)
886 << Name
<< TagName
<< SemaRef
.getLangOpts().CPlusPlus
887 << FixItHint::CreateInsertion(NameLoc
, FixItTagName
);
889 for (LookupResult::iterator I
= Result
.begin(), IEnd
= Result
.end();
891 SemaRef
.Diag((*I
)->getLocation(), diag::note_decl_hiding_tag_type
)
894 // Replace lookup results with just the tag decl.
895 Result
.clear(Sema::LookupTagName
);
896 SemaRef
.LookupParsedName(Result
, S
, &SS
);
903 Sema::NameClassification
Sema::ClassifyName(Scope
*S
, CXXScopeSpec
&SS
,
904 IdentifierInfo
*&Name
,
905 SourceLocation NameLoc
,
906 const Token
&NextToken
,
907 CorrectionCandidateCallback
*CCC
) {
908 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
909 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
911 assert(NextToken
.isNot(tok::coloncolon
) &&
912 "parse nested name specifiers before calling ClassifyName");
913 if (getLangOpts().CPlusPlus
&& SS
.isSet() &&
914 isCurrentClassName(*Name
, S
, &SS
)) {
915 // Per [class.qual]p2, this names the constructors of SS, not the
916 // injected-class-name. We don't have a classification for that.
917 // There's not much point caching this result, since the parser
918 // will reject it later.
919 return NameClassification::Unknown();
922 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
923 LookupParsedName(Result
, S
, &SS
, !CurMethod
);
926 return NameClassification::Error();
928 // For unqualified lookup in a class template in MSVC mode, look into
929 // dependent base classes where the primary class template is known.
930 if (Result
.empty() && SS
.isEmpty() && getLangOpts().MSVCCompat
) {
931 if (ParsedType TypeInBase
=
932 recoverFromTypeInKnownDependentBase(*this, *Name
, NameLoc
))
936 // Perform lookup for Objective-C instance variables (including automatically
937 // synthesized instance variables), if we're in an Objective-C method.
938 // FIXME: This lookup really, really needs to be folded in to the normal
939 // unqualified lookup mechanism.
940 if (SS
.isEmpty() && CurMethod
&& !isResultTypeOrTemplate(Result
, NextToken
)) {
941 DeclResult Ivar
= LookupIvarInObjCMethod(Result
, S
, Name
);
942 if (Ivar
.isInvalid())
943 return NameClassification::Error();
945 return NameClassification::NonType(cast
<NamedDecl
>(Ivar
.get()));
947 // We defer builtin creation until after ivar lookup inside ObjC methods.
949 LookupBuiltin(Result
);
952 bool SecondTry
= false;
953 bool IsFilteredTemplateName
= false;
956 switch (Result
.getResultKind()) {
957 case LookupResult::NotFound
:
958 // If an unqualified-id is followed by a '(', then we have a function
960 if (SS
.isEmpty() && NextToken
.is(tok::l_paren
)) {
961 // In C++, this is an ADL-only call.
963 if (getLangOpts().CPlusPlus
)
964 return NameClassification::UndeclaredNonType();
967 // If the expression that precedes the parenthesized argument list in a
968 // function call consists solely of an identifier, and if no
969 // declaration is visible for this identifier, the identifier is
970 // implicitly declared exactly as if, in the innermost block containing
971 // the function call, the declaration
973 // extern int identifier ();
977 // We also allow this in C99 as an extension. However, this is not
978 // allowed in all language modes as functions without prototypes may not
980 if (getLangOpts().implicitFunctionsAllowed()) {
981 if (NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *Name
, S
))
982 return NameClassification::NonType(D
);
986 if (getLangOpts().CPlusPlus20
&& SS
.isEmpty() && NextToken
.is(tok::less
)) {
987 // In C++20 onwards, this could be an ADL-only call to a function
988 // template, and we're required to assume that this is a template name.
990 // FIXME: Find a way to still do typo correction in this case.
991 TemplateName Template
=
992 Context
.getAssumedTemplateName(NameInfo
.getName());
993 return NameClassification::UndeclaredTemplate(Template
);
996 // In C, we first see whether there is a tag type by the same name, in
997 // which case it's likely that the user just forgot to write "enum",
998 // "struct", or "union".
999 if (!getLangOpts().CPlusPlus
&& !SecondTry
&&
1000 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
1004 // Perform typo correction to determine if there is another name that is
1005 // close to this name.
1006 if (!SecondTry
&& CCC
) {
1008 if (TypoCorrection Corrected
=
1009 CorrectTypo(Result
.getLookupNameInfo(), Result
.getLookupKind(), S
,
1010 &SS
, *CCC
, CTK_ErrorRecovery
)) {
1011 unsigned UnqualifiedDiag
= diag::err_undeclared_var_use_suggest
;
1012 unsigned QualifiedDiag
= diag::err_no_member_suggest
;
1014 NamedDecl
*FirstDecl
= Corrected
.getFoundDecl();
1015 NamedDecl
*UnderlyingFirstDecl
= Corrected
.getCorrectionDecl();
1016 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1017 UnderlyingFirstDecl
&& isa
<TemplateDecl
>(UnderlyingFirstDecl
)) {
1018 UnqualifiedDiag
= diag::err_no_template_suggest
;
1019 QualifiedDiag
= diag::err_no_member_template_suggest
;
1020 } else if (UnderlyingFirstDecl
&&
1021 (isa
<TypeDecl
>(UnderlyingFirstDecl
) ||
1022 isa
<ObjCInterfaceDecl
>(UnderlyingFirstDecl
) ||
1023 isa
<ObjCCompatibleAliasDecl
>(UnderlyingFirstDecl
))) {
1024 UnqualifiedDiag
= diag::err_unknown_typename_suggest
;
1025 QualifiedDiag
= diag::err_unknown_nested_typename_suggest
;
1029 diagnoseTypo(Corrected
, PDiag(UnqualifiedDiag
) << Name
);
1030 } else {// FIXME: is this even reachable? Test it.
1031 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
1032 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
1033 Name
->getName().equals(CorrectedStr
);
1034 diagnoseTypo(Corrected
, PDiag(QualifiedDiag
)
1035 << Name
<< computeDeclContext(SS
, false)
1036 << DroppedSpecifier
<< SS
.getRange());
1039 // Update the name, so that the caller has the new name.
1040 Name
= Corrected
.getCorrectionAsIdentifierInfo();
1042 // Typo correction corrected to a keyword.
1043 if (Corrected
.isKeyword())
1046 // Also update the LookupResult...
1047 // FIXME: This should probably go away at some point
1049 Result
.setLookupName(Corrected
.getCorrection());
1051 Result
.addDecl(FirstDecl
);
1053 // If we found an Objective-C instance variable, let
1054 // LookupInObjCMethod build the appropriate expression to
1055 // reference the ivar.
1056 // FIXME: This is a gross hack.
1057 if (ObjCIvarDecl
*Ivar
= Result
.getAsSingle
<ObjCIvarDecl
>()) {
1059 LookupIvarInObjCMethod(Result
, S
, Ivar
->getIdentifier());
1061 return NameClassification::Error();
1063 return NameClassification::NonType(Ivar
);
1070 // We failed to correct; just fall through and let the parser deal with it.
1071 Result
.suppressDiagnostics();
1072 return NameClassification::Unknown();
1074 case LookupResult::NotFoundInCurrentInstantiation
: {
1075 // We performed name lookup into the current instantiation, and there were
1076 // dependent bases, so we treat this result the same way as any other
1077 // dependent nested-name-specifier.
1079 // C++ [temp.res]p2:
1080 // A name used in a template declaration or definition and that is
1081 // dependent on a template-parameter is assumed not to name a type
1082 // unless the applicable name lookup finds a type name or the name is
1083 // qualified by the keyword typename.
1085 // FIXME: If the next token is '<', we might want to ask the parser to
1086 // perform some heroics to see if we actually have a
1087 // template-argument-list, which would indicate a missing 'template'
1089 return NameClassification::DependentNonType();
1092 case LookupResult::Found
:
1093 case LookupResult::FoundOverloaded
:
1094 case LookupResult::FoundUnresolvedValue
:
1097 case LookupResult::Ambiguous
:
1098 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1099 hasAnyAcceptableTemplateNames(Result
, /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false)) {
1101 // C++ [temp.local]p3:
1102 // A lookup that finds an injected-class-name (10.2) can result in an
1103 // ambiguity in certain cases (for example, if it is found in more than
1104 // one base class). If all of the injected-class-names that are found
1105 // refer to specializations of the same class template, and if the name
1106 // is followed by a template-argument-list, the reference refers to the
1107 // class template itself and not a specialization thereof, and is not
1110 // This filtering can make an ambiguous result into an unambiguous one,
1111 // so try again after filtering out template names.
1112 FilterAcceptableTemplateNames(Result
);
1113 if (!Result
.isAmbiguous()) {
1114 IsFilteredTemplateName
= true;
1119 // Diagnose the ambiguity and return an error.
1120 return NameClassification::Error();
1123 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1124 (IsFilteredTemplateName
||
1125 hasAnyAcceptableTemplateNames(
1126 Result
, /*AllowFunctionTemplates=*/true,
1127 /*AllowDependent=*/false,
1128 /*AllowNonTemplateFunctions*/ SS
.isEmpty() &&
1129 getLangOpts().CPlusPlus20
))) {
1130 // C++ [temp.names]p3:
1131 // After name lookup (3.4) finds that a name is a template-name or that
1132 // an operator-function-id or a literal- operator-id refers to a set of
1133 // overloaded functions any member of which is a function template if
1134 // this is followed by a <, the < is always taken as the delimiter of a
1135 // template-argument-list and never as the less-than operator.
1136 // C++2a [temp.names]p2:
1137 // A name is also considered to refer to a template if it is an
1138 // unqualified-id followed by a < and name lookup finds either one
1139 // or more functions or finds nothing.
1140 if (!IsFilteredTemplateName
)
1141 FilterAcceptableTemplateNames(Result
);
1143 bool IsFunctionTemplate
;
1145 TemplateName Template
;
1146 if (Result
.end() - Result
.begin() > 1) {
1147 IsFunctionTemplate
= true;
1148 Template
= Context
.getOverloadedTemplateName(Result
.begin(),
1150 } else if (!Result
.empty()) {
1151 auto *TD
= cast
<TemplateDecl
>(getAsTemplateNameDecl(
1152 *Result
.begin(), /*AllowFunctionTemplates=*/true,
1153 /*AllowDependent=*/false));
1154 IsFunctionTemplate
= isa
<FunctionTemplateDecl
>(TD
);
1155 IsVarTemplate
= isa
<VarTemplateDecl
>(TD
);
1157 UsingShadowDecl
*FoundUsingShadow
=
1158 dyn_cast
<UsingShadowDecl
>(*Result
.begin());
1159 assert(!FoundUsingShadow
||
1160 TD
== cast
<TemplateDecl
>(FoundUsingShadow
->getTargetDecl()));
1162 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
1163 if (SS
.isNotEmpty())
1164 Template
= Context
.getQualifiedTemplateName(SS
.getScopeRep(),
1165 /*TemplateKeyword=*/false,
1168 // All results were non-template functions. This is a function template
1170 IsFunctionTemplate
= true;
1171 Template
= Context
.getAssumedTemplateName(NameInfo
.getName());
1174 if (IsFunctionTemplate
) {
1175 // Function templates always go through overload resolution, at which
1176 // point we'll perform the various checks (e.g., accessibility) we need
1177 // to based on which function we selected.
1178 Result
.suppressDiagnostics();
1180 return NameClassification::FunctionTemplate(Template
);
1183 return IsVarTemplate
? NameClassification::VarTemplate(Template
)
1184 : NameClassification::TypeTemplate(Template
);
1187 auto BuildTypeFor
= [&](TypeDecl
*Type
, NamedDecl
*Found
) {
1188 QualType T
= Context
.getTypeDeclType(Type
);
1189 if (const auto *USD
= dyn_cast
<UsingShadowDecl
>(Found
))
1190 T
= Context
.getUsingType(USD
, T
);
1191 return buildNamedType(*this, &SS
, T
, NameLoc
);
1194 NamedDecl
*FirstDecl
= (*Result
.begin())->getUnderlyingDecl();
1195 if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(FirstDecl
)) {
1196 DiagnoseUseOfDecl(Type
, NameLoc
);
1197 MarkAnyDeclReferenced(Type
->getLocation(), Type
, /*OdrUse=*/false);
1198 return BuildTypeFor(Type
, *Result
.begin());
1201 ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(FirstDecl
);
1203 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1204 if (ObjCCompatibleAliasDecl
*Alias
=
1205 dyn_cast
<ObjCCompatibleAliasDecl
>(FirstDecl
))
1206 Class
= Alias
->getClassInterface();
1210 DiagnoseUseOfDecl(Class
, NameLoc
);
1212 if (NextToken
.is(tok::period
)) {
1213 // Interface. <something> is parsed as a property reference expression.
1214 // Just return "unknown" as a fall-through for now.
1215 Result
.suppressDiagnostics();
1216 return NameClassification::Unknown();
1219 QualType T
= Context
.getObjCInterfaceType(Class
);
1220 return ParsedType::make(T
);
1223 if (isa
<ConceptDecl
>(FirstDecl
))
1224 return NameClassification::Concept(
1225 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1227 if (auto *EmptyD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(FirstDecl
)) {
1228 (void)DiagnoseUseOfDecl(EmptyD
, NameLoc
);
1229 return NameClassification::Error();
1232 // We can have a type template here if we're classifying a template argument.
1233 if (isa
<TemplateDecl
>(FirstDecl
) && !isa
<FunctionTemplateDecl
>(FirstDecl
) &&
1234 !isa
<VarTemplateDecl
>(FirstDecl
))
1235 return NameClassification::TypeTemplate(
1236 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1238 // Check for a tag type hidden by a non-type decl in a few cases where it
1239 // seems likely a type is wanted instead of the non-type that was found.
1240 bool NextIsOp
= NextToken
.isOneOf(tok::amp
, tok::star
);
1241 if ((NextToken
.is(tok::identifier
) ||
1243 FirstDecl
->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1244 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
1245 TypeDecl
*Type
= Result
.getAsSingle
<TypeDecl
>();
1246 DiagnoseUseOfDecl(Type
, NameLoc
);
1247 return BuildTypeFor(Type
, *Result
.begin());
1250 // If we already know which single declaration is referenced, just annotate
1251 // that declaration directly. Defer resolving even non-overloaded class
1252 // member accesses, as we need to defer certain access checks until we know
1254 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1255 if (Result
.isSingleResult() && !ADL
&&
1256 (!FirstDecl
->isCXXClassMember() || isa
<EnumConstantDecl
>(FirstDecl
)))
1257 return NameClassification::NonType(Result
.getRepresentativeDecl());
1259 // Otherwise, this is an overload set that we will need to resolve later.
1260 Result
.suppressDiagnostics();
1261 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1262 Context
, Result
.getNamingClass(), SS
.getWithLocInContext(Context
),
1263 Result
.getLookupNameInfo(), ADL
, Result
.isOverloadedResult(),
1264 Result
.begin(), Result
.end()));
1268 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo
*Name
,
1269 SourceLocation NameLoc
) {
1270 assert(getLangOpts().CPlusPlus
&& "ADL-only call in C?");
1272 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
1273 return BuildDeclarationNameExpr(SS
, Result
, /*ADL=*/true);
1277 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec
&SS
,
1278 IdentifierInfo
*Name
,
1279 SourceLocation NameLoc
,
1280 bool IsAddressOfOperand
) {
1281 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
1282 return ActOnDependentIdExpression(SS
, /*TemplateKWLoc=*/SourceLocation(),
1283 NameInfo
, IsAddressOfOperand
,
1284 /*TemplateArgs=*/nullptr);
1287 ExprResult
Sema::ActOnNameClassifiedAsNonType(Scope
*S
, const CXXScopeSpec
&SS
,
1289 SourceLocation NameLoc
,
1290 const Token
&NextToken
) {
1291 if (getCurMethodDecl() && SS
.isEmpty())
1292 if (auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(Found
->getUnderlyingDecl()))
1293 return BuildIvarRefExpr(S
, NameLoc
, Ivar
);
1295 // Reconstruct the lookup result.
1296 LookupResult
Result(*this, Found
->getDeclName(), NameLoc
, LookupOrdinaryName
);
1297 Result
.addDecl(Found
);
1298 Result
.resolveKind();
1300 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1301 return BuildDeclarationNameExpr(SS
, Result
, ADL
, /*AcceptInvalidDecl=*/true);
1304 ExprResult
Sema::ActOnNameClassifiedAsOverloadSet(Scope
*S
, Expr
*E
) {
1305 // For an implicit class member access, transform the result into a member
1306 // access expression if necessary.
1307 auto *ULE
= cast
<UnresolvedLookupExpr
>(E
);
1308 if ((*ULE
->decls_begin())->isCXXClassMember()) {
1310 SS
.Adopt(ULE
->getQualifierLoc());
1312 // Reconstruct the lookup result.
1313 LookupResult
Result(*this, ULE
->getName(), ULE
->getNameLoc(),
1314 LookupOrdinaryName
);
1315 Result
.setNamingClass(ULE
->getNamingClass());
1316 for (auto I
= ULE
->decls_begin(), E
= ULE
->decls_end(); I
!= E
; ++I
)
1317 Result
.addDecl(*I
, I
.getAccess());
1318 Result
.resolveKind();
1319 return BuildPossibleImplicitMemberExpr(SS
, SourceLocation(), Result
,
1323 // Otherwise, this is already in the form we needed, and no further checks
1328 Sema::TemplateNameKindForDiagnostics
1329 Sema::getTemplateNameKindForDiagnostics(TemplateName Name
) {
1330 auto *TD
= Name
.getAsTemplateDecl();
1332 return TemplateNameKindForDiagnostics::DependentTemplate
;
1333 if (isa
<ClassTemplateDecl
>(TD
))
1334 return TemplateNameKindForDiagnostics::ClassTemplate
;
1335 if (isa
<FunctionTemplateDecl
>(TD
))
1336 return TemplateNameKindForDiagnostics::FunctionTemplate
;
1337 if (isa
<VarTemplateDecl
>(TD
))
1338 return TemplateNameKindForDiagnostics::VarTemplate
;
1339 if (isa
<TypeAliasTemplateDecl
>(TD
))
1340 return TemplateNameKindForDiagnostics::AliasTemplate
;
1341 if (isa
<TemplateTemplateParmDecl
>(TD
))
1342 return TemplateNameKindForDiagnostics::TemplateTemplateParam
;
1343 if (isa
<ConceptDecl
>(TD
))
1344 return TemplateNameKindForDiagnostics::Concept
;
1345 return TemplateNameKindForDiagnostics::DependentTemplate
;
1348 void Sema::PushDeclContext(Scope
*S
, DeclContext
*DC
) {
1349 assert(DC
->getLexicalParent() == CurContext
&&
1350 "The next DeclContext should be lexically contained in the current one.");
1355 void Sema::PopDeclContext() {
1356 assert(CurContext
&& "DeclContext imbalance!");
1358 CurContext
= CurContext
->getLexicalParent();
1359 assert(CurContext
&& "Popped translation unit!");
1362 Sema::SkippedDefinitionContext
Sema::ActOnTagStartSkippedDefinition(Scope
*S
,
1364 // Unlike PushDeclContext, the context to which we return is not necessarily
1365 // the containing DC of TD, because the new context will be some pre-existing
1366 // TagDecl definition instead of a fresh one.
1367 auto Result
= static_cast<SkippedDefinitionContext
>(CurContext
);
1368 CurContext
= cast
<TagDecl
>(D
)->getDefinition();
1369 assert(CurContext
&& "skipping definition of undefined tag");
1370 // Start lookups from the parent of the current context; we don't want to look
1371 // into the pre-existing complete definition.
1372 S
->setEntity(CurContext
->getLookupParent());
1376 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context
) {
1377 CurContext
= static_cast<decltype(CurContext
)>(Context
);
1380 /// EnterDeclaratorContext - Used when we must lookup names in the context
1381 /// of a declarator's nested name specifier.
1383 void Sema::EnterDeclaratorContext(Scope
*S
, DeclContext
*DC
) {
1384 // C++0x [basic.lookup.unqual]p13:
1385 // A name used in the definition of a static data member of class
1386 // X (after the qualified-id of the static member) is looked up as
1387 // if the name was used in a member function of X.
1388 // C++0x [basic.lookup.unqual]p14:
1389 // If a variable member of a namespace is defined outside of the
1390 // scope of its namespace then any name used in the definition of
1391 // the variable member (after the declarator-id) is looked up as
1392 // if the definition of the variable member occurred in its
1394 // Both of these imply that we should push a scope whose context
1395 // is the semantic context of the declaration. We can't use
1396 // PushDeclContext here because that context is not necessarily
1397 // lexically contained in the current context. Fortunately,
1398 // the containing scope should have the appropriate information.
1400 assert(!S
->getEntity() && "scope already has entity");
1403 Scope
*Ancestor
= S
->getParent();
1404 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1405 assert(Ancestor
->getEntity() == CurContext
&& "ancestor context mismatch");
1411 if (S
->getParent()->isTemplateParamScope()) {
1412 // Also set the corresponding entities for all immediately-enclosing
1413 // template parameter scopes.
1414 EnterTemplatedContext(S
->getParent(), DC
);
1418 void Sema::ExitDeclaratorContext(Scope
*S
) {
1419 assert(S
->getEntity() == CurContext
&& "Context imbalance!");
1421 // Switch back to the lexical context. The safety of this is
1422 // enforced by an assert in EnterDeclaratorContext.
1423 Scope
*Ancestor
= S
->getParent();
1424 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1425 CurContext
= Ancestor
->getEntity();
1427 // We don't need to do anything with the scope, which is going to
1431 void Sema::EnterTemplatedContext(Scope
*S
, DeclContext
*DC
) {
1432 assert(S
->isTemplateParamScope() &&
1433 "expected to be initializing a template parameter scope");
1435 // C++20 [temp.local]p7:
1436 // In the definition of a member of a class template that appears outside
1437 // of the class template definition, the name of a member of the class
1438 // template hides the name of a template-parameter of any enclosing class
1439 // templates (but not a template-parameter of the member if the member is a
1440 // class or function template).
1441 // C++20 [temp.local]p9:
1442 // In the definition of a class template or in the definition of a member
1443 // of such a template that appears outside of the template definition, for
1444 // each non-dependent base class (13.8.2.1), if the name of the base class
1445 // or the name of a member of the base class is the same as the name of a
1446 // template-parameter, the base class name or member name hides the
1447 // template-parameter name (6.4.10).
1449 // This means that a template parameter scope should be searched immediately
1450 // after searching the DeclContext for which it is a template parameter
1451 // scope. For example, for
1452 // template<typename T> template<typename U> template<typename V>
1453 // void N::A<T>::B<U>::f(...)
1454 // we search V then B<U> (and base classes) then U then A<T> (and base
1455 // classes) then T then N then ::.
1456 unsigned ScopeDepth
= getTemplateDepth(S
);
1457 for (; S
&& S
->isTemplateParamScope(); S
= S
->getParent(), --ScopeDepth
) {
1458 DeclContext
*SearchDCAfterScope
= DC
;
1459 for (; DC
; DC
= DC
->getLookupParent()) {
1460 if (const TemplateParameterList
*TPL
=
1461 cast
<Decl
>(DC
)->getDescribedTemplateParams()) {
1462 unsigned DCDepth
= TPL
->getDepth() + 1;
1463 if (DCDepth
> ScopeDepth
)
1465 if (ScopeDepth
== DCDepth
)
1466 SearchDCAfterScope
= DC
= DC
->getLookupParent();
1470 S
->setLookupEntity(SearchDCAfterScope
);
1474 void Sema::ActOnReenterFunctionContext(Scope
* S
, Decl
*D
) {
1475 // We assume that the caller has already called
1476 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1477 FunctionDecl
*FD
= D
->getAsFunction();
1481 // Same implementation as PushDeclContext, but enters the context
1482 // from the lexical parent, rather than the top-level class.
1483 assert(CurContext
== FD
->getLexicalParent() &&
1484 "The next DeclContext should be lexically contained in the current one.");
1486 S
->setEntity(CurContext
);
1488 for (unsigned P
= 0, NumParams
= FD
->getNumParams(); P
< NumParams
; ++P
) {
1489 ParmVarDecl
*Param
= FD
->getParamDecl(P
);
1490 // If the parameter has an identifier, then add it to the scope
1491 if (Param
->getIdentifier()) {
1493 IdResolver
.AddDecl(Param
);
1498 void Sema::ActOnExitFunctionContext() {
1499 // Same implementation as PopDeclContext, but returns to the lexical parent,
1500 // rather than the top-level class.
1501 assert(CurContext
&& "DeclContext imbalance!");
1502 CurContext
= CurContext
->getLexicalParent();
1503 assert(CurContext
&& "Popped translation unit!");
1506 /// Determine whether overloading is allowed for a new function
1507 /// declaration considering prior declarations of the same name.
1509 /// This routine determines whether overloading is possible, not
1510 /// whether a new declaration actually overloads a previous one.
1511 /// It will return true in C++ (where overloads are alway permitted)
1512 /// or, as a C extension, when either the new declaration or a
1513 /// previous one is declared with the 'overloadable' attribute.
1514 static bool AllowOverloadingOfFunction(const LookupResult
&Previous
,
1515 ASTContext
&Context
,
1516 const FunctionDecl
*New
) {
1517 if (Context
.getLangOpts().CPlusPlus
|| New
->hasAttr
<OverloadableAttr
>())
1520 // Multiversion function declarations are not overloads in the
1521 // usual sense of that term, but lookup will report that an
1522 // overload set was found if more than one multiversion function
1523 // declaration is present for the same name. It is therefore
1524 // inadequate to assume that some prior declaration(s) had
1525 // the overloadable attribute; checking is required. Since one
1526 // declaration is permitted to omit the attribute, it is necessary
1527 // to check at least two; hence the 'any_of' check below. Note that
1528 // the overloadable attribute is implicitly added to declarations
1529 // that were required to have it but did not.
1530 if (Previous
.getResultKind() == LookupResult::FoundOverloaded
) {
1531 return llvm::any_of(Previous
, [](const NamedDecl
*ND
) {
1532 return ND
->hasAttr
<OverloadableAttr
>();
1534 } else if (Previous
.getResultKind() == LookupResult::Found
)
1535 return Previous
.getFoundDecl()->hasAttr
<OverloadableAttr
>();
1540 /// Add this decl to the scope shadowed decl chains.
1541 void Sema::PushOnScopeChains(NamedDecl
*D
, Scope
*S
, bool AddToContext
) {
1542 // Move up the scope chain until we find the nearest enclosing
1543 // non-transparent context. The declaration will be introduced into this
1545 while (S
->getEntity() && S
->getEntity()->isTransparentContext())
1548 // Add scoped declarations into their context, so that they can be
1549 // found later. Declarations without a context won't be inserted
1550 // into any context.
1552 CurContext
->addDecl(D
);
1554 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1555 // are function-local declarations.
1556 if (getLangOpts().CPlusPlus
&& D
->isOutOfLine() && !S
->getFnParent())
1559 // Template instantiations should also not be pushed into scope.
1560 if (isa
<FunctionDecl
>(D
) &&
1561 cast
<FunctionDecl
>(D
)->isFunctionTemplateSpecialization())
1564 // If this replaces anything in the current scope,
1565 IdentifierResolver::iterator I
= IdResolver
.begin(D
->getDeclName()),
1566 IEnd
= IdResolver
.end();
1567 for (; I
!= IEnd
; ++I
) {
1568 if (S
->isDeclScope(*I
) && D
->declarationReplaces(*I
)) {
1570 IdResolver
.RemoveDecl(*I
);
1572 // Should only need to replace one decl.
1579 if (isa
<LabelDecl
>(D
) && !cast
<LabelDecl
>(D
)->isGnuLocal()) {
1580 // Implicitly-generated labels may end up getting generated in an order that
1581 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1582 // the label at the appropriate place in the identifier chain.
1583 for (I
= IdResolver
.begin(D
->getDeclName()); I
!= IEnd
; ++I
) {
1584 DeclContext
*IDC
= (*I
)->getLexicalDeclContext()->getRedeclContext();
1585 if (IDC
== CurContext
) {
1586 if (!S
->isDeclScope(*I
))
1588 } else if (IDC
->Encloses(CurContext
))
1592 IdResolver
.InsertDeclAfter(I
, D
);
1594 IdResolver
.AddDecl(D
);
1596 warnOnReservedIdentifier(D
);
1599 bool Sema::isDeclInScope(NamedDecl
*D
, DeclContext
*Ctx
, Scope
*S
,
1600 bool AllowInlineNamespace
) const {
1601 return IdResolver
.isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
);
1604 Scope
*Sema::getScopeForDeclContext(Scope
*S
, DeclContext
*DC
) {
1605 DeclContext
*TargetDC
= DC
->getPrimaryContext();
1607 if (DeclContext
*ScopeDC
= S
->getEntity())
1608 if (ScopeDC
->getPrimaryContext() == TargetDC
)
1610 } while ((S
= S
->getParent()));
1615 static bool isOutOfScopePreviousDeclaration(NamedDecl
*,
1619 /// Filters out lookup results that don't fall within the given scope
1620 /// as determined by isDeclInScope.
1621 void Sema::FilterLookupForScope(LookupResult
&R
, DeclContext
*Ctx
, Scope
*S
,
1622 bool ConsiderLinkage
,
1623 bool AllowInlineNamespace
) {
1624 LookupResult::Filter F
= R
.makeFilter();
1625 while (F
.hasNext()) {
1626 NamedDecl
*D
= F
.next();
1628 if (isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
))
1631 if (ConsiderLinkage
&& isOutOfScopePreviousDeclaration(D
, Ctx
, Context
))
1640 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1641 /// have compatible owning modules.
1642 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl
*New
, NamedDecl
*Old
) {
1643 // [module.interface]p7:
1644 // A declaration is attached to a module as follows:
1645 // - If the declaration is a non-dependent friend declaration that nominates a
1646 // function with a declarator-id that is a qualified-id or template-id or that
1647 // nominates a class other than with an elaborated-type-specifier with neither
1648 // a nested-name-specifier nor a simple-template-id, it is attached to the
1649 // module to which the friend is attached ([basic.link]).
1650 if (New
->getFriendObjectKind() &&
1651 Old
->getOwningModuleForLinkage() != New
->getOwningModuleForLinkage()) {
1652 New
->setLocalOwningModule(Old
->getOwningModule());
1653 makeMergedDefinitionVisible(New
);
1657 Module
*NewM
= New
->getOwningModule();
1658 Module
*OldM
= Old
->getOwningModule();
1660 if (NewM
&& NewM
->isPrivateModule())
1661 NewM
= NewM
->Parent
;
1662 if (OldM
&& OldM
->isPrivateModule())
1663 OldM
= OldM
->Parent
;
1669 // A module implementation unit has visibility of the decls in its
1670 // implicitly imported interface.
1671 if (NewM
->isModuleImplementation() && OldM
== ThePrimaryInterface
)
1674 // Partitions are part of the module, but a partition could import another
1675 // module, so verify that the PMIs agree.
1676 if ((NewM
->isModulePartition() || OldM
->isModulePartition()) &&
1677 NewM
->getPrimaryModuleInterfaceName() ==
1678 OldM
->getPrimaryModuleInterfaceName())
1682 bool NewIsModuleInterface
= NewM
&& NewM
->isModulePurview();
1683 bool OldIsModuleInterface
= OldM
&& OldM
->isModulePurview();
1684 if (NewIsModuleInterface
|| OldIsModuleInterface
) {
1685 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1686 // if a declaration of D [...] appears in the purview of a module, all
1687 // other such declarations shall appear in the purview of the same module
1688 Diag(New
->getLocation(), diag::err_mismatched_owning_module
)
1690 << NewIsModuleInterface
1691 << (NewIsModuleInterface
? NewM
->getFullModuleName() : "")
1692 << OldIsModuleInterface
1693 << (OldIsModuleInterface
? OldM
->getFullModuleName() : "");
1694 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1695 New
->setInvalidDecl();
1702 // [module.interface]p6:
1703 // A redeclaration of an entity X is implicitly exported if X was introduced by
1704 // an exported declaration; otherwise it shall not be exported.
1705 bool Sema::CheckRedeclarationExported(NamedDecl
*New
, NamedDecl
*Old
) {
1706 // [module.interface]p1:
1707 // An export-declaration shall inhabit a namespace scope.
1709 // So it is meaningless to talk about redeclaration which is not at namespace
1711 if (!New
->getLexicalDeclContext()
1712 ->getNonTransparentContext()
1713 ->isFileContext() ||
1714 !Old
->getLexicalDeclContext()
1715 ->getNonTransparentContext()
1719 bool IsNewExported
= New
->isInExportDeclContext();
1720 bool IsOldExported
= Old
->isInExportDeclContext();
1722 // It should be irrevelant if both of them are not exported.
1723 if (!IsNewExported
&& !IsOldExported
)
1729 assert(IsNewExported
);
1731 auto Lk
= Old
->getFormalLinkage();
1733 if (Lk
== Linkage::InternalLinkage
)
1735 else if (Lk
== Linkage::ModuleLinkage
)
1737 Diag(New
->getLocation(), diag::err_redeclaration_non_exported
) << New
<< S
;
1738 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1742 // A wrapper function for checking the semantic restrictions of
1743 // a redeclaration within a module.
1744 bool Sema::CheckRedeclarationInModule(NamedDecl
*New
, NamedDecl
*Old
) {
1745 if (CheckRedeclarationModuleOwnership(New
, Old
))
1748 if (CheckRedeclarationExported(New
, Old
))
1754 // Check the redefinition in C++20 Modules.
1756 // [basic.def.odr]p14:
1757 // For any definable item D with definitions in multiple translation units,
1758 // - if D is a non-inline non-templated function or variable, or
1759 // - if the definitions in different translation units do not satisfy the
1760 // following requirements,
1761 // the program is ill-formed; a diagnostic is required only if the definable
1762 // item is attached to a named module and a prior definition is reachable at
1763 // the point where a later definition occurs.
1764 // - Each such definition shall not be attached to a named module
1766 // - Each such definition shall consist of the same sequence of tokens, ...
1769 // Return true if the redefinition is not allowed. Return false otherwise.
1770 bool Sema::IsRedefinitionInModule(const NamedDecl
*New
,
1771 const NamedDecl
*Old
) const {
1772 assert(getASTContext().isSameEntity(New
, Old
) &&
1773 "New and Old are not the same definition, we should diagnostic it "
1774 "immediately instead of checking it.");
1775 assert(const_cast<Sema
*>(this)->isReachable(New
) &&
1776 const_cast<Sema
*>(this)->isReachable(Old
) &&
1777 "We shouldn't see unreachable definitions here.");
1779 Module
*NewM
= New
->getOwningModule();
1780 Module
*OldM
= Old
->getOwningModule();
1782 // We only checks for named modules here. The header like modules is skipped.
1783 // FIXME: This is not right if we import the header like modules in the module
1786 // For example, assuming "header.h" provides definition for `D`.
1790 // import "header.h"; // or #include "header.h" but import it by clang modules
1795 // import "header.h"; // or uses clang modules.
1798 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1799 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1800 // reject it. But the current implementation couldn't detect the case since we
1801 // don't record the information about the importee modules.
1803 // But this might not be painful in practice. Since the design of C++20 Named
1804 // Modules suggests us to use headers in global module fragment instead of
1806 if (NewM
&& NewM
->isHeaderLikeModule())
1808 if (OldM
&& OldM
->isHeaderLikeModule())
1814 // [basic.def.odr]p14.3
1815 // Each such definition shall not be attached to a named module
1817 if ((NewM
&& NewM
->isModulePurview()) || (OldM
&& OldM
->isModulePurview()))
1820 // Then New and Old lives in the same TU if their share one same module unit.
1822 NewM
= NewM
->getTopLevelModule();
1824 OldM
= OldM
->getTopLevelModule();
1825 return OldM
== NewM
;
1828 static bool isUsingDeclNotAtClassScope(NamedDecl
*D
) {
1829 if (D
->getDeclContext()->isFileContext())
1832 return isa
<UsingShadowDecl
>(D
) ||
1833 isa
<UnresolvedUsingTypenameDecl
>(D
) ||
1834 isa
<UnresolvedUsingValueDecl
>(D
);
1837 /// Removes using shadow declarations not at class scope from the lookup
1839 static void RemoveUsingDecls(LookupResult
&R
) {
1840 LookupResult::Filter F
= R
.makeFilter();
1842 if (isUsingDeclNotAtClassScope(F
.next()))
1848 /// Check for this common pattern:
1851 /// S(const S&); // DO NOT IMPLEMENT
1852 /// void operator=(const S&); // DO NOT IMPLEMENT
1855 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl
*D
) {
1856 // FIXME: Should check for private access too but access is set after we get
1858 if (D
->doesThisDeclarationHaveABody())
1861 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(D
))
1862 return CD
->isCopyConstructor();
1863 return D
->isCopyAssignmentOperator();
1866 // We need this to handle
1869 // void *foo() { return 0; }
1872 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1873 // for example. If 'A', foo will have external linkage. If we have '*A',
1874 // foo will have no linkage. Since we can't know until we get to the end
1875 // of the typedef, this function finds out if D might have non-external linkage.
1876 // Callers should verify at the end of the TU if it D has external linkage or
1878 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl
*D
) {
1879 const DeclContext
*DC
= D
->getDeclContext();
1880 while (!DC
->isTranslationUnit()) {
1881 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(DC
)){
1882 if (!RD
->hasNameForLinkage())
1885 DC
= DC
->getParent();
1888 return !D
->isExternallyVisible();
1891 // FIXME: This needs to be refactored; some other isInMainFile users want
1893 static bool isMainFileLoc(const Sema
&S
, SourceLocation Loc
) {
1894 if (S
.TUKind
!= TU_Complete
|| S
.getLangOpts().IsHeaderFile
)
1896 return S
.SourceMgr
.isInMainFile(Loc
);
1899 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl
*D
) const {
1902 if (D
->isInvalidDecl() || D
->isUsed() || D
->hasAttr
<UnusedAttr
>())
1905 // Ignore all entities declared within templates, and out-of-line definitions
1906 // of members of class templates.
1907 if (D
->getDeclContext()->isDependentContext() ||
1908 D
->getLexicalDeclContext()->isDependentContext())
1911 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1912 if (FD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1914 // A non-out-of-line declaration of a member specialization was implicitly
1915 // instantiated; it's the out-of-line declaration that we're interested in.
1916 if (FD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1917 FD
->getMemberSpecializationInfo() && !FD
->isOutOfLine())
1920 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
1921 if (MD
->isVirtual() || IsDisallowedCopyOrAssign(MD
))
1924 // 'static inline' functions are defined in headers; don't warn.
1925 if (FD
->isInlined() && !isMainFileLoc(*this, FD
->getLocation()))
1929 if (FD
->doesThisDeclarationHaveABody() &&
1930 Context
.DeclMustBeEmitted(FD
))
1932 } else if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1933 // Constants and utility variables are defined in headers with internal
1934 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1936 if (!isMainFileLoc(*this, VD
->getLocation()))
1939 if (Context
.DeclMustBeEmitted(VD
))
1942 if (VD
->isStaticDataMember() &&
1943 VD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1945 if (VD
->isStaticDataMember() &&
1946 VD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1947 VD
->getMemberSpecializationInfo() && !VD
->isOutOfLine())
1950 if (VD
->isInline() && !isMainFileLoc(*this, VD
->getLocation()))
1956 // Only warn for unused decls internal to the translation unit.
1957 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1958 // for inline functions defined in the main source file, for instance.
1959 return mightHaveNonExternalLinkage(D
);
1962 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl
*D
) {
1966 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1967 const FunctionDecl
*First
= FD
->getFirstDecl();
1968 if (FD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1969 return; // First should already be in the vector.
1972 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1973 const VarDecl
*First
= VD
->getFirstDecl();
1974 if (VD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1975 return; // First should already be in the vector.
1978 if (ShouldWarnIfUnusedFileScopedDecl(D
))
1979 UnusedFileScopedDecls
.push_back(D
);
1982 static bool ShouldDiagnoseUnusedDecl(const LangOptions
&LangOpts
,
1983 const NamedDecl
*D
) {
1984 if (D
->isInvalidDecl())
1987 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
)) {
1988 // For a decomposition declaration, warn if none of the bindings are
1989 // referenced, instead of if the variable itself is referenced (which
1990 // it is, by the bindings' expressions).
1991 bool IsAllPlaceholders
= true;
1992 for (auto *BD
: DD
->bindings()) {
1993 if (BD
->isReferenced())
1995 IsAllPlaceholders
= IsAllPlaceholders
&& BD
->isPlaceholderVar(LangOpts
);
1997 if (IsAllPlaceholders
)
1999 } else if (!D
->getDeclName()) {
2001 } else if (D
->isReferenced() || D
->isUsed()) {
2005 if (D
->isPlaceholderVar(LangOpts
))
2008 if (D
->hasAttr
<UnusedAttr
>() || D
->hasAttr
<ObjCPreciseLifetimeAttr
>() ||
2009 D
->hasAttr
<CleanupAttr
>())
2012 if (isa
<LabelDecl
>(D
))
2015 // Except for labels, we only care about unused decls that are local to
2017 bool WithinFunction
= D
->getDeclContext()->isFunctionOrMethod();
2018 if (const auto *R
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext()))
2019 // For dependent types, the diagnostic is deferred.
2021 WithinFunction
|| (R
->isLocalClass() && !R
->isDependentType());
2022 if (!WithinFunction
)
2025 if (isa
<TypedefNameDecl
>(D
))
2028 // White-list anything that isn't a local variable.
2029 if (!isa
<VarDecl
>(D
) || isa
<ParmVarDecl
>(D
) || isa
<ImplicitParamDecl
>(D
))
2032 // Types of valid local variables should be complete, so this should succeed.
2033 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2035 const Expr
*Init
= VD
->getInit();
2036 if (const auto *Cleanups
= dyn_cast_or_null
<ExprWithCleanups
>(Init
))
2037 Init
= Cleanups
->getSubExpr();
2039 const auto *Ty
= VD
->getType().getTypePtr();
2041 // Only look at the outermost level of typedef.
2042 if (const TypedefType
*TT
= Ty
->getAs
<TypedefType
>()) {
2043 // Allow anything marked with __attribute__((unused)).
2044 if (TT
->getDecl()->hasAttr
<UnusedAttr
>())
2048 // Warn for reference variables whose initializtion performs lifetime
2050 if (const auto *MTE
= dyn_cast_or_null
<MaterializeTemporaryExpr
>(Init
)) {
2051 if (MTE
->getExtendingDecl()) {
2052 Ty
= VD
->getType().getNonReferenceType().getTypePtr();
2053 Init
= MTE
->getSubExpr()->IgnoreImplicitAsWritten();
2057 // If we failed to complete the type for some reason, or if the type is
2058 // dependent, don't diagnose the variable.
2059 if (Ty
->isIncompleteType() || Ty
->isDependentType())
2062 // Look at the element type to ensure that the warning behaviour is
2063 // consistent for both scalars and arrays.
2064 Ty
= Ty
->getBaseElementTypeUnsafe();
2066 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2067 const TagDecl
*Tag
= TT
->getDecl();
2068 if (Tag
->hasAttr
<UnusedAttr
>())
2071 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2072 if (!RD
->hasTrivialDestructor() && !RD
->hasAttr
<WarnUnusedAttr
>())
2076 const CXXConstructExpr
*Construct
=
2077 dyn_cast
<CXXConstructExpr
>(Init
);
2078 if (Construct
&& !Construct
->isElidable()) {
2079 CXXConstructorDecl
*CD
= Construct
->getConstructor();
2080 if (!CD
->isTrivial() && !RD
->hasAttr
<WarnUnusedAttr
>() &&
2081 (VD
->getInit()->isValueDependent() || !VD
->evaluateValue()))
2085 // Suppress the warning if we don't know how this is constructed, and
2086 // it could possibly be non-trivial constructor.
2087 if (Init
->isTypeDependent()) {
2088 for (const CXXConstructorDecl
*Ctor
: RD
->ctors())
2089 if (!Ctor
->isTrivial())
2093 // Suppress the warning if the constructor is unresolved because
2094 // its arguments are dependent.
2095 if (isa
<CXXUnresolvedConstructExpr
>(Init
))
2101 // TODO: __attribute__((unused)) templates?
2107 static void GenerateFixForUnusedDecl(const NamedDecl
*D
, ASTContext
&Ctx
,
2109 if (isa
<LabelDecl
>(D
)) {
2110 SourceLocation AfterColon
= Lexer::findLocationAfterToken(
2111 D
->getEndLoc(), tok::colon
, Ctx
.getSourceManager(), Ctx
.getLangOpts(),
2112 /*SkipTrailingWhitespaceAndNewline=*/false);
2113 if (AfterColon
.isInvalid())
2115 Hint
= FixItHint::CreateRemoval(
2116 CharSourceRange::getCharRange(D
->getBeginLoc(), AfterColon
));
2120 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl
*D
) {
2121 DiagnoseUnusedNestedTypedefs(
2122 D
, [this](SourceLocation Loc
, PartialDiagnostic PD
) { Diag(Loc
, PD
); });
2125 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl
*D
,
2126 DiagReceiverTy DiagReceiver
) {
2127 if (D
->getTypeForDecl()->isDependentType())
2130 for (auto *TmpD
: D
->decls()) {
2131 if (const auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
2132 DiagnoseUnusedDecl(T
, DiagReceiver
);
2133 else if(const auto *R
= dyn_cast
<RecordDecl
>(TmpD
))
2134 DiagnoseUnusedNestedTypedefs(R
, DiagReceiver
);
2138 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
) {
2140 D
, [this](SourceLocation Loc
, PartialDiagnostic PD
) { Diag(Loc
, PD
); });
2143 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2144 /// unless they are marked attr(unused).
2145 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
, DiagReceiverTy DiagReceiver
) {
2146 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D
))
2149 if (auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
2150 // typedefs can be referenced later on, so the diagnostics are emitted
2151 // at end-of-translation-unit.
2152 UnusedLocalTypedefNameCandidates
.insert(TD
);
2157 GenerateFixForUnusedDecl(D
, Context
, Hint
);
2160 if (isa
<VarDecl
>(D
) && cast
<VarDecl
>(D
)->isExceptionVariable())
2161 DiagID
= diag::warn_unused_exception_param
;
2162 else if (isa
<LabelDecl
>(D
))
2163 DiagID
= diag::warn_unused_label
;
2165 DiagID
= diag::warn_unused_variable
;
2167 SourceLocation DiagLoc
= D
->getLocation();
2168 DiagReceiver(DiagLoc
, PDiag(DiagID
) << D
<< Hint
<< SourceRange(DiagLoc
));
2171 void Sema::DiagnoseUnusedButSetDecl(const VarDecl
*VD
,
2172 DiagReceiverTy DiagReceiver
) {
2173 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2174 // it's not really unused.
2175 if (!VD
->isReferenced() || !VD
->getDeclName() || VD
->hasAttr
<CleanupAttr
>())
2178 // In C++, `_` variables behave as if they were maybe_unused
2179 if (VD
->hasAttr
<UnusedAttr
>() || VD
->isPlaceholderVar(getLangOpts()))
2182 const auto *Ty
= VD
->getType().getTypePtr()->getBaseElementTypeUnsafe();
2184 if (Ty
->isReferenceType() || Ty
->isDependentType())
2187 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2188 const TagDecl
*Tag
= TT
->getDecl();
2189 if (Tag
->hasAttr
<UnusedAttr
>())
2191 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2192 // mimic gcc's behavior.
2193 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2194 if (!RD
->hasAttr
<WarnUnusedAttr
>())
2199 // Don't warn about __block Objective-C pointer variables, as they might
2200 // be assigned in the block but not used elsewhere for the purpose of lifetime
2202 if (VD
->hasAttr
<BlocksAttr
>() && Ty
->isObjCObjectPointerType())
2205 // Don't warn about Objective-C pointer variables with precise lifetime
2206 // semantics; they can be used to ensure ARC releases the object at a known
2207 // time, which may mean assignment but no other references.
2208 if (VD
->hasAttr
<ObjCPreciseLifetimeAttr
>() && Ty
->isObjCObjectPointerType())
2211 auto iter
= RefsMinusAssignments
.find(VD
);
2212 if (iter
== RefsMinusAssignments
.end())
2215 assert(iter
->getSecond() >= 0 &&
2216 "Found a negative number of references to a VarDecl");
2217 if (iter
->getSecond() != 0)
2219 unsigned DiagID
= isa
<ParmVarDecl
>(VD
) ? diag::warn_unused_but_set_parameter
2220 : diag::warn_unused_but_set_variable
;
2221 DiagReceiver(VD
->getLocation(), PDiag(DiagID
) << VD
);
2224 static void CheckPoppedLabel(LabelDecl
*L
, Sema
&S
,
2225 Sema::DiagReceiverTy DiagReceiver
) {
2226 // Verify that we have no forward references left. If so, there was a goto
2227 // or address of a label taken, but no definition of it. Label fwd
2228 // definitions are indicated with a null substmt which is also not a resolved
2229 // MS inline assembly label name.
2230 bool Diagnose
= false;
2231 if (L
->isMSAsmLabel())
2232 Diagnose
= !L
->isResolvedMSAsmLabel();
2234 Diagnose
= L
->getStmt() == nullptr;
2236 DiagReceiver(L
->getLocation(), S
.PDiag(diag::err_undeclared_label_use
)
2240 void Sema::ActOnPopScope(SourceLocation Loc
, Scope
*S
) {
2243 if (S
->decl_empty()) return;
2244 assert((S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
)) &&
2245 "Scope shouldn't contain decls!");
2247 /// We visit the decls in non-deterministic order, but we want diagnostics
2248 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2249 /// and sort the diagnostics before emitting them, after we visited all decls.
2252 std::optional
<SourceLocation
> PreviousDeclLoc
;
2253 PartialDiagnostic PD
;
2255 SmallVector
<LocAndDiag
, 16> DeclDiags
;
2256 auto addDiag
= [&DeclDiags
](SourceLocation Loc
, PartialDiagnostic PD
) {
2257 DeclDiags
.push_back(LocAndDiag
{Loc
, std::nullopt
, std::move(PD
)});
2259 auto addDiagWithPrev
= [&DeclDiags
](SourceLocation Loc
,
2260 SourceLocation PreviousDeclLoc
,
2261 PartialDiagnostic PD
) {
2262 DeclDiags
.push_back(LocAndDiag
{Loc
, PreviousDeclLoc
, std::move(PD
)});
2265 for (auto *TmpD
: S
->decls()) {
2266 assert(TmpD
&& "This decl didn't get pushed??");
2268 assert(isa
<NamedDecl
>(TmpD
) && "Decl isn't NamedDecl?");
2269 NamedDecl
*D
= cast
<NamedDecl
>(TmpD
);
2271 // Diagnose unused variables in this scope.
2272 if (!S
->hasUnrecoverableErrorOccurred()) {
2273 DiagnoseUnusedDecl(D
, addDiag
);
2274 if (const auto *RD
= dyn_cast
<RecordDecl
>(D
))
2275 DiagnoseUnusedNestedTypedefs(RD
, addDiag
);
2276 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2277 DiagnoseUnusedButSetDecl(VD
, addDiag
);
2278 RefsMinusAssignments
.erase(VD
);
2282 if (!D
->getDeclName()) continue;
2284 // If this was a forward reference to a label, verify it was defined.
2285 if (LabelDecl
*LD
= dyn_cast
<LabelDecl
>(D
))
2286 CheckPoppedLabel(LD
, *this, addDiag
);
2288 // Remove this name from our lexical scope, and warn on it if we haven't
2290 IdResolver
.RemoveDecl(D
);
2291 auto ShadowI
= ShadowingDecls
.find(D
);
2292 if (ShadowI
!= ShadowingDecls
.end()) {
2293 if (const auto *FD
= dyn_cast
<FieldDecl
>(ShadowI
->second
)) {
2294 addDiagWithPrev(D
->getLocation(), FD
->getLocation(),
2295 PDiag(diag::warn_ctor_parm_shadows_field
)
2296 << D
<< FD
<< FD
->getParent());
2298 ShadowingDecls
.erase(ShadowI
);
2302 llvm::sort(DeclDiags
,
2303 [](const LocAndDiag
&LHS
, const LocAndDiag
&RHS
) -> bool {
2304 // The particular order for diagnostics is not important, as long
2305 // as the order is deterministic. Using the raw location is going
2306 // to generally be in source order unless there are macro
2307 // expansions involved.
2308 return LHS
.Loc
.getRawEncoding() < RHS
.Loc
.getRawEncoding();
2310 for (const LocAndDiag
&D
: DeclDiags
) {
2312 if (D
.PreviousDeclLoc
)
2313 Diag(*D
.PreviousDeclLoc
, diag::note_previous_declaration
);
2317 /// Look for an Objective-C class in the translation unit.
2319 /// \param Id The name of the Objective-C class we're looking for. If
2320 /// typo-correction fixes this name, the Id will be updated
2321 /// to the fixed name.
2323 /// \param IdLoc The location of the name in the translation unit.
2325 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2326 /// if there is no class with the given name.
2328 /// \returns The declaration of the named Objective-C class, or NULL if the
2329 /// class could not be found.
2330 ObjCInterfaceDecl
*Sema::getObjCInterfaceDecl(IdentifierInfo
*&Id
,
2331 SourceLocation IdLoc
,
2332 bool DoTypoCorrection
) {
2333 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2334 // creation from this context.
2335 NamedDecl
*IDecl
= LookupSingleName(TUScope
, Id
, IdLoc
, LookupOrdinaryName
);
2337 if (!IDecl
&& DoTypoCorrection
) {
2338 // Perform typo correction at the given location, but only if we
2339 // find an Objective-C class name.
2340 DeclFilterCCC
<ObjCInterfaceDecl
> CCC
{};
2341 if (TypoCorrection C
=
2342 CorrectTypo(DeclarationNameInfo(Id
, IdLoc
), LookupOrdinaryName
,
2343 TUScope
, nullptr, CCC
, CTK_ErrorRecovery
)) {
2344 diagnoseTypo(C
, PDiag(diag::err_undef_interface_suggest
) << Id
);
2345 IDecl
= C
.getCorrectionDeclAs
<ObjCInterfaceDecl
>();
2346 Id
= IDecl
->getIdentifier();
2349 ObjCInterfaceDecl
*Def
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IDecl
);
2350 // This routine must always return a class definition, if any.
2351 if (Def
&& Def
->getDefinition())
2352 Def
= Def
->getDefinition();
2356 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2357 /// from S, where a non-field would be declared. This routine copes
2358 /// with the difference between C and C++ scoping rules in structs and
2359 /// unions. For example, the following code is well-formed in C but
2360 /// ill-formed in C++:
2366 /// void test_S6() {
2371 /// For the declaration of BAR, this routine will return a different
2372 /// scope. The scope S will be the scope of the unnamed enumeration
2373 /// within S6. In C++, this routine will return the scope associated
2374 /// with S6, because the enumeration's scope is a transparent
2375 /// context but structures can contain non-field names. In C, this
2376 /// routine will return the translation unit scope, since the
2377 /// enumeration's scope is a transparent context and structures cannot
2378 /// contain non-field names.
2379 Scope
*Sema::getNonFieldDeclScope(Scope
*S
) {
2380 while (((S
->getFlags() & Scope::DeclScope
) == 0) ||
2381 (S
->getEntity() && S
->getEntity()->isTransparentContext()) ||
2382 (S
->isClassScope() && !getLangOpts().CPlusPlus
))
2387 static StringRef
getHeaderName(Builtin::Context
&BuiltinInfo
, unsigned ID
,
2388 ASTContext::GetBuiltinTypeError Error
) {
2390 case ASTContext::GE_None
:
2392 case ASTContext::GE_Missing_type
:
2393 return BuiltinInfo
.getHeaderName(ID
);
2394 case ASTContext::GE_Missing_stdio
:
2396 case ASTContext::GE_Missing_setjmp
:
2398 case ASTContext::GE_Missing_ucontext
:
2399 return "ucontext.h";
2401 llvm_unreachable("unhandled error kind");
2404 FunctionDecl
*Sema::CreateBuiltin(IdentifierInfo
*II
, QualType Type
,
2405 unsigned ID
, SourceLocation Loc
) {
2406 DeclContext
*Parent
= Context
.getTranslationUnitDecl();
2408 if (getLangOpts().CPlusPlus
) {
2409 LinkageSpecDecl
*CLinkageDecl
= LinkageSpecDecl::Create(
2410 Context
, Parent
, Loc
, Loc
, LinkageSpecLanguageIDs::C
, false);
2411 CLinkageDecl
->setImplicit();
2412 Parent
->addDecl(CLinkageDecl
);
2413 Parent
= CLinkageDecl
;
2416 FunctionDecl
*New
= FunctionDecl::Create(Context
, Parent
, Loc
, Loc
, II
, Type
,
2417 /*TInfo=*/nullptr, SC_Extern
,
2418 getCurFPFeatures().isFPConstrained(),
2419 false, Type
->isFunctionProtoType());
2421 New
->addAttr(BuiltinAttr::CreateImplicit(Context
, ID
));
2423 // Create Decl objects for each parameter, adding them to the
2425 if (const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(Type
)) {
2426 SmallVector
<ParmVarDecl
*, 16> Params
;
2427 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
2428 ParmVarDecl
*parm
= ParmVarDecl::Create(
2429 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
2430 FT
->getParamType(i
), /*TInfo=*/nullptr, SC_None
, nullptr);
2431 parm
->setScopeInfo(0, i
);
2432 Params
.push_back(parm
);
2434 New
->setParams(Params
);
2437 AddKnownFunctionAttributes(New
);
2441 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2442 /// file scope. lazily create a decl for it. ForRedeclaration is true
2443 /// if we're creating this built-in in anticipation of redeclaring the
2445 NamedDecl
*Sema::LazilyCreateBuiltin(IdentifierInfo
*II
, unsigned ID
,
2446 Scope
*S
, bool ForRedeclaration
,
2447 SourceLocation Loc
) {
2448 LookupNecessaryTypesForBuiltin(S
, ID
);
2450 ASTContext::GetBuiltinTypeError Error
;
2451 QualType R
= Context
.GetBuiltinType(ID
, Error
);
2453 if (!ForRedeclaration
)
2456 // If we have a builtin without an associated type we should not emit a
2457 // warning when we were not able to find a type for it.
2458 if (Error
== ASTContext::GE_Missing_type
||
2459 Context
.BuiltinInfo
.allowTypeMismatch(ID
))
2462 // If we could not find a type for setjmp it is because the jmp_buf type was
2463 // not defined prior to the setjmp declaration.
2464 if (Error
== ASTContext::GE_Missing_setjmp
) {
2465 Diag(Loc
, diag::warn_implicit_decl_no_jmp_buf
)
2466 << Context
.BuiltinInfo
.getName(ID
);
2470 // Generally, we emit a warning that the declaration requires the
2471 // appropriate header.
2472 Diag(Loc
, diag::warn_implicit_decl_requires_sysheader
)
2473 << getHeaderName(Context
.BuiltinInfo
, ID
, Error
)
2474 << Context
.BuiltinInfo
.getName(ID
);
2478 if (!ForRedeclaration
&&
2479 (Context
.BuiltinInfo
.isPredefinedLibFunction(ID
) ||
2480 Context
.BuiltinInfo
.isHeaderDependentFunction(ID
))) {
2481 Diag(Loc
, LangOpts
.C99
? diag::ext_implicit_lib_function_decl_c99
2482 : diag::ext_implicit_lib_function_decl
)
2483 << Context
.BuiltinInfo
.getName(ID
) << R
;
2484 if (const char *Header
= Context
.BuiltinInfo
.getHeaderName(ID
))
2485 Diag(Loc
, diag::note_include_header_or_declare
)
2486 << Header
<< Context
.BuiltinInfo
.getName(ID
);
2492 FunctionDecl
*New
= CreateBuiltin(II
, R
, ID
, Loc
);
2493 RegisterLocallyScopedExternCDecl(New
, S
);
2495 // TUScope is the translation-unit scope to insert this function into.
2496 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2497 // relate Scopes to DeclContexts, and probably eliminate CurContext
2498 // entirely, but we're not there yet.
2499 DeclContext
*SavedContext
= CurContext
;
2500 CurContext
= New
->getDeclContext();
2501 PushOnScopeChains(New
, TUScope
);
2502 CurContext
= SavedContext
;
2506 /// Typedef declarations don't have linkage, but they still denote the same
2507 /// entity if their types are the same.
2508 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2510 static void filterNonConflictingPreviousTypedefDecls(Sema
&S
,
2511 TypedefNameDecl
*Decl
,
2512 LookupResult
&Previous
) {
2513 // This is only interesting when modules are enabled.
2514 if (!S
.getLangOpts().Modules
&& !S
.getLangOpts().ModulesLocalVisibility
)
2517 // Empty sets are uninteresting.
2518 if (Previous
.empty())
2521 LookupResult::Filter Filter
= Previous
.makeFilter();
2522 while (Filter
.hasNext()) {
2523 NamedDecl
*Old
= Filter
.next();
2525 // Non-hidden declarations are never ignored.
2526 if (S
.isVisible(Old
))
2529 // Declarations of the same entity are not ignored, even if they have
2530 // different linkages.
2531 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2532 if (S
.Context
.hasSameType(OldTD
->getUnderlyingType(),
2533 Decl
->getUnderlyingType()))
2536 // If both declarations give a tag declaration a typedef name for linkage
2537 // purposes, then they declare the same entity.
2538 if (OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2539 Decl
->getAnonDeclWithTypedefName())
2549 bool Sema::isIncompatibleTypedef(TypeDecl
*Old
, TypedefNameDecl
*New
) {
2551 if (TypedefNameDecl
*OldTypedef
= dyn_cast
<TypedefNameDecl
>(Old
))
2552 OldType
= OldTypedef
->getUnderlyingType();
2554 OldType
= Context
.getTypeDeclType(Old
);
2555 QualType NewType
= New
->getUnderlyingType();
2557 if (NewType
->isVariablyModifiedType()) {
2558 // Must not redefine a typedef with a variably-modified type.
2559 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2560 Diag(New
->getLocation(), diag::err_redefinition_variably_modified_typedef
)
2562 if (Old
->getLocation().isValid())
2563 notePreviousDefinition(Old
, New
->getLocation());
2564 New
->setInvalidDecl();
2568 if (OldType
!= NewType
&&
2569 !OldType
->isDependentType() &&
2570 !NewType
->isDependentType() &&
2571 !Context
.hasSameType(OldType
, NewType
)) {
2572 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2573 Diag(New
->getLocation(), diag::err_redefinition_different_typedef
)
2574 << Kind
<< NewType
<< OldType
;
2575 if (Old
->getLocation().isValid())
2576 notePreviousDefinition(Old
, New
->getLocation());
2577 New
->setInvalidDecl();
2583 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2584 /// same name and scope as a previous declaration 'Old'. Figure out
2585 /// how to resolve this situation, merging decls or emitting
2586 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2588 void Sema::MergeTypedefNameDecl(Scope
*S
, TypedefNameDecl
*New
,
2589 LookupResult
&OldDecls
) {
2590 // If the new decl is known invalid already, don't bother doing any
2592 if (New
->isInvalidDecl()) return;
2594 // Allow multiple definitions for ObjC built-in typedefs.
2595 // FIXME: Verify the underlying types are equivalent!
2596 if (getLangOpts().ObjC
) {
2597 const IdentifierInfo
*TypeID
= New
->getIdentifier();
2598 switch (TypeID
->getLength()) {
2602 if (!TypeID
->isStr("id"))
2604 QualType T
= New
->getUnderlyingType();
2605 if (!T
->isPointerType())
2607 if (!T
->isVoidPointerType()) {
2608 QualType PT
= T
->castAs
<PointerType
>()->getPointeeType();
2609 if (!PT
->isStructureType())
2612 Context
.setObjCIdRedefinitionType(T
);
2613 // Install the built-in type for 'id', ignoring the current definition.
2614 New
->setTypeForDecl(Context
.getObjCIdType().getTypePtr());
2618 if (!TypeID
->isStr("Class"))
2620 Context
.setObjCClassRedefinitionType(New
->getUnderlyingType());
2621 // Install the built-in type for 'Class', ignoring the current definition.
2622 New
->setTypeForDecl(Context
.getObjCClassType().getTypePtr());
2625 if (!TypeID
->isStr("SEL"))
2627 Context
.setObjCSelRedefinitionType(New
->getUnderlyingType());
2628 // Install the built-in type for 'SEL', ignoring the current definition.
2629 New
->setTypeForDecl(Context
.getObjCSelType().getTypePtr());
2632 // Fall through - the typedef name was not a builtin type.
2635 // Verify the old decl was also a type.
2636 TypeDecl
*Old
= OldDecls
.getAsSingle
<TypeDecl
>();
2638 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
2639 << New
->getDeclName();
2641 NamedDecl
*OldD
= OldDecls
.getRepresentativeDecl();
2642 if (OldD
->getLocation().isValid())
2643 notePreviousDefinition(OldD
, New
->getLocation());
2645 return New
->setInvalidDecl();
2648 // If the old declaration is invalid, just give up here.
2649 if (Old
->isInvalidDecl())
2650 return New
->setInvalidDecl();
2652 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2653 auto *OldTag
= OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2654 auto *NewTag
= New
->getAnonDeclWithTypedefName();
2655 NamedDecl
*Hidden
= nullptr;
2656 if (OldTag
&& NewTag
&&
2657 OldTag
->getCanonicalDecl() != NewTag
->getCanonicalDecl() &&
2658 !hasVisibleDefinition(OldTag
, &Hidden
)) {
2659 // There is a definition of this tag, but it is not visible. Use it
2660 // instead of our tag.
2661 New
->setTypeForDecl(OldTD
->getTypeForDecl());
2662 if (OldTD
->isModed())
2663 New
->setModedTypeSourceInfo(OldTD
->getTypeSourceInfo(),
2664 OldTD
->getUnderlyingType());
2666 New
->setTypeSourceInfo(OldTD
->getTypeSourceInfo());
2668 // Make the old tag definition visible.
2669 makeMergedDefinitionVisible(Hidden
);
2671 // If this was an unscoped enumeration, yank all of its enumerators
2672 // out of the scope.
2673 if (isa
<EnumDecl
>(NewTag
)) {
2674 Scope
*EnumScope
= getNonFieldDeclScope(S
);
2675 for (auto *D
: NewTag
->decls()) {
2676 auto *ED
= cast
<EnumConstantDecl
>(D
);
2677 assert(EnumScope
->isDeclScope(ED
));
2678 EnumScope
->RemoveDecl(ED
);
2679 IdResolver
.RemoveDecl(ED
);
2680 ED
->getLexicalDeclContext()->removeDecl(ED
);
2686 // If the typedef types are not identical, reject them in all languages and
2687 // with any extensions enabled.
2688 if (isIncompatibleTypedef(Old
, New
))
2691 // The types match. Link up the redeclaration chain and merge attributes if
2692 // the old declaration was a typedef.
2693 if (TypedefNameDecl
*Typedef
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2694 New
->setPreviousDecl(Typedef
);
2695 mergeDeclAttributes(New
, Old
);
2698 if (getLangOpts().MicrosoftExt
)
2701 if (getLangOpts().CPlusPlus
) {
2702 // C++ [dcl.typedef]p2:
2703 // In a given non-class scope, a typedef specifier can be used to
2704 // redefine the name of any type declared in that scope to refer
2705 // to the type to which it already refers.
2706 if (!isa
<CXXRecordDecl
>(CurContext
))
2709 // C++0x [dcl.typedef]p4:
2710 // In a given class scope, a typedef specifier can be used to redefine
2711 // any class-name declared in that scope that is not also a typedef-name
2712 // to refer to the type to which it already refers.
2714 // This wording came in via DR424, which was a correction to the
2715 // wording in DR56, which accidentally banned code like:
2718 // typedef struct A { } A;
2721 // in the C++03 standard. We implement the C++0x semantics, which
2722 // allow the above but disallow
2729 // since that was the intent of DR56.
2730 if (!isa
<TypedefNameDecl
>(Old
))
2733 Diag(New
->getLocation(), diag::err_redefinition
)
2734 << New
->getDeclName();
2735 notePreviousDefinition(Old
, New
->getLocation());
2736 return New
->setInvalidDecl();
2739 // Modules always permit redefinition of typedefs, as does C11.
2740 if (getLangOpts().Modules
|| getLangOpts().C11
)
2743 // If we have a redefinition of a typedef in C, emit a warning. This warning
2744 // is normally mapped to an error, but can be controlled with
2745 // -Wtypedef-redefinition. If either the original or the redefinition is
2746 // in a system header, don't emit this for compatibility with GCC.
2747 if (getDiagnostics().getSuppressSystemWarnings() &&
2748 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2749 (Old
->isImplicit() ||
2750 Context
.getSourceManager().isInSystemHeader(Old
->getLocation()) ||
2751 Context
.getSourceManager().isInSystemHeader(New
->getLocation())))
2754 Diag(New
->getLocation(), diag::ext_redefinition_of_typedef
)
2755 << New
->getDeclName();
2756 notePreviousDefinition(Old
, New
->getLocation());
2759 /// DeclhasAttr - returns true if decl Declaration already has the target
2761 static bool DeclHasAttr(const Decl
*D
, const Attr
*A
) {
2762 const OwnershipAttr
*OA
= dyn_cast
<OwnershipAttr
>(A
);
2763 const AnnotateAttr
*Ann
= dyn_cast
<AnnotateAttr
>(A
);
2764 for (const auto *i
: D
->attrs())
2765 if (i
->getKind() == A
->getKind()) {
2767 if (Ann
->getAnnotation() == cast
<AnnotateAttr
>(i
)->getAnnotation())
2771 // FIXME: Don't hardcode this check
2772 if (OA
&& isa
<OwnershipAttr
>(i
))
2773 return OA
->getOwnKind() == cast
<OwnershipAttr
>(i
)->getOwnKind();
2780 static bool isAttributeTargetADefinition(Decl
*D
) {
2781 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
2782 return VD
->isThisDeclarationADefinition();
2783 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
2784 return TD
->isCompleteDefinition() || TD
->isBeingDefined();
2788 /// Merge alignment attributes from \p Old to \p New, taking into account the
2789 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2791 /// \return \c true if any attributes were added to \p New.
2792 static bool mergeAlignedAttrs(Sema
&S
, NamedDecl
*New
, Decl
*Old
) {
2793 // Look for alignas attributes on Old, and pick out whichever attribute
2794 // specifies the strictest alignment requirement.
2795 AlignedAttr
*OldAlignasAttr
= nullptr;
2796 AlignedAttr
*OldStrictestAlignAttr
= nullptr;
2797 unsigned OldAlign
= 0;
2798 for (auto *I
: Old
->specific_attrs
<AlignedAttr
>()) {
2799 // FIXME: We have no way of representing inherited dependent alignments
2801 // template<int A, int B> struct alignas(A) X;
2802 // template<int A, int B> struct alignas(B) X {};
2803 // For now, we just ignore any alignas attributes which are not on the
2804 // definition in such a case.
2805 if (I
->isAlignmentDependent())
2811 unsigned Align
= I
->getAlignment(S
.Context
);
2812 if (Align
> OldAlign
) {
2814 OldStrictestAlignAttr
= I
;
2818 // Look for alignas attributes on New.
2819 AlignedAttr
*NewAlignasAttr
= nullptr;
2820 unsigned NewAlign
= 0;
2821 for (auto *I
: New
->specific_attrs
<AlignedAttr
>()) {
2822 if (I
->isAlignmentDependent())
2828 unsigned Align
= I
->getAlignment(S
.Context
);
2829 if (Align
> NewAlign
)
2833 if (OldAlignasAttr
&& NewAlignasAttr
&& OldAlign
!= NewAlign
) {
2834 // Both declarations have 'alignas' attributes. We require them to match.
2835 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2836 // fall short. (If two declarations both have alignas, they must both match
2837 // every definition, and so must match each other if there is a definition.)
2839 // If either declaration only contains 'alignas(0)' specifiers, then it
2840 // specifies the natural alignment for the type.
2841 if (OldAlign
== 0 || NewAlign
== 0) {
2843 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(New
))
2846 Ty
= S
.Context
.getTagDeclType(cast
<TagDecl
>(New
));
2849 OldAlign
= S
.Context
.getTypeAlign(Ty
);
2851 NewAlign
= S
.Context
.getTypeAlign(Ty
);
2854 if (OldAlign
!= NewAlign
) {
2855 S
.Diag(NewAlignasAttr
->getLocation(), diag::err_alignas_mismatch
)
2856 << (unsigned)S
.Context
.toCharUnitsFromBits(OldAlign
).getQuantity()
2857 << (unsigned)S
.Context
.toCharUnitsFromBits(NewAlign
).getQuantity();
2858 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_previous_declaration
);
2862 if (OldAlignasAttr
&& !NewAlignasAttr
&& isAttributeTargetADefinition(New
)) {
2863 // C++11 [dcl.align]p6:
2864 // if any declaration of an entity has an alignment-specifier,
2865 // every defining declaration of that entity shall specify an
2866 // equivalent alignment.
2868 // If the definition of an object does not have an alignment
2869 // specifier, any other declaration of that object shall also
2870 // have no alignment specifier.
2871 S
.Diag(New
->getLocation(), diag::err_alignas_missing_on_definition
)
2873 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_alignas_on_declaration
)
2877 bool AnyAdded
= false;
2879 // Ensure we have an attribute representing the strictest alignment.
2880 if (OldAlign
> NewAlign
) {
2881 AlignedAttr
*Clone
= OldStrictestAlignAttr
->clone(S
.Context
);
2882 Clone
->setInherited(true);
2883 New
->addAttr(Clone
);
2887 // Ensure we have an alignas attribute if the old declaration had one.
2888 if (OldAlignasAttr
&& !NewAlignasAttr
&&
2889 !(AnyAdded
&& OldStrictestAlignAttr
->isAlignas())) {
2890 AlignedAttr
*Clone
= OldAlignasAttr
->clone(S
.Context
);
2891 Clone
->setInherited(true);
2892 New
->addAttr(Clone
);
2899 #define WANT_DECL_MERGE_LOGIC
2900 #include "clang/Sema/AttrParsedAttrImpl.inc"
2901 #undef WANT_DECL_MERGE_LOGIC
2903 static bool mergeDeclAttribute(Sema
&S
, NamedDecl
*D
,
2904 const InheritableAttr
*Attr
,
2905 Sema::AvailabilityMergeKind AMK
) {
2906 // Diagnose any mutual exclusions between the attribute that we want to add
2907 // and attributes that already exist on the declaration.
2908 if (!DiagnoseMutualExclusions(S
, D
, Attr
))
2911 // This function copies an attribute Attr from a previous declaration to the
2912 // new declaration D if the new declaration doesn't itself have that attribute
2913 // yet or if that attribute allows duplicates.
2914 // If you're adding a new attribute that requires logic different from
2915 // "use explicit attribute on decl if present, else use attribute from
2916 // previous decl", for example if the attribute needs to be consistent
2917 // between redeclarations, you need to call a custom merge function here.
2918 InheritableAttr
*NewAttr
= nullptr;
2919 if (const auto *AA
= dyn_cast
<AvailabilityAttr
>(Attr
))
2920 NewAttr
= S
.mergeAvailabilityAttr(
2921 D
, *AA
, AA
->getPlatform(), AA
->isImplicit(), AA
->getIntroduced(),
2922 AA
->getDeprecated(), AA
->getObsoleted(), AA
->getUnavailable(),
2923 AA
->getMessage(), AA
->getStrict(), AA
->getReplacement(), AMK
,
2925 else if (const auto *VA
= dyn_cast
<VisibilityAttr
>(Attr
))
2926 NewAttr
= S
.mergeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2927 else if (const auto *VA
= dyn_cast
<TypeVisibilityAttr
>(Attr
))
2928 NewAttr
= S
.mergeTypeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2929 else if (const auto *ImportA
= dyn_cast
<DLLImportAttr
>(Attr
))
2930 NewAttr
= S
.mergeDLLImportAttr(D
, *ImportA
);
2931 else if (const auto *ExportA
= dyn_cast
<DLLExportAttr
>(Attr
))
2932 NewAttr
= S
.mergeDLLExportAttr(D
, *ExportA
);
2933 else if (const auto *EA
= dyn_cast
<ErrorAttr
>(Attr
))
2934 NewAttr
= S
.mergeErrorAttr(D
, *EA
, EA
->getUserDiagnostic());
2935 else if (const auto *FA
= dyn_cast
<FormatAttr
>(Attr
))
2936 NewAttr
= S
.mergeFormatAttr(D
, *FA
, FA
->getType(), FA
->getFormatIdx(),
2938 else if (const auto *SA
= dyn_cast
<SectionAttr
>(Attr
))
2939 NewAttr
= S
.mergeSectionAttr(D
, *SA
, SA
->getName());
2940 else if (const auto *CSA
= dyn_cast
<CodeSegAttr
>(Attr
))
2941 NewAttr
= S
.mergeCodeSegAttr(D
, *CSA
, CSA
->getName());
2942 else if (const auto *IA
= dyn_cast
<MSInheritanceAttr
>(Attr
))
2943 NewAttr
= S
.mergeMSInheritanceAttr(D
, *IA
, IA
->getBestCase(),
2944 IA
->getInheritanceModel());
2945 else if (const auto *AA
= dyn_cast
<AlwaysInlineAttr
>(Attr
))
2946 NewAttr
= S
.mergeAlwaysInlineAttr(D
, *AA
,
2947 &S
.Context
.Idents
.get(AA
->getSpelling()));
2948 else if (S
.getLangOpts().CUDA
&& isa
<FunctionDecl
>(D
) &&
2949 (isa
<CUDAHostAttr
>(Attr
) || isa
<CUDADeviceAttr
>(Attr
) ||
2950 isa
<CUDAGlobalAttr
>(Attr
))) {
2951 // CUDA target attributes are part of function signature for
2952 // overloading purposes and must not be merged.
2954 } else if (const auto *MA
= dyn_cast
<MinSizeAttr
>(Attr
))
2955 NewAttr
= S
.mergeMinSizeAttr(D
, *MA
);
2956 else if (const auto *SNA
= dyn_cast
<SwiftNameAttr
>(Attr
))
2957 NewAttr
= S
.mergeSwiftNameAttr(D
, *SNA
, SNA
->getName());
2958 else if (const auto *OA
= dyn_cast
<OptimizeNoneAttr
>(Attr
))
2959 NewAttr
= S
.mergeOptimizeNoneAttr(D
, *OA
);
2960 else if (const auto *InternalLinkageA
= dyn_cast
<InternalLinkageAttr
>(Attr
))
2961 NewAttr
= S
.mergeInternalLinkageAttr(D
, *InternalLinkageA
);
2962 else if (isa
<AlignedAttr
>(Attr
))
2963 // AlignedAttrs are handled separately, because we need to handle all
2964 // such attributes on a declaration at the same time.
2966 else if ((isa
<DeprecatedAttr
>(Attr
) || isa
<UnavailableAttr
>(Attr
)) &&
2967 (AMK
== Sema::AMK_Override
||
2968 AMK
== Sema::AMK_ProtocolImplementation
||
2969 AMK
== Sema::AMK_OptionalProtocolImplementation
))
2971 else if (const auto *UA
= dyn_cast
<UuidAttr
>(Attr
))
2972 NewAttr
= S
.mergeUuidAttr(D
, *UA
, UA
->getGuid(), UA
->getGuidDecl());
2973 else if (const auto *IMA
= dyn_cast
<WebAssemblyImportModuleAttr
>(Attr
))
2974 NewAttr
= S
.mergeImportModuleAttr(D
, *IMA
);
2975 else if (const auto *INA
= dyn_cast
<WebAssemblyImportNameAttr
>(Attr
))
2976 NewAttr
= S
.mergeImportNameAttr(D
, *INA
);
2977 else if (const auto *TCBA
= dyn_cast
<EnforceTCBAttr
>(Attr
))
2978 NewAttr
= S
.mergeEnforceTCBAttr(D
, *TCBA
);
2979 else if (const auto *TCBLA
= dyn_cast
<EnforceTCBLeafAttr
>(Attr
))
2980 NewAttr
= S
.mergeEnforceTCBLeafAttr(D
, *TCBLA
);
2981 else if (const auto *BTFA
= dyn_cast
<BTFDeclTagAttr
>(Attr
))
2982 NewAttr
= S
.mergeBTFDeclTagAttr(D
, *BTFA
);
2983 else if (const auto *NT
= dyn_cast
<HLSLNumThreadsAttr
>(Attr
))
2985 S
.mergeHLSLNumThreadsAttr(D
, *NT
, NT
->getX(), NT
->getY(), NT
->getZ());
2986 else if (const auto *SA
= dyn_cast
<HLSLShaderAttr
>(Attr
))
2987 NewAttr
= S
.mergeHLSLShaderAttr(D
, *SA
, SA
->getType());
2988 else if (Attr
->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D
, Attr
))
2989 NewAttr
= cast
<InheritableAttr
>(Attr
->clone(S
.Context
));
2992 NewAttr
->setInherited(true);
2993 D
->addAttr(NewAttr
);
2994 if (isa
<MSInheritanceAttr
>(NewAttr
))
2995 S
.Consumer
.AssignInheritanceModel(cast
<CXXRecordDecl
>(D
));
3002 static const NamedDecl
*getDefinition(const Decl
*D
) {
3003 if (const TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
3004 return TD
->getDefinition();
3005 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
3006 const VarDecl
*Def
= VD
->getDefinition();
3009 return VD
->getActingDefinition();
3011 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
3012 const FunctionDecl
*Def
= nullptr;
3013 if (FD
->isDefined(Def
, true))
3019 static bool hasAttribute(const Decl
*D
, attr::Kind Kind
) {
3020 for (const auto *Attribute
: D
->attrs())
3021 if (Attribute
->getKind() == Kind
)
3026 /// checkNewAttributesAfterDef - If we already have a definition, check that
3027 /// there are no new attributes in this declaration.
3028 static void checkNewAttributesAfterDef(Sema
&S
, Decl
*New
, const Decl
*Old
) {
3029 if (!New
->hasAttrs())
3032 const NamedDecl
*Def
= getDefinition(Old
);
3033 if (!Def
|| Def
== New
)
3036 AttrVec
&NewAttributes
= New
->getAttrs();
3037 for (unsigned I
= 0, E
= NewAttributes
.size(); I
!= E
;) {
3038 const Attr
*NewAttribute
= NewAttributes
[I
];
3040 if (isa
<AliasAttr
>(NewAttribute
) || isa
<IFuncAttr
>(NewAttribute
)) {
3041 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(New
)) {
3042 Sema::SkipBodyInfo SkipBody
;
3043 S
.CheckForFunctionRedefinition(FD
, cast
<FunctionDecl
>(Def
), &SkipBody
);
3045 // If we're skipping this definition, drop the "alias" attribute.
3046 if (SkipBody
.ShouldSkip
) {
3047 NewAttributes
.erase(NewAttributes
.begin() + I
);
3052 VarDecl
*VD
= cast
<VarDecl
>(New
);
3053 unsigned Diag
= cast
<VarDecl
>(Def
)->isThisDeclarationADefinition() ==
3054 VarDecl::TentativeDefinition
3055 ? diag::err_alias_after_tentative
3056 : diag::err_redefinition
;
3057 S
.Diag(VD
->getLocation(), Diag
) << VD
->getDeclName();
3058 if (Diag
== diag::err_redefinition
)
3059 S
.notePreviousDefinition(Def
, VD
->getLocation());
3061 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3062 VD
->setInvalidDecl();
3068 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(Def
)) {
3069 // Tentative definitions are only interesting for the alias check above.
3070 if (VD
->isThisDeclarationADefinition() != VarDecl::Definition
) {
3076 if (hasAttribute(Def
, NewAttribute
->getKind())) {
3078 continue; // regular attr merging will take care of validating this.
3081 if (isa
<C11NoReturnAttr
>(NewAttribute
)) {
3082 // C's _Noreturn is allowed to be added to a function after it is defined.
3085 } else if (isa
<UuidAttr
>(NewAttribute
)) {
3086 // msvc will allow a subsequent definition to add an uuid to a class
3089 } else if (const AlignedAttr
*AA
= dyn_cast
<AlignedAttr
>(NewAttribute
)) {
3090 if (AA
->isAlignas()) {
3091 // C++11 [dcl.align]p6:
3092 // if any declaration of an entity has an alignment-specifier,
3093 // every defining declaration of that entity shall specify an
3094 // equivalent alignment.
3096 // If the definition of an object does not have an alignment
3097 // specifier, any other declaration of that object shall also
3098 // have no alignment specifier.
3099 S
.Diag(Def
->getLocation(), diag::err_alignas_missing_on_definition
)
3101 S
.Diag(NewAttribute
->getLocation(), diag::note_alignas_on_declaration
)
3103 NewAttributes
.erase(NewAttributes
.begin() + I
);
3107 } else if (isa
<LoaderUninitializedAttr
>(NewAttribute
)) {
3108 // If there is a C definition followed by a redeclaration with this
3109 // attribute then there are two different definitions. In C++, prefer the
3110 // standard diagnostics.
3111 if (!S
.getLangOpts().CPlusPlus
) {
3112 S
.Diag(NewAttribute
->getLocation(),
3113 diag::err_loader_uninitialized_redeclaration
);
3114 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3115 NewAttributes
.erase(NewAttributes
.begin() + I
);
3119 } else if (isa
<SelectAnyAttr
>(NewAttribute
) &&
3120 cast
<VarDecl
>(New
)->isInline() &&
3121 !cast
<VarDecl
>(New
)->isInlineSpecified()) {
3122 // Don't warn about applying selectany to implicitly inline variables.
3123 // Older compilers and language modes would require the use of selectany
3124 // to make such variables inline, and it would have no effect if we
3128 } else if (isa
<OMPDeclareVariantAttr
>(NewAttribute
)) {
3129 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3130 // declarations after definitions.
3135 S
.Diag(NewAttribute
->getLocation(),
3136 diag::warn_attribute_precede_definition
);
3137 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3138 NewAttributes
.erase(NewAttributes
.begin() + I
);
3143 static void diagnoseMissingConstinit(Sema
&S
, const VarDecl
*InitDecl
,
3144 const ConstInitAttr
*CIAttr
,
3145 bool AttrBeforeInit
) {
3146 SourceLocation InsertLoc
= InitDecl
->getInnerLocStart();
3148 // Figure out a good way to write this specifier on the old declaration.
3149 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3150 // enough of the attribute list spelling information to extract that without
3152 std::string SuitableSpelling
;
3153 if (S
.getLangOpts().CPlusPlus20
)
3154 SuitableSpelling
= std::string(
3155 S
.PP
.getLastMacroWithSpelling(InsertLoc
, {tok::kw_constinit
}));
3156 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3157 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3158 InsertLoc
, {tok::l_square
, tok::l_square
,
3159 S
.PP
.getIdentifierInfo("clang"), tok::coloncolon
,
3160 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3161 tok::r_square
, tok::r_square
}));
3162 if (SuitableSpelling
.empty())
3163 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3164 InsertLoc
, {tok::kw___attribute
, tok::l_paren
, tok::r_paren
,
3165 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3166 tok::r_paren
, tok::r_paren
}));
3167 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus20
)
3168 SuitableSpelling
= "constinit";
3169 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3170 SuitableSpelling
= "[[clang::require_constant_initialization]]";
3171 if (SuitableSpelling
.empty())
3172 SuitableSpelling
= "__attribute__((require_constant_initialization))";
3173 SuitableSpelling
+= " ";
3175 if (AttrBeforeInit
) {
3176 // extern constinit int a;
3177 // int a = 0; // error (missing 'constinit'), accepted as extension
3178 assert(CIAttr
->isConstinit() && "should not diagnose this for attribute");
3179 S
.Diag(InitDecl
->getLocation(), diag::ext_constinit_missing
)
3180 << InitDecl
<< FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3181 S
.Diag(CIAttr
->getLocation(), diag::note_constinit_specified_here
);
3184 // constinit extern int a; // error (missing 'constinit')
3185 S
.Diag(CIAttr
->getLocation(),
3186 CIAttr
->isConstinit() ? diag::err_constinit_added_too_late
3187 : diag::warn_require_const_init_added_too_late
)
3188 << FixItHint::CreateRemoval(SourceRange(CIAttr
->getLocation()));
3189 S
.Diag(InitDecl
->getLocation(), diag::note_constinit_missing_here
)
3190 << CIAttr
->isConstinit()
3191 << FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3195 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3196 void Sema::mergeDeclAttributes(NamedDecl
*New
, Decl
*Old
,
3197 AvailabilityMergeKind AMK
) {
3198 if (UsedAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<UsedAttr
>()) {
3199 UsedAttr
*NewAttr
= OldAttr
->clone(Context
);
3200 NewAttr
->setInherited(true);
3201 New
->addAttr(NewAttr
);
3203 if (RetainAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<RetainAttr
>()) {
3204 RetainAttr
*NewAttr
= OldAttr
->clone(Context
);
3205 NewAttr
->setInherited(true);
3206 New
->addAttr(NewAttr
);
3209 if (!Old
->hasAttrs() && !New
->hasAttrs())
3212 // [dcl.constinit]p1:
3213 // If the [constinit] specifier is applied to any declaration of a
3214 // variable, it shall be applied to the initializing declaration.
3215 const auto *OldConstInit
= Old
->getAttr
<ConstInitAttr
>();
3216 const auto *NewConstInit
= New
->getAttr
<ConstInitAttr
>();
3217 if (bool(OldConstInit
) != bool(NewConstInit
)) {
3218 const auto *OldVD
= cast
<VarDecl
>(Old
);
3219 auto *NewVD
= cast
<VarDecl
>(New
);
3221 // Find the initializing declaration. Note that we might not have linked
3222 // the new declaration into the redeclaration chain yet.
3223 const VarDecl
*InitDecl
= OldVD
->getInitializingDeclaration();
3225 (NewVD
->hasInit() || NewVD
->isThisDeclarationADefinition()))
3228 if (InitDecl
== NewVD
) {
3229 // This is the initializing declaration. If it would inherit 'constinit',
3230 // that's ill-formed. (Note that we do not apply this to the attribute
3232 if (OldConstInit
&& OldConstInit
->isConstinit())
3233 diagnoseMissingConstinit(*this, NewVD
, OldConstInit
,
3234 /*AttrBeforeInit=*/true);
3235 } else if (NewConstInit
) {
3236 // This is the first time we've been told that this declaration should
3237 // have a constant initializer. If we already saw the initializing
3238 // declaration, this is too late.
3239 if (InitDecl
&& InitDecl
!= NewVD
) {
3240 diagnoseMissingConstinit(*this, InitDecl
, NewConstInit
,
3241 /*AttrBeforeInit=*/false);
3242 NewVD
->dropAttr
<ConstInitAttr
>();
3247 // Attributes declared post-definition are currently ignored.
3248 checkNewAttributesAfterDef(*this, New
, Old
);
3250 if (AsmLabelAttr
*NewA
= New
->getAttr
<AsmLabelAttr
>()) {
3251 if (AsmLabelAttr
*OldA
= Old
->getAttr
<AsmLabelAttr
>()) {
3252 if (!OldA
->isEquivalent(NewA
)) {
3253 // This redeclaration changes __asm__ label.
3254 Diag(New
->getLocation(), diag::err_different_asm_label
);
3255 Diag(OldA
->getLocation(), diag::note_previous_declaration
);
3257 } else if (Old
->isUsed()) {
3258 // This redeclaration adds an __asm__ label to a declaration that has
3259 // already been ODR-used.
3260 Diag(New
->getLocation(), diag::err_late_asm_label_name
)
3261 << isa
<FunctionDecl
>(Old
) << New
->getAttr
<AsmLabelAttr
>()->getRange();
3265 // Re-declaration cannot add abi_tag's.
3266 if (const auto *NewAbiTagAttr
= New
->getAttr
<AbiTagAttr
>()) {
3267 if (const auto *OldAbiTagAttr
= Old
->getAttr
<AbiTagAttr
>()) {
3268 for (const auto &NewTag
: NewAbiTagAttr
->tags()) {
3269 if (!llvm::is_contained(OldAbiTagAttr
->tags(), NewTag
)) {
3270 Diag(NewAbiTagAttr
->getLocation(),
3271 diag::err_new_abi_tag_on_redeclaration
)
3273 Diag(OldAbiTagAttr
->getLocation(), diag::note_previous_declaration
);
3277 Diag(NewAbiTagAttr
->getLocation(), diag::err_abi_tag_on_redeclaration
);
3278 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3282 // This redeclaration adds a section attribute.
3283 if (New
->hasAttr
<SectionAttr
>() && !Old
->hasAttr
<SectionAttr
>()) {
3284 if (auto *VD
= dyn_cast
<VarDecl
>(New
)) {
3285 if (VD
->isThisDeclarationADefinition() == VarDecl::DeclarationOnly
) {
3286 Diag(New
->getLocation(), diag::warn_attribute_section_on_redeclaration
);
3287 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3292 // Redeclaration adds code-seg attribute.
3293 const auto *NewCSA
= New
->getAttr
<CodeSegAttr
>();
3294 if (NewCSA
&& !Old
->hasAttr
<CodeSegAttr
>() &&
3295 !NewCSA
->isImplicit() && isa
<CXXMethodDecl
>(New
)) {
3296 Diag(New
->getLocation(), diag::warn_mismatched_section
)
3298 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3301 if (!Old
->hasAttrs())
3304 bool foundAny
= New
->hasAttrs();
3306 // Ensure that any moving of objects within the allocated map is done before
3308 if (!foundAny
) New
->setAttrs(AttrVec());
3310 for (auto *I
: Old
->specific_attrs
<InheritableAttr
>()) {
3311 // Ignore deprecated/unavailable/availability attributes if requested.
3312 AvailabilityMergeKind LocalAMK
= AMK_None
;
3313 if (isa
<DeprecatedAttr
>(I
) ||
3314 isa
<UnavailableAttr
>(I
) ||
3315 isa
<AvailabilityAttr
>(I
)) {
3320 case AMK_Redeclaration
:
3322 case AMK_ProtocolImplementation
:
3323 case AMK_OptionalProtocolImplementation
:
3330 if (isa
<UsedAttr
>(I
) || isa
<RetainAttr
>(I
))
3333 if (mergeDeclAttribute(*this, New
, I
, LocalAMK
))
3337 if (mergeAlignedAttrs(*this, New
, Old
))
3340 if (!foundAny
) New
->dropAttrs();
3343 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3345 static void mergeParamDeclAttributes(ParmVarDecl
*newDecl
,
3346 const ParmVarDecl
*oldDecl
,
3348 // C++11 [dcl.attr.depend]p2:
3349 // The first declaration of a function shall specify the
3350 // carries_dependency attribute for its declarator-id if any declaration
3351 // of the function specifies the carries_dependency attribute.
3352 const CarriesDependencyAttr
*CDA
= newDecl
->getAttr
<CarriesDependencyAttr
>();
3353 if (CDA
&& !oldDecl
->hasAttr
<CarriesDependencyAttr
>()) {
3354 S
.Diag(CDA
->getLocation(),
3355 diag::err_carries_dependency_missing_on_first_decl
) << 1/*Param*/;
3356 // Find the first declaration of the parameter.
3357 // FIXME: Should we build redeclaration chains for function parameters?
3358 const FunctionDecl
*FirstFD
=
3359 cast
<FunctionDecl
>(oldDecl
->getDeclContext())->getFirstDecl();
3360 const ParmVarDecl
*FirstVD
=
3361 FirstFD
->getParamDecl(oldDecl
->getFunctionScopeIndex());
3362 S
.Diag(FirstVD
->getLocation(),
3363 diag::note_carries_dependency_missing_first_decl
) << 1/*Param*/;
3366 if (!oldDecl
->hasAttrs())
3369 bool foundAny
= newDecl
->hasAttrs();
3371 // Ensure that any moving of objects within the allocated map is
3372 // done before we process them.
3373 if (!foundAny
) newDecl
->setAttrs(AttrVec());
3375 for (const auto *I
: oldDecl
->specific_attrs
<InheritableParamAttr
>()) {
3376 if (!DeclHasAttr(newDecl
, I
)) {
3377 InheritableAttr
*newAttr
=
3378 cast
<InheritableParamAttr
>(I
->clone(S
.Context
));
3379 newAttr
->setInherited(true);
3380 newDecl
->addAttr(newAttr
);
3385 if (!foundAny
) newDecl
->dropAttrs();
3388 static bool EquivalentArrayTypes(QualType Old
, QualType New
,
3389 const ASTContext
&Ctx
) {
3391 auto NoSizeInfo
= [&Ctx
](QualType Ty
) {
3392 if (Ty
->isIncompleteArrayType() || Ty
->isPointerType())
3394 if (const auto *VAT
= Ctx
.getAsVariableArrayType(Ty
))
3395 return VAT
->getSizeModifier() == ArraySizeModifier::Star
;
3399 // `type[]` is equivalent to `type *` and `type[*]`.
3400 if (NoSizeInfo(Old
) && NoSizeInfo(New
))
3403 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3404 if (Old
->isVariableArrayType() && New
->isVariableArrayType()) {
3405 const auto *OldVAT
= Ctx
.getAsVariableArrayType(Old
);
3406 const auto *NewVAT
= Ctx
.getAsVariableArrayType(New
);
3407 if ((OldVAT
->getSizeModifier() == ArraySizeModifier::Star
) ^
3408 (NewVAT
->getSizeModifier() == ArraySizeModifier::Star
))
3413 // Only compare size, ignore Size modifiers and CVR.
3414 if (Old
->isConstantArrayType() && New
->isConstantArrayType()) {
3415 return Ctx
.getAsConstantArrayType(Old
)->getSize() ==
3416 Ctx
.getAsConstantArrayType(New
)->getSize();
3419 // Don't try to compare dependent sized array
3420 if (Old
->isDependentSizedArrayType() && New
->isDependentSizedArrayType()) {
3427 static void mergeParamDeclTypes(ParmVarDecl
*NewParam
,
3428 const ParmVarDecl
*OldParam
,
3430 if (auto Oldnullability
= OldParam
->getType()->getNullability()) {
3431 if (auto Newnullability
= NewParam
->getType()->getNullability()) {
3432 if (*Oldnullability
!= *Newnullability
) {
3433 S
.Diag(NewParam
->getLocation(), diag::warn_mismatched_nullability_attr
)
3434 << DiagNullabilityKind(
3436 ((NewParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3438 << DiagNullabilityKind(
3440 ((OldParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3442 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration
);
3445 QualType NewT
= NewParam
->getType();
3446 NewT
= S
.Context
.getAttributedType(
3447 AttributedType::getNullabilityAttrKind(*Oldnullability
),
3449 NewParam
->setType(NewT
);
3452 const auto *OldParamDT
= dyn_cast
<DecayedType
>(OldParam
->getType());
3453 const auto *NewParamDT
= dyn_cast
<DecayedType
>(NewParam
->getType());
3454 if (OldParamDT
&& NewParamDT
&&
3455 OldParamDT
->getPointeeType() == NewParamDT
->getPointeeType()) {
3456 QualType OldParamOT
= OldParamDT
->getOriginalType();
3457 QualType NewParamOT
= NewParamDT
->getOriginalType();
3458 if (!EquivalentArrayTypes(OldParamOT
, NewParamOT
, S
.getASTContext())) {
3459 S
.Diag(NewParam
->getLocation(), diag::warn_inconsistent_array_form
)
3460 << NewParam
<< NewParamOT
;
3461 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration_as
)
3469 /// Used in MergeFunctionDecl to keep track of function parameters in
3471 struct GNUCompatibleParamWarning
{
3472 ParmVarDecl
*OldParm
;
3473 ParmVarDecl
*NewParm
;
3474 QualType PromotedType
;
3477 } // end anonymous namespace
3479 // Determine whether the previous declaration was a definition, implicit
3480 // declaration, or a declaration.
3481 template <typename T
>
3482 static std::pair
<diag::kind
, SourceLocation
>
3483 getNoteDiagForInvalidRedeclaration(const T
*Old
, const T
*New
) {
3484 diag::kind PrevDiag
;
3485 SourceLocation OldLocation
= Old
->getLocation();
3486 if (Old
->isThisDeclarationADefinition())
3487 PrevDiag
= diag::note_previous_definition
;
3488 else if (Old
->isImplicit()) {
3489 PrevDiag
= diag::note_previous_implicit_declaration
;
3490 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Old
)) {
3491 if (FD
->getBuiltinID())
3492 PrevDiag
= diag::note_previous_builtin_declaration
;
3494 if (OldLocation
.isInvalid())
3495 OldLocation
= New
->getLocation();
3497 PrevDiag
= diag::note_previous_declaration
;
3498 return std::make_pair(PrevDiag
, OldLocation
);
3501 /// canRedefineFunction - checks if a function can be redefined. Currently,
3502 /// only extern inline functions can be redefined, and even then only in
3504 static bool canRedefineFunction(const FunctionDecl
*FD
,
3505 const LangOptions
& LangOpts
) {
3506 return ((FD
->hasAttr
<GNUInlineAttr
>() || LangOpts
.GNUInline
) &&
3507 !LangOpts
.CPlusPlus
&&
3508 FD
->isInlineSpecified() &&
3509 FD
->getStorageClass() == SC_Extern
);
3512 const AttributedType
*Sema::getCallingConvAttributedType(QualType T
) const {
3513 const AttributedType
*AT
= T
->getAs
<AttributedType
>();
3514 while (AT
&& !AT
->isCallingConv())
3515 AT
= AT
->getModifiedType()->getAs
<AttributedType
>();
3519 template <typename T
>
3520 static bool haveIncompatibleLanguageLinkages(const T
*Old
, const T
*New
) {
3521 const DeclContext
*DC
= Old
->getDeclContext();
3525 LanguageLinkage OldLinkage
= Old
->getLanguageLinkage();
3526 if (OldLinkage
== CXXLanguageLinkage
&& New
->isInExternCContext())
3528 if (OldLinkage
== CLanguageLinkage
&& New
->isInExternCXXContext())
3533 template<typename T
> static bool isExternC(T
*D
) { return D
->isExternC(); }
3534 static bool isExternC(VarTemplateDecl
*) { return false; }
3535 static bool isExternC(FunctionTemplateDecl
*) { return false; }
3537 /// Check whether a redeclaration of an entity introduced by a
3538 /// using-declaration is valid, given that we know it's not an overload
3539 /// (nor a hidden tag declaration).
3540 template<typename ExpectedDecl
>
3541 static bool checkUsingShadowRedecl(Sema
&S
, UsingShadowDecl
*OldS
,
3542 ExpectedDecl
*New
) {
3543 // C++11 [basic.scope.declarative]p4:
3544 // Given a set of declarations in a single declarative region, each of
3545 // which specifies the same unqualified name,
3546 // -- they shall all refer to the same entity, or all refer to functions
3547 // and function templates; or
3548 // -- exactly one declaration shall declare a class name or enumeration
3549 // name that is not a typedef name and the other declarations shall all
3550 // refer to the same variable or enumerator, or all refer to functions
3551 // and function templates; in this case the class name or enumeration
3552 // name is hidden (3.3.10).
3554 // C++11 [namespace.udecl]p14:
3555 // If a function declaration in namespace scope or block scope has the
3556 // same name and the same parameter-type-list as a function introduced
3557 // by a using-declaration, and the declarations do not declare the same
3558 // function, the program is ill-formed.
3560 auto *Old
= dyn_cast
<ExpectedDecl
>(OldS
->getTargetDecl());
3562 !Old
->getDeclContext()->getRedeclContext()->Equals(
3563 New
->getDeclContext()->getRedeclContext()) &&
3564 !(isExternC(Old
) && isExternC(New
)))
3568 S
.Diag(New
->getLocation(), diag::err_using_decl_conflict_reverse
);
3569 S
.Diag(OldS
->getTargetDecl()->getLocation(), diag::note_using_decl_target
);
3570 S
.Diag(OldS
->getIntroducer()->getLocation(), diag::note_using_decl
) << 0;
3576 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl
*A
,
3577 const FunctionDecl
*B
) {
3578 assert(A
->getNumParams() == B
->getNumParams());
3580 auto AttrEq
= [](const ParmVarDecl
*A
, const ParmVarDecl
*B
) {
3581 const auto *AttrA
= A
->getAttr
<PassObjectSizeAttr
>();
3582 const auto *AttrB
= B
->getAttr
<PassObjectSizeAttr
>();
3585 return AttrA
&& AttrB
&& AttrA
->getType() == AttrB
->getType() &&
3586 AttrA
->isDynamic() == AttrB
->isDynamic();
3589 return std::equal(A
->param_begin(), A
->param_end(), B
->param_begin(), AttrEq
);
3592 /// If necessary, adjust the semantic declaration context for a qualified
3593 /// declaration to name the correct inline namespace within the qualifier.
3594 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl
*NewD
,
3595 DeclaratorDecl
*OldD
) {
3596 // The only case where we need to update the DeclContext is when
3597 // redeclaration lookup for a qualified name finds a declaration
3598 // in an inline namespace within the context named by the qualifier:
3600 // inline namespace N { int f(); }
3601 // int ::f(); // Sema DC needs adjusting from :: to N::.
3603 // For unqualified declarations, the semantic context *can* change
3604 // along the redeclaration chain (for local extern declarations,
3605 // extern "C" declarations, and friend declarations in particular).
3606 if (!NewD
->getQualifier())
3609 // NewD is probably already in the right context.
3610 auto *NamedDC
= NewD
->getDeclContext()->getRedeclContext();
3611 auto *SemaDC
= OldD
->getDeclContext()->getRedeclContext();
3612 if (NamedDC
->Equals(SemaDC
))
3615 assert((NamedDC
->InEnclosingNamespaceSetOf(SemaDC
) ||
3616 NewD
->isInvalidDecl() || OldD
->isInvalidDecl()) &&
3617 "unexpected context for redeclaration");
3619 auto *LexDC
= NewD
->getLexicalDeclContext();
3620 auto FixSemaDC
= [=](NamedDecl
*D
) {
3623 D
->setDeclContext(SemaDC
);
3624 D
->setLexicalDeclContext(LexDC
);
3628 if (auto *FD
= dyn_cast
<FunctionDecl
>(NewD
))
3629 FixSemaDC(FD
->getDescribedFunctionTemplate());
3630 else if (auto *VD
= dyn_cast
<VarDecl
>(NewD
))
3631 FixSemaDC(VD
->getDescribedVarTemplate());
3634 /// MergeFunctionDecl - We just parsed a function 'New' from
3635 /// declarator D which has the same name and scope as a previous
3636 /// declaration 'Old'. Figure out how to resolve this situation,
3637 /// merging decls or emitting diagnostics as appropriate.
3639 /// In C++, New and Old must be declarations that are not
3640 /// overloaded. Use IsOverload to determine whether New and Old are
3641 /// overloaded, and to select the Old declaration that New should be
3644 /// Returns true if there was an error, false otherwise.
3645 bool Sema::MergeFunctionDecl(FunctionDecl
*New
, NamedDecl
*&OldD
, Scope
*S
,
3646 bool MergeTypeWithOld
, bool NewDeclIsDefn
) {
3647 // Verify the old decl was also a function.
3648 FunctionDecl
*Old
= OldD
->getAsFunction();
3650 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(OldD
)) {
3651 if (New
->getFriendObjectKind()) {
3652 Diag(New
->getLocation(), diag::err_using_decl_friend
);
3653 Diag(Shadow
->getTargetDecl()->getLocation(),
3654 diag::note_using_decl_target
);
3655 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
3660 // Check whether the two declarations might declare the same function or
3661 // function template.
3662 if (FunctionTemplateDecl
*NewTemplate
=
3663 New
->getDescribedFunctionTemplate()) {
3664 if (checkUsingShadowRedecl
<FunctionTemplateDecl
>(*this, Shadow
,
3667 OldD
= Old
= cast
<FunctionTemplateDecl
>(Shadow
->getTargetDecl())
3670 if (checkUsingShadowRedecl
<FunctionDecl
>(*this, Shadow
, New
))
3672 OldD
= Old
= cast
<FunctionDecl
>(Shadow
->getTargetDecl());
3675 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
3676 << New
->getDeclName();
3677 notePreviousDefinition(OldD
, New
->getLocation());
3682 // If the old declaration was found in an inline namespace and the new
3683 // declaration was qualified, update the DeclContext to match.
3684 adjustDeclContextForDeclaratorDecl(New
, Old
);
3686 // If the old declaration is invalid, just give up here.
3687 if (Old
->isInvalidDecl())
3690 // Disallow redeclaration of some builtins.
3691 if (!getASTContext().canBuiltinBeRedeclared(Old
)) {
3692 Diag(New
->getLocation(), diag::err_builtin_redeclare
) << Old
->getDeclName();
3693 Diag(Old
->getLocation(), diag::note_previous_builtin_declaration
)
3694 << Old
<< Old
->getType();
3698 diag::kind PrevDiag
;
3699 SourceLocation OldLocation
;
3700 std::tie(PrevDiag
, OldLocation
) =
3701 getNoteDiagForInvalidRedeclaration(Old
, New
);
3703 // Don't complain about this if we're in GNU89 mode and the old function
3704 // is an extern inline function.
3705 // Don't complain about specializations. They are not supposed to have
3707 if (!isa
<CXXMethodDecl
>(New
) && !isa
<CXXMethodDecl
>(Old
) &&
3708 New
->getStorageClass() == SC_Static
&&
3709 Old
->hasExternalFormalLinkage() &&
3710 !New
->getTemplateSpecializationInfo() &&
3711 !canRedefineFunction(Old
, getLangOpts())) {
3712 if (getLangOpts().MicrosoftExt
) {
3713 Diag(New
->getLocation(), diag::ext_static_non_static
) << New
;
3714 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3716 Diag(New
->getLocation(), diag::err_static_non_static
) << New
;
3717 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3722 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
3723 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
3724 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
3726 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3727 New
->dropAttr
<InternalLinkageAttr
>();
3730 if (auto *EA
= New
->getAttr
<ErrorAttr
>()) {
3731 if (!Old
->hasAttr
<ErrorAttr
>()) {
3732 Diag(EA
->getLocation(), diag::err_attribute_missing_on_first_decl
) << EA
;
3733 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3734 New
->dropAttr
<ErrorAttr
>();
3738 if (CheckRedeclarationInModule(New
, Old
))
3741 if (!getLangOpts().CPlusPlus
) {
3742 bool OldOvl
= Old
->hasAttr
<OverloadableAttr
>();
3743 if (OldOvl
!= New
->hasAttr
<OverloadableAttr
>() && !Old
->isImplicit()) {
3744 Diag(New
->getLocation(), diag::err_attribute_overloadable_mismatch
)
3747 // Try our best to find a decl that actually has the overloadable
3748 // attribute for the note. In most cases (e.g. programs with only one
3749 // broken declaration/definition), this won't matter.
3751 // FIXME: We could do this if we juggled some extra state in
3752 // OverloadableAttr, rather than just removing it.
3753 const Decl
*DiagOld
= Old
;
3755 auto OldIter
= llvm::find_if(Old
->redecls(), [](const Decl
*D
) {
3756 const auto *A
= D
->getAttr
<OverloadableAttr
>();
3757 return A
&& !A
->isImplicit();
3759 // If we've implicitly added *all* of the overloadable attrs to this
3760 // chain, emitting a "previous redecl" note is pointless.
3761 DiagOld
= OldIter
== Old
->redecls_end() ? nullptr : *OldIter
;
3765 Diag(DiagOld
->getLocation(),
3766 diag::note_attribute_overloadable_prev_overload
)
3770 New
->addAttr(OverloadableAttr::CreateImplicit(Context
));
3772 New
->dropAttr
<OverloadableAttr
>();
3776 // It is not permitted to redeclare an SME function with different SME
3778 if (IsInvalidSMECallConversion(Old
->getType(), New
->getType(),
3779 AArch64SMECallConversionKind::MatchExactly
)) {
3780 Diag(New
->getLocation(), diag::err_sme_attr_mismatch
)
3781 << New
->getType() << Old
->getType();
3782 Diag(OldLocation
, diag::note_previous_declaration
);
3786 // If a function is first declared with a calling convention, but is later
3787 // declared or defined without one, all following decls assume the calling
3788 // convention of the first.
3790 // It's OK if a function is first declared without a calling convention,
3791 // but is later declared or defined with the default calling convention.
3793 // To test if either decl has an explicit calling convention, we look for
3794 // AttributedType sugar nodes on the type as written. If they are missing or
3795 // were canonicalized away, we assume the calling convention was implicit.
3797 // Note also that we DO NOT return at this point, because we still have
3798 // other tests to run.
3799 QualType OldQType
= Context
.getCanonicalType(Old
->getType());
3800 QualType NewQType
= Context
.getCanonicalType(New
->getType());
3801 const FunctionType
*OldType
= cast
<FunctionType
>(OldQType
);
3802 const FunctionType
*NewType
= cast
<FunctionType
>(NewQType
);
3803 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
3804 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
3805 bool RequiresAdjustment
= false;
3807 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC()) {
3808 FunctionDecl
*First
= Old
->getFirstDecl();
3809 const FunctionType
*FT
=
3810 First
->getType().getCanonicalType()->castAs
<FunctionType
>();
3811 FunctionType::ExtInfo FI
= FT
->getExtInfo();
3812 bool NewCCExplicit
= getCallingConvAttributedType(New
->getType());
3813 if (!NewCCExplicit
) {
3814 // Inherit the CC from the previous declaration if it was specified
3815 // there but not here.
3816 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3817 RequiresAdjustment
= true;
3818 } else if (Old
->getBuiltinID()) {
3819 // Builtin attribute isn't propagated to the new one yet at this point,
3820 // so we check if the old one is a builtin.
3822 // Calling Conventions on a Builtin aren't really useful and setting a
3823 // default calling convention and cdecl'ing some builtin redeclarations is
3824 // common, so warn and ignore the calling convention on the redeclaration.
3825 Diag(New
->getLocation(), diag::warn_cconv_unsupported
)
3826 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3827 << (int)CallingConventionIgnoredReason::BuiltinFunction
;
3828 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3829 RequiresAdjustment
= true;
3831 // Calling conventions aren't compatible, so complain.
3832 bool FirstCCExplicit
= getCallingConvAttributedType(First
->getType());
3833 Diag(New
->getLocation(), diag::err_cconv_change
)
3834 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3836 << (!FirstCCExplicit
? "" :
3837 FunctionType::getNameForCallConv(FI
.getCC()));
3839 // Put the note on the first decl, since it is the one that matters.
3840 Diag(First
->getLocation(), diag::note_previous_declaration
);
3845 // FIXME: diagnose the other way around?
3846 if (OldTypeInfo
.getNoReturn() && !NewTypeInfo
.getNoReturn()) {
3847 NewTypeInfo
= NewTypeInfo
.withNoReturn(true);
3848 RequiresAdjustment
= true;
3851 // Merge regparm attribute.
3852 if (OldTypeInfo
.getHasRegParm() != NewTypeInfo
.getHasRegParm() ||
3853 OldTypeInfo
.getRegParm() != NewTypeInfo
.getRegParm()) {
3854 if (NewTypeInfo
.getHasRegParm()) {
3855 Diag(New
->getLocation(), diag::err_regparm_mismatch
)
3856 << NewType
->getRegParmType()
3857 << OldType
->getRegParmType();
3858 Diag(OldLocation
, diag::note_previous_declaration
);
3862 NewTypeInfo
= NewTypeInfo
.withRegParm(OldTypeInfo
.getRegParm());
3863 RequiresAdjustment
= true;
3866 // Merge ns_returns_retained attribute.
3867 if (OldTypeInfo
.getProducesResult() != NewTypeInfo
.getProducesResult()) {
3868 if (NewTypeInfo
.getProducesResult()) {
3869 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
)
3870 << "'ns_returns_retained'";
3871 Diag(OldLocation
, diag::note_previous_declaration
);
3875 NewTypeInfo
= NewTypeInfo
.withProducesResult(true);
3876 RequiresAdjustment
= true;
3879 if (OldTypeInfo
.getNoCallerSavedRegs() !=
3880 NewTypeInfo
.getNoCallerSavedRegs()) {
3881 if (NewTypeInfo
.getNoCallerSavedRegs()) {
3882 AnyX86NoCallerSavedRegistersAttr
*Attr
=
3883 New
->getAttr
<AnyX86NoCallerSavedRegistersAttr
>();
3884 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
) << Attr
;
3885 Diag(OldLocation
, diag::note_previous_declaration
);
3889 NewTypeInfo
= NewTypeInfo
.withNoCallerSavedRegs(true);
3890 RequiresAdjustment
= true;
3893 if (RequiresAdjustment
) {
3894 const FunctionType
*AdjustedType
= New
->getType()->getAs
<FunctionType
>();
3895 AdjustedType
= Context
.adjustFunctionType(AdjustedType
, NewTypeInfo
);
3896 New
->setType(QualType(AdjustedType
, 0));
3897 NewQType
= Context
.getCanonicalType(New
->getType());
3900 // If this redeclaration makes the function inline, we may need to add it to
3901 // UndefinedButUsed.
3902 if (!Old
->isInlined() && New
->isInlined() &&
3903 !New
->hasAttr
<GNUInlineAttr
>() &&
3904 !getLangOpts().GNUInline
&&
3905 Old
->isUsed(false) &&
3906 !Old
->isDefined() && !New
->isThisDeclarationADefinition())
3907 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
3910 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3912 if (New
->hasAttr
<GNUInlineAttr
>() &&
3913 Old
->isInlined() && !Old
->hasAttr
<GNUInlineAttr
>()) {
3914 UndefinedButUsed
.erase(Old
->getCanonicalDecl());
3917 // If pass_object_size params don't match up perfectly, this isn't a valid
3919 if (Old
->getNumParams() > 0 && Old
->getNumParams() == New
->getNumParams() &&
3920 !hasIdenticalPassObjectSizeAttrs(Old
, New
)) {
3921 Diag(New
->getLocation(), diag::err_different_pass_object_size_params
)
3922 << New
->getDeclName();
3923 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3927 if (getLangOpts().CPlusPlus
) {
3928 OldQType
= Context
.getCanonicalType(Old
->getType());
3929 NewQType
= Context
.getCanonicalType(New
->getType());
3931 // Go back to the type source info to compare the declared return types,
3932 // per C++1y [dcl.type.auto]p13:
3933 // Redeclarations or specializations of a function or function template
3934 // with a declared return type that uses a placeholder type shall also
3935 // use that placeholder, not a deduced type.
3936 QualType OldDeclaredReturnType
= Old
->getDeclaredReturnType();
3937 QualType NewDeclaredReturnType
= New
->getDeclaredReturnType();
3938 if (!Context
.hasSameType(OldDeclaredReturnType
, NewDeclaredReturnType
) &&
3939 canFullyTypeCheckRedeclaration(New
, Old
, NewDeclaredReturnType
,
3940 OldDeclaredReturnType
)) {
3942 if (NewDeclaredReturnType
->isObjCObjectPointerType() &&
3943 OldDeclaredReturnType
->isObjCObjectPointerType())
3944 // FIXME: This does the wrong thing for a deduced return type.
3945 ResQT
= Context
.mergeObjCGCQualifiers(NewQType
, OldQType
);
3946 if (ResQT
.isNull()) {
3947 if (New
->isCXXClassMember() && New
->isOutOfLine())
3948 Diag(New
->getLocation(), diag::err_member_def_does_not_match_ret_type
)
3949 << New
<< New
->getReturnTypeSourceRange();
3951 Diag(New
->getLocation(), diag::err_ovl_diff_return_type
)
3952 << New
->getReturnTypeSourceRange();
3953 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType()
3954 << Old
->getReturnTypeSourceRange();
3961 QualType OldReturnType
= OldType
->getReturnType();
3962 QualType NewReturnType
= cast
<FunctionType
>(NewQType
)->getReturnType();
3963 if (OldReturnType
!= NewReturnType
) {
3964 // If this function has a deduced return type and has already been
3965 // defined, copy the deduced value from the old declaration.
3966 AutoType
*OldAT
= Old
->getReturnType()->getContainedAutoType();
3967 if (OldAT
&& OldAT
->isDeduced()) {
3968 QualType DT
= OldAT
->getDeducedType();
3970 New
->setType(SubstAutoTypeDependent(New
->getType()));
3971 NewQType
= Context
.getCanonicalType(SubstAutoTypeDependent(NewQType
));
3973 New
->setType(SubstAutoType(New
->getType(), DT
));
3974 NewQType
= Context
.getCanonicalType(SubstAutoType(NewQType
, DT
));
3979 const CXXMethodDecl
*OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
3980 CXXMethodDecl
*NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
3981 if (OldMethod
&& NewMethod
) {
3982 // Preserve triviality.
3983 NewMethod
->setTrivial(OldMethod
->isTrivial());
3985 // MSVC allows explicit template specialization at class scope:
3986 // 2 CXXMethodDecls referring to the same function will be injected.
3987 // We don't want a redeclaration error.
3988 bool IsClassScopeExplicitSpecialization
=
3989 OldMethod
->isFunctionTemplateSpecialization() &&
3990 NewMethod
->isFunctionTemplateSpecialization();
3991 bool isFriend
= NewMethod
->getFriendObjectKind();
3993 if (!isFriend
&& NewMethod
->getLexicalDeclContext()->isRecord() &&
3994 !IsClassScopeExplicitSpecialization
) {
3995 // -- Member function declarations with the same name and the
3996 // same parameter types cannot be overloaded if any of them
3997 // is a static member function declaration.
3998 if (OldMethod
->isStatic() != NewMethod
->isStatic()) {
3999 Diag(New
->getLocation(), diag::err_ovl_static_nonstatic_member
);
4000 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4004 // C++ [class.mem]p1:
4005 // [...] A member shall not be declared twice in the
4006 // member-specification, except that a nested class or member
4007 // class template can be declared and then later defined.
4008 if (!inTemplateInstantiation()) {
4010 if (isa
<CXXConstructorDecl
>(OldMethod
))
4011 NewDiag
= diag::err_constructor_redeclared
;
4012 else if (isa
<CXXDestructorDecl
>(NewMethod
))
4013 NewDiag
= diag::err_destructor_redeclared
;
4014 else if (isa
<CXXConversionDecl
>(NewMethod
))
4015 NewDiag
= diag::err_conv_function_redeclared
;
4017 NewDiag
= diag::err_member_redeclared
;
4019 Diag(New
->getLocation(), NewDiag
);
4021 Diag(New
->getLocation(), diag::err_member_redeclared_in_instantiation
)
4022 << New
<< New
->getType();
4024 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4027 // Complain if this is an explicit declaration of a special
4028 // member that was initially declared implicitly.
4030 // As an exception, it's okay to befriend such methods in order
4031 // to permit the implicit constructor/destructor/operator calls.
4032 } else if (OldMethod
->isImplicit()) {
4034 NewMethod
->setImplicit();
4036 Diag(NewMethod
->getLocation(),
4037 diag::err_definition_of_implicitly_declared_member
)
4038 << New
<< getSpecialMember(OldMethod
);
4041 } else if (OldMethod
->getFirstDecl()->isExplicitlyDefaulted() && !isFriend
) {
4042 Diag(NewMethod
->getLocation(),
4043 diag::err_definition_of_explicitly_defaulted_member
)
4044 << getSpecialMember(OldMethod
);
4049 // C++1z [over.load]p2
4050 // Certain function declarations cannot be overloaded:
4051 // -- Function declarations that differ only in the return type,
4052 // the exception specification, or both cannot be overloaded.
4054 // Check the exception specifications match. This may recompute the type of
4055 // both Old and New if it resolved exception specifications, so grab the
4056 // types again after this. Because this updates the type, we do this before
4057 // any of the other checks below, which may update the "de facto" NewQType
4058 // but do not necessarily update the type of New.
4059 if (CheckEquivalentExceptionSpec(Old
, New
))
4062 // C++11 [dcl.attr.noreturn]p1:
4063 // The first declaration of a function shall specify the noreturn
4064 // attribute if any declaration of that function specifies the noreturn
4066 if (const auto *NRA
= New
->getAttr
<CXX11NoReturnAttr
>())
4067 if (!Old
->hasAttr
<CXX11NoReturnAttr
>()) {
4068 Diag(NRA
->getLocation(), diag::err_attribute_missing_on_first_decl
)
4070 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4073 // C++11 [dcl.attr.depend]p2:
4074 // The first declaration of a function shall specify the
4075 // carries_dependency attribute for its declarator-id if any declaration
4076 // of the function specifies the carries_dependency attribute.
4077 const CarriesDependencyAttr
*CDA
= New
->getAttr
<CarriesDependencyAttr
>();
4078 if (CDA
&& !Old
->hasAttr
<CarriesDependencyAttr
>()) {
4079 Diag(CDA
->getLocation(),
4080 diag::err_carries_dependency_missing_on_first_decl
) << 0/*Function*/;
4081 Diag(Old
->getFirstDecl()->getLocation(),
4082 diag::note_carries_dependency_missing_first_decl
) << 0/*Function*/;
4086 // All declarations for a function shall agree exactly in both the
4087 // return type and the parameter-type-list.
4088 // We also want to respect all the extended bits except noreturn.
4090 // noreturn should now match unless the old type info didn't have it.
4091 QualType OldQTypeForComparison
= OldQType
;
4092 if (!OldTypeInfo
.getNoReturn() && NewTypeInfo
.getNoReturn()) {
4093 auto *OldType
= OldQType
->castAs
<FunctionProtoType
>();
4094 const FunctionType
*OldTypeForComparison
4095 = Context
.adjustFunctionType(OldType
, OldTypeInfo
.withNoReturn(true));
4096 OldQTypeForComparison
= QualType(OldTypeForComparison
, 0);
4097 assert(OldQTypeForComparison
.isCanonical());
4100 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
4101 // As a special case, retain the language linkage from previous
4102 // declarations of a friend function as an extension.
4104 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4105 // and is useful because there's otherwise no way to specify language
4106 // linkage within class scope.
4108 // Check cautiously as the friend object kind isn't yet complete.
4109 if (New
->getFriendObjectKind() != Decl::FOK_None
) {
4110 Diag(New
->getLocation(), diag::ext_retained_language_linkage
) << New
;
4111 Diag(OldLocation
, PrevDiag
);
4113 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4114 Diag(OldLocation
, PrevDiag
);
4119 // If the function types are compatible, merge the declarations. Ignore the
4120 // exception specifier because it was already checked above in
4121 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4122 // about incompatible types under -fms-compatibility.
4123 if (Context
.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison
,
4125 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4127 // If the types are imprecise (due to dependent constructs in friends or
4128 // local extern declarations), it's OK if they differ. We'll check again
4129 // during instantiation.
4130 if (!canFullyTypeCheckRedeclaration(New
, Old
, NewQType
, OldQType
))
4133 // Fall through for conflicting redeclarations and redefinitions.
4136 // C: Function types need to be compatible, not identical. This handles
4137 // duplicate function decls like "void f(int); void f(enum X);" properly.
4138 if (!getLangOpts().CPlusPlus
) {
4139 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4140 // type is specified by a function definition that contains a (possibly
4141 // empty) identifier list, both shall agree in the number of parameters
4142 // and the type of each parameter shall be compatible with the type that
4143 // results from the application of default argument promotions to the
4144 // type of the corresponding identifier. ...
4145 // This cannot be handled by ASTContext::typesAreCompatible() because that
4146 // doesn't know whether the function type is for a definition or not when
4147 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4148 // we need to cover here is that the number of arguments agree as the
4149 // default argument promotion rules were already checked by
4150 // ASTContext::typesAreCompatible().
4151 if (Old
->hasPrototype() && !New
->hasWrittenPrototype() && NewDeclIsDefn
&&
4152 Old
->getNumParams() != New
->getNumParams() && !Old
->isImplicit()) {
4153 if (Old
->hasInheritedPrototype())
4154 Old
= Old
->getCanonicalDecl();
4155 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
;
4156 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
4160 // If we are merging two functions where only one of them has a prototype,
4161 // we may have enough information to decide to issue a diagnostic that the
4162 // function without a protoype will change behavior in C23. This handles
4164 // void i(); void i(int j);
4165 // void i(int j); void i();
4166 // void i(); void i(int j) {}
4167 // See ActOnFinishFunctionBody() for other cases of the behavior change
4168 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4169 // type without a prototype.
4170 if (New
->hasWrittenPrototype() != Old
->hasWrittenPrototype() &&
4171 !New
->isImplicit() && !Old
->isImplicit()) {
4172 const FunctionDecl
*WithProto
, *WithoutProto
;
4173 if (New
->hasWrittenPrototype()) {
4181 if (WithProto
->getNumParams() != 0) {
4182 if (WithoutProto
->getBuiltinID() == 0 && !WithoutProto
->isImplicit()) {
4183 // The one without the prototype will be changing behavior in C23, so
4184 // warn about that one so long as it's a user-visible declaration.
4185 bool IsWithoutProtoADef
= false, IsWithProtoADef
= false;
4186 if (WithoutProto
== New
)
4187 IsWithoutProtoADef
= NewDeclIsDefn
;
4189 IsWithProtoADef
= NewDeclIsDefn
;
4190 Diag(WithoutProto
->getLocation(),
4191 diag::warn_non_prototype_changes_behavior
)
4192 << IsWithoutProtoADef
<< (WithoutProto
->getNumParams() ? 0 : 1)
4193 << (WithoutProto
== Old
) << IsWithProtoADef
;
4195 // The reason the one without the prototype will be changing behavior
4196 // is because of the one with the prototype, so note that so long as
4197 // it's a user-visible declaration. There is one exception to this:
4198 // when the new declaration is a definition without a prototype, the
4199 // old declaration with a prototype is not the cause of the issue,
4200 // and that does not need to be noted because the one with a
4201 // prototype will not change behavior in C23.
4202 if (WithProto
->getBuiltinID() == 0 && !WithProto
->isImplicit() &&
4203 !IsWithoutProtoADef
)
4204 Diag(WithProto
->getLocation(), diag::note_conflicting_prototype
);
4209 if (Context
.typesAreCompatible(OldQType
, NewQType
)) {
4210 const FunctionType
*OldFuncType
= OldQType
->getAs
<FunctionType
>();
4211 const FunctionType
*NewFuncType
= NewQType
->getAs
<FunctionType
>();
4212 const FunctionProtoType
*OldProto
= nullptr;
4213 if (MergeTypeWithOld
&& isa
<FunctionNoProtoType
>(NewFuncType
) &&
4214 (OldProto
= dyn_cast
<FunctionProtoType
>(OldFuncType
))) {
4215 // The old declaration provided a function prototype, but the
4216 // new declaration does not. Merge in the prototype.
4217 assert(!OldProto
->hasExceptionSpec() && "Exception spec in C");
4218 NewQType
= Context
.getFunctionType(NewFuncType
->getReturnType(),
4219 OldProto
->getParamTypes(),
4220 OldProto
->getExtProtoInfo());
4221 New
->setType(NewQType
);
4222 New
->setHasInheritedPrototype();
4224 // Synthesize parameters with the same types.
4225 SmallVector
<ParmVarDecl
*, 16> Params
;
4226 for (const auto &ParamType
: OldProto
->param_types()) {
4227 ParmVarDecl
*Param
= ParmVarDecl::Create(
4228 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
4229 ParamType
, /*TInfo=*/nullptr, SC_None
, nullptr);
4230 Param
->setScopeInfo(0, Params
.size());
4231 Param
->setImplicit();
4232 Params
.push_back(Param
);
4235 New
->setParams(Params
);
4238 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4242 // Check if the function types are compatible when pointer size address
4243 // spaces are ignored.
4244 if (Context
.hasSameFunctionTypeIgnoringPtrSizes(OldQType
, NewQType
))
4247 // GNU C permits a K&R definition to follow a prototype declaration
4248 // if the declared types of the parameters in the K&R definition
4249 // match the types in the prototype declaration, even when the
4250 // promoted types of the parameters from the K&R definition differ
4251 // from the types in the prototype. GCC then keeps the types from
4254 // If a variadic prototype is followed by a non-variadic K&R definition,
4255 // the K&R definition becomes variadic. This is sort of an edge case, but
4256 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4258 if (!getLangOpts().CPlusPlus
&&
4259 Old
->hasPrototype() && !New
->hasPrototype() &&
4260 New
->getType()->getAs
<FunctionProtoType
>() &&
4261 Old
->getNumParams() == New
->getNumParams()) {
4262 SmallVector
<QualType
, 16> ArgTypes
;
4263 SmallVector
<GNUCompatibleParamWarning
, 16> Warnings
;
4264 const FunctionProtoType
*OldProto
4265 = Old
->getType()->getAs
<FunctionProtoType
>();
4266 const FunctionProtoType
*NewProto
4267 = New
->getType()->getAs
<FunctionProtoType
>();
4269 // Determine whether this is the GNU C extension.
4270 QualType MergedReturn
= Context
.mergeTypes(OldProto
->getReturnType(),
4271 NewProto
->getReturnType());
4272 bool LooseCompatible
= !MergedReturn
.isNull();
4273 for (unsigned Idx
= 0, End
= Old
->getNumParams();
4274 LooseCompatible
&& Idx
!= End
; ++Idx
) {
4275 ParmVarDecl
*OldParm
= Old
->getParamDecl(Idx
);
4276 ParmVarDecl
*NewParm
= New
->getParamDecl(Idx
);
4277 if (Context
.typesAreCompatible(OldParm
->getType(),
4278 NewProto
->getParamType(Idx
))) {
4279 ArgTypes
.push_back(NewParm
->getType());
4280 } else if (Context
.typesAreCompatible(OldParm
->getType(),
4282 /*CompareUnqualified=*/true)) {
4283 GNUCompatibleParamWarning Warn
= { OldParm
, NewParm
,
4284 NewProto
->getParamType(Idx
) };
4285 Warnings
.push_back(Warn
);
4286 ArgTypes
.push_back(NewParm
->getType());
4288 LooseCompatible
= false;
4291 if (LooseCompatible
) {
4292 for (unsigned Warn
= 0; Warn
< Warnings
.size(); ++Warn
) {
4293 Diag(Warnings
[Warn
].NewParm
->getLocation(),
4294 diag::ext_param_promoted_not_compatible_with_prototype
)
4295 << Warnings
[Warn
].PromotedType
4296 << Warnings
[Warn
].OldParm
->getType();
4297 if (Warnings
[Warn
].OldParm
->getLocation().isValid())
4298 Diag(Warnings
[Warn
].OldParm
->getLocation(),
4299 diag::note_previous_declaration
);
4302 if (MergeTypeWithOld
)
4303 New
->setType(Context
.getFunctionType(MergedReturn
, ArgTypes
,
4304 OldProto
->getExtProtoInfo()));
4305 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4308 // Fall through to diagnose conflicting types.
4311 // A function that has already been declared has been redeclared or
4312 // defined with a different type; show an appropriate diagnostic.
4314 // If the previous declaration was an implicitly-generated builtin
4315 // declaration, then at the very least we should use a specialized note.
4317 if (Old
->isImplicit() && (BuiltinID
= Old
->getBuiltinID())) {
4318 // If it's actually a library-defined builtin function like 'malloc'
4319 // or 'printf', just warn about the incompatible redeclaration.
4320 if (Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
)) {
4321 Diag(New
->getLocation(), diag::warn_redecl_library_builtin
) << New
;
4322 Diag(OldLocation
, diag::note_previous_builtin_declaration
)
4323 << Old
<< Old
->getType();
4327 PrevDiag
= diag::note_previous_builtin_declaration
;
4330 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
->getDeclName();
4331 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4335 /// Completes the merge of two function declarations that are
4336 /// known to be compatible.
4338 /// This routine handles the merging of attributes and other
4339 /// properties of function declarations from the old declaration to
4340 /// the new declaration, once we know that New is in fact a
4341 /// redeclaration of Old.
4344 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl
*New
, FunctionDecl
*Old
,
4345 Scope
*S
, bool MergeTypeWithOld
) {
4346 // Merge the attributes
4347 mergeDeclAttributes(New
, Old
);
4349 // Merge "pure" flag.
4353 // Merge "used" flag.
4354 if (Old
->getMostRecentDecl()->isUsed(false))
4357 // Merge attributes from the parameters. These can mismatch with K&R
4359 if (New
->getNumParams() == Old
->getNumParams())
4360 for (unsigned i
= 0, e
= New
->getNumParams(); i
!= e
; ++i
) {
4361 ParmVarDecl
*NewParam
= New
->getParamDecl(i
);
4362 ParmVarDecl
*OldParam
= Old
->getParamDecl(i
);
4363 mergeParamDeclAttributes(NewParam
, OldParam
, *this);
4364 mergeParamDeclTypes(NewParam
, OldParam
, *this);
4367 if (getLangOpts().CPlusPlus
)
4368 return MergeCXXFunctionDecl(New
, Old
, S
);
4370 // Merge the function types so the we get the composite types for the return
4371 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4373 QualType Merged
= Context
.mergeTypes(Old
->getType(), New
->getType());
4374 if (!Merged
.isNull() && MergeTypeWithOld
)
4375 New
->setType(Merged
);
4380 void Sema::mergeObjCMethodDecls(ObjCMethodDecl
*newMethod
,
4381 ObjCMethodDecl
*oldMethod
) {
4382 // Merge the attributes, including deprecated/unavailable
4383 AvailabilityMergeKind MergeKind
=
4384 isa
<ObjCProtocolDecl
>(oldMethod
->getDeclContext())
4385 ? (oldMethod
->isOptional() ? AMK_OptionalProtocolImplementation
4386 : AMK_ProtocolImplementation
)
4387 : isa
<ObjCImplDecl
>(newMethod
->getDeclContext()) ? AMK_Redeclaration
4390 mergeDeclAttributes(newMethod
, oldMethod
, MergeKind
);
4392 // Merge attributes from the parameters.
4393 ObjCMethodDecl::param_const_iterator oi
= oldMethod
->param_begin(),
4394 oe
= oldMethod
->param_end();
4395 for (ObjCMethodDecl::param_iterator
4396 ni
= newMethod
->param_begin(), ne
= newMethod
->param_end();
4397 ni
!= ne
&& oi
!= oe
; ++ni
, ++oi
)
4398 mergeParamDeclAttributes(*ni
, *oi
, *this);
4400 CheckObjCMethodOverride(newMethod
, oldMethod
);
4403 static void diagnoseVarDeclTypeMismatch(Sema
&S
, VarDecl
*New
, VarDecl
* Old
) {
4404 assert(!S
.Context
.hasSameType(New
->getType(), Old
->getType()));
4406 S
.Diag(New
->getLocation(), New
->isThisDeclarationADefinition()
4407 ? diag::err_redefinition_different_type
4408 : diag::err_redeclaration_different_type
)
4409 << New
->getDeclName() << New
->getType() << Old
->getType();
4411 diag::kind PrevDiag
;
4412 SourceLocation OldLocation
;
4413 std::tie(PrevDiag
, OldLocation
)
4414 = getNoteDiagForInvalidRedeclaration(Old
, New
);
4415 S
.Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4416 New
->setInvalidDecl();
4419 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4420 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4421 /// emitting diagnostics as appropriate.
4423 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4424 /// to here in AddInitializerToDecl. We can't check them before the initializer
4426 void Sema::MergeVarDeclTypes(VarDecl
*New
, VarDecl
*Old
,
4427 bool MergeTypeWithOld
) {
4428 if (New
->isInvalidDecl() || Old
->isInvalidDecl() || New
->getType()->containsErrors() || Old
->getType()->containsErrors())
4432 if (getLangOpts().CPlusPlus
) {
4433 if (New
->getType()->isUndeducedType()) {
4434 // We don't know what the new type is until the initializer is attached.
4436 } else if (Context
.hasSameType(New
->getType(), Old
->getType())) {
4437 // These could still be something that needs exception specs checked.
4438 return MergeVarDeclExceptionSpecs(New
, Old
);
4440 // C++ [basic.link]p10:
4441 // [...] the types specified by all declarations referring to a given
4442 // object or function shall be identical, except that declarations for an
4443 // array object can specify array types that differ by the presence or
4444 // absence of a major array bound (8.3.4).
4445 else if (Old
->getType()->isArrayType() && New
->getType()->isArrayType()) {
4446 const ArrayType
*OldArray
= Context
.getAsArrayType(Old
->getType());
4447 const ArrayType
*NewArray
= Context
.getAsArrayType(New
->getType());
4449 // We are merging a variable declaration New into Old. If it has an array
4450 // bound, and that bound differs from Old's bound, we should diagnose the
4452 if (!NewArray
->isIncompleteArrayType() && !NewArray
->isDependentType()) {
4453 for (VarDecl
*PrevVD
= Old
->getMostRecentDecl(); PrevVD
;
4454 PrevVD
= PrevVD
->getPreviousDecl()) {
4455 QualType PrevVDTy
= PrevVD
->getType();
4456 if (PrevVDTy
->isIncompleteArrayType() || PrevVDTy
->isDependentType())
4459 if (!Context
.hasSameType(New
->getType(), PrevVDTy
))
4460 return diagnoseVarDeclTypeMismatch(*this, New
, PrevVD
);
4464 if (OldArray
->isIncompleteArrayType() && NewArray
->isArrayType()) {
4465 if (Context
.hasSameType(OldArray
->getElementType(),
4466 NewArray
->getElementType()))
4467 MergedT
= New
->getType();
4469 // FIXME: Check visibility. New is hidden but has a complete type. If New
4470 // has no array bound, it should not inherit one from Old, if Old is not
4472 else if (OldArray
->isArrayType() && NewArray
->isIncompleteArrayType()) {
4473 if (Context
.hasSameType(OldArray
->getElementType(),
4474 NewArray
->getElementType()))
4475 MergedT
= Old
->getType();
4478 else if (New
->getType()->isObjCObjectPointerType() &&
4479 Old
->getType()->isObjCObjectPointerType()) {
4480 MergedT
= Context
.mergeObjCGCQualifiers(New
->getType(),
4485 // All declarations that refer to the same object or function shall have
4487 MergedT
= Context
.mergeTypes(New
->getType(), Old
->getType());
4489 if (MergedT
.isNull()) {
4490 // It's OK if we couldn't merge types if either type is dependent, for a
4491 // block-scope variable. In other cases (static data members of class
4492 // templates, variable templates, ...), we require the types to be
4494 // FIXME: The C++ standard doesn't say anything about this.
4495 if ((New
->getType()->isDependentType() ||
4496 Old
->getType()->isDependentType()) && New
->isLocalVarDecl()) {
4497 // If the old type was dependent, we can't merge with it, so the new type
4498 // becomes dependent for now. We'll reproduce the original type when we
4499 // instantiate the TypeSourceInfo for the variable.
4500 if (!New
->getType()->isDependentType() && MergeTypeWithOld
)
4501 New
->setType(Context
.DependentTy
);
4504 return diagnoseVarDeclTypeMismatch(*this, New
, Old
);
4507 // Don't actually update the type on the new declaration if the old
4508 // declaration was an extern declaration in a different scope.
4509 if (MergeTypeWithOld
)
4510 New
->setType(MergedT
);
4513 static bool mergeTypeWithPrevious(Sema
&S
, VarDecl
*NewVD
, VarDecl
*OldVD
,
4514 LookupResult
&Previous
) {
4516 // For an identifier with internal or external linkage declared
4517 // in a scope in which a prior declaration of that identifier is
4518 // visible, if the prior declaration specifies internal or
4519 // external linkage, the type of the identifier at the later
4520 // declaration becomes the composite type.
4522 // If the variable isn't visible, we do not merge with its type.
4523 if (Previous
.isShadowed())
4526 if (S
.getLangOpts().CPlusPlus
) {
4527 // C++11 [dcl.array]p3:
4528 // If there is a preceding declaration of the entity in the same
4529 // scope in which the bound was specified, an omitted array bound
4530 // is taken to be the same as in that earlier declaration.
4531 return NewVD
->isPreviousDeclInSameBlockScope() ||
4532 (!OldVD
->getLexicalDeclContext()->isFunctionOrMethod() &&
4533 !NewVD
->getLexicalDeclContext()->isFunctionOrMethod());
4535 // If the old declaration was function-local, don't merge with its
4536 // type unless we're in the same function.
4537 return !OldVD
->getLexicalDeclContext()->isFunctionOrMethod() ||
4538 OldVD
->getLexicalDeclContext() == NewVD
->getLexicalDeclContext();
4542 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4543 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4544 /// situation, merging decls or emitting diagnostics as appropriate.
4546 /// Tentative definition rules (C99 6.9.2p2) are checked by
4547 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4548 /// definitions here, since the initializer hasn't been attached.
4550 void Sema::MergeVarDecl(VarDecl
*New
, LookupResult
&Previous
) {
4551 // If the new decl is already invalid, don't do any other checking.
4552 if (New
->isInvalidDecl())
4555 if (!shouldLinkPossiblyHiddenDecl(Previous
, New
))
4558 VarTemplateDecl
*NewTemplate
= New
->getDescribedVarTemplate();
4560 // Verify the old decl was also a variable or variable template.
4561 VarDecl
*Old
= nullptr;
4562 VarTemplateDecl
*OldTemplate
= nullptr;
4563 if (Previous
.isSingleResult()) {
4565 OldTemplate
= dyn_cast
<VarTemplateDecl
>(Previous
.getFoundDecl());
4566 Old
= OldTemplate
? OldTemplate
->getTemplatedDecl() : nullptr;
4569 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4570 if (checkUsingShadowRedecl
<VarTemplateDecl
>(*this, Shadow
, NewTemplate
))
4571 return New
->setInvalidDecl();
4573 Old
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl());
4576 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4577 if (checkUsingShadowRedecl
<VarDecl
>(*this, Shadow
, New
))
4578 return New
->setInvalidDecl();
4582 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
4583 << New
->getDeclName();
4584 notePreviousDefinition(Previous
.getRepresentativeDecl(),
4585 New
->getLocation());
4586 return New
->setInvalidDecl();
4589 // If the old declaration was found in an inline namespace and the new
4590 // declaration was qualified, update the DeclContext to match.
4591 adjustDeclContextForDeclaratorDecl(New
, Old
);
4593 // Ensure the template parameters are compatible.
4595 !TemplateParameterListsAreEqual(NewTemplate
->getTemplateParameters(),
4596 OldTemplate
->getTemplateParameters(),
4597 /*Complain=*/true, TPL_TemplateMatch
))
4598 return New
->setInvalidDecl();
4600 // C++ [class.mem]p1:
4601 // A member shall not be declared twice in the member-specification [...]
4603 // Here, we need only consider static data members.
4604 if (Old
->isStaticDataMember() && !New
->isOutOfLine()) {
4605 Diag(New
->getLocation(), diag::err_duplicate_member
)
4606 << New
->getIdentifier();
4607 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4608 New
->setInvalidDecl();
4611 mergeDeclAttributes(New
, Old
);
4612 // Warn if an already-declared variable is made a weak_import in a subsequent
4614 if (New
->hasAttr
<WeakImportAttr
>() &&
4615 Old
->getStorageClass() == SC_None
&&
4616 !Old
->hasAttr
<WeakImportAttr
>()) {
4617 Diag(New
->getLocation(), diag::warn_weak_import
) << New
->getDeclName();
4618 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4619 // Remove weak_import attribute on new declaration.
4620 New
->dropAttr
<WeakImportAttr
>();
4623 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
4624 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
4625 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
4627 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4628 New
->dropAttr
<InternalLinkageAttr
>();
4632 VarDecl
*MostRecent
= Old
->getMostRecentDecl();
4633 if (MostRecent
!= Old
) {
4634 MergeVarDeclTypes(New
, MostRecent
,
4635 mergeTypeWithPrevious(*this, New
, MostRecent
, Previous
));
4636 if (New
->isInvalidDecl())
4640 MergeVarDeclTypes(New
, Old
, mergeTypeWithPrevious(*this, New
, Old
, Previous
));
4641 if (New
->isInvalidDecl())
4644 diag::kind PrevDiag
;
4645 SourceLocation OldLocation
;
4646 std::tie(PrevDiag
, OldLocation
) =
4647 getNoteDiagForInvalidRedeclaration(Old
, New
);
4649 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4650 if (New
->getStorageClass() == SC_Static
&&
4651 !New
->isStaticDataMember() &&
4652 Old
->hasExternalFormalLinkage()) {
4653 if (getLangOpts().MicrosoftExt
) {
4654 Diag(New
->getLocation(), diag::ext_static_non_static
)
4655 << New
->getDeclName();
4656 Diag(OldLocation
, PrevDiag
);
4658 Diag(New
->getLocation(), diag::err_static_non_static
)
4659 << New
->getDeclName();
4660 Diag(OldLocation
, PrevDiag
);
4661 return New
->setInvalidDecl();
4665 // For an identifier declared with the storage-class specifier
4666 // extern in a scope in which a prior declaration of that
4667 // identifier is visible,23) if the prior declaration specifies
4668 // internal or external linkage, the linkage of the identifier at
4669 // the later declaration is the same as the linkage specified at
4670 // the prior declaration. If no prior declaration is visible, or
4671 // if the prior declaration specifies no linkage, then the
4672 // identifier has external linkage.
4673 if (New
->hasExternalStorage() && Old
->hasLinkage())
4675 else if (New
->getCanonicalDecl()->getStorageClass() != SC_Static
&&
4676 !New
->isStaticDataMember() &&
4677 Old
->getCanonicalDecl()->getStorageClass() == SC_Static
) {
4678 Diag(New
->getLocation(), diag::err_non_static_static
) << New
->getDeclName();
4679 Diag(OldLocation
, PrevDiag
);
4680 return New
->setInvalidDecl();
4683 // Check if extern is followed by non-extern and vice-versa.
4684 if (New
->hasExternalStorage() &&
4685 !Old
->hasLinkage() && Old
->isLocalVarDeclOrParm()) {
4686 Diag(New
->getLocation(), diag::err_extern_non_extern
) << New
->getDeclName();
4687 Diag(OldLocation
, PrevDiag
);
4688 return New
->setInvalidDecl();
4690 if (Old
->hasLinkage() && New
->isLocalVarDeclOrParm() &&
4691 !New
->hasExternalStorage()) {
4692 Diag(New
->getLocation(), diag::err_non_extern_extern
) << New
->getDeclName();
4693 Diag(OldLocation
, PrevDiag
);
4694 return New
->setInvalidDecl();
4697 if (CheckRedeclarationInModule(New
, Old
))
4700 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4702 // FIXME: The test for external storage here seems wrong? We still
4703 // need to check for mismatches.
4704 if (!New
->hasExternalStorage() && !New
->isFileVarDecl() &&
4705 // Don't complain about out-of-line definitions of static members.
4706 !(Old
->getLexicalDeclContext()->isRecord() &&
4707 !New
->getLexicalDeclContext()->isRecord())) {
4708 Diag(New
->getLocation(), diag::err_redefinition
) << New
->getDeclName();
4709 Diag(OldLocation
, PrevDiag
);
4710 return New
->setInvalidDecl();
4713 if (New
->isInline() && !Old
->getMostRecentDecl()->isInline()) {
4714 if (VarDecl
*Def
= Old
->getDefinition()) {
4715 // C++1z [dcl.fcn.spec]p4:
4716 // If the definition of a variable appears in a translation unit before
4717 // its first declaration as inline, the program is ill-formed.
4718 Diag(New
->getLocation(), diag::err_inline_decl_follows_def
) << New
;
4719 Diag(Def
->getLocation(), diag::note_previous_definition
);
4723 // If this redeclaration makes the variable inline, we may need to add it to
4724 // UndefinedButUsed.
4725 if (!Old
->isInline() && New
->isInline() && Old
->isUsed(false) &&
4726 !Old
->getDefinition() && !New
->isThisDeclarationADefinition())
4727 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
4730 if (New
->getTLSKind() != Old
->getTLSKind()) {
4731 if (!Old
->getTLSKind()) {
4732 Diag(New
->getLocation(), diag::err_thread_non_thread
) << New
->getDeclName();
4733 Diag(OldLocation
, PrevDiag
);
4734 } else if (!New
->getTLSKind()) {
4735 Diag(New
->getLocation(), diag::err_non_thread_thread
) << New
->getDeclName();
4736 Diag(OldLocation
, PrevDiag
);
4738 // Do not allow redeclaration to change the variable between requiring
4739 // static and dynamic initialization.
4740 // FIXME: GCC allows this, but uses the TLS keyword on the first
4741 // declaration to determine the kind. Do we need to be compatible here?
4742 Diag(New
->getLocation(), diag::err_thread_thread_different_kind
)
4743 << New
->getDeclName() << (New
->getTLSKind() == VarDecl::TLS_Dynamic
);
4744 Diag(OldLocation
, PrevDiag
);
4748 // C++ doesn't have tentative definitions, so go right ahead and check here.
4749 if (getLangOpts().CPlusPlus
) {
4750 if (Old
->isStaticDataMember() && Old
->getCanonicalDecl()->isInline() &&
4751 Old
->getCanonicalDecl()->isConstexpr()) {
4752 // This definition won't be a definition any more once it's been merged.
4753 Diag(New
->getLocation(),
4754 diag::warn_deprecated_redundant_constexpr_static_def
);
4755 } else if (New
->isThisDeclarationADefinition() == VarDecl::Definition
) {
4756 VarDecl
*Def
= Old
->getDefinition();
4757 if (Def
&& checkVarDeclRedefinition(Def
, New
))
4762 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
4763 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4764 Diag(OldLocation
, PrevDiag
);
4765 New
->setInvalidDecl();
4769 // Merge "used" flag.
4770 if (Old
->getMostRecentDecl()->isUsed(false))
4773 // Keep a chain of previous declarations.
4774 New
->setPreviousDecl(Old
);
4776 NewTemplate
->setPreviousDecl(OldTemplate
);
4778 // Inherit access appropriately.
4779 New
->setAccess(Old
->getAccess());
4781 NewTemplate
->setAccess(New
->getAccess());
4783 if (Old
->isInline())
4784 New
->setImplicitlyInline();
4787 void Sema::notePreviousDefinition(const NamedDecl
*Old
, SourceLocation New
) {
4788 SourceManager
&SrcMgr
= getSourceManager();
4789 auto FNewDecLoc
= SrcMgr
.getDecomposedLoc(New
);
4790 auto FOldDecLoc
= SrcMgr
.getDecomposedLoc(Old
->getLocation());
4791 auto *FNew
= SrcMgr
.getFileEntryForID(FNewDecLoc
.first
);
4792 auto FOld
= SrcMgr
.getFileEntryRefForID(FOldDecLoc
.first
);
4793 auto &HSI
= PP
.getHeaderSearchInfo();
4794 StringRef HdrFilename
=
4795 SrcMgr
.getFilename(SrcMgr
.getSpellingLoc(Old
->getLocation()));
4797 auto noteFromModuleOrInclude
= [&](Module
*Mod
,
4798 SourceLocation IncLoc
) -> bool {
4799 // Redefinition errors with modules are common with non modular mapped
4800 // headers, example: a non-modular header H in module A that also gets
4801 // included directly in a TU. Pointing twice to the same header/definition
4802 // is confusing, try to get better diagnostics when modules is on.
4803 if (IncLoc
.isValid()) {
4805 Diag(IncLoc
, diag::note_redefinition_modules_same_file
)
4806 << HdrFilename
.str() << Mod
->getFullModuleName();
4807 if (!Mod
->DefinitionLoc
.isInvalid())
4808 Diag(Mod
->DefinitionLoc
, diag::note_defined_here
)
4809 << Mod
->getFullModuleName();
4811 Diag(IncLoc
, diag::note_redefinition_include_same_file
)
4812 << HdrFilename
.str();
4820 // Is it the same file and same offset? Provide more information on why
4821 // this leads to a redefinition error.
4822 if (FNew
== FOld
&& FNewDecLoc
.second
== FOldDecLoc
.second
) {
4823 SourceLocation OldIncLoc
= SrcMgr
.getIncludeLoc(FOldDecLoc
.first
);
4824 SourceLocation NewIncLoc
= SrcMgr
.getIncludeLoc(FNewDecLoc
.first
);
4826 noteFromModuleOrInclude(Old
->getOwningModule(), OldIncLoc
);
4827 EmittedDiag
|= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc
);
4829 // If the header has no guards, emit a note suggesting one.
4830 if (FOld
&& !HSI
.isFileMultipleIncludeGuarded(*FOld
))
4831 Diag(Old
->getLocation(), diag::note_use_ifdef_guards
);
4837 // Redefinition coming from different files or couldn't do better above.
4838 if (Old
->getLocation().isValid())
4839 Diag(Old
->getLocation(), diag::note_previous_definition
);
4842 /// We've just determined that \p Old and \p New both appear to be definitions
4843 /// of the same variable. Either diagnose or fix the problem.
4844 bool Sema::checkVarDeclRedefinition(VarDecl
*Old
, VarDecl
*New
) {
4845 if (!hasVisibleDefinition(Old
) &&
4846 (New
->getFormalLinkage() == InternalLinkage
||
4848 isa
<VarTemplateSpecializationDecl
>(New
) ||
4849 New
->getDescribedVarTemplate() ||
4850 New
->getNumTemplateParameterLists() ||
4851 New
->getDeclContext()->isDependentContext())) {
4852 // The previous definition is hidden, and multiple definitions are
4853 // permitted (in separate TUs). Demote this to a declaration.
4854 New
->demoteThisDefinitionToDeclaration();
4856 // Make the canonical definition visible.
4857 if (auto *OldTD
= Old
->getDescribedVarTemplate())
4858 makeMergedDefinitionVisible(OldTD
);
4859 makeMergedDefinitionVisible(Old
);
4862 Diag(New
->getLocation(), diag::err_redefinition
) << New
;
4863 notePreviousDefinition(Old
, New
->getLocation());
4864 New
->setInvalidDecl();
4869 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4870 /// no declarator (e.g. "struct foo;") is parsed.
4871 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
4873 const ParsedAttributesView
&DeclAttrs
,
4874 RecordDecl
*&AnonRecord
) {
4875 return ParsedFreeStandingDeclSpec(
4876 S
, AS
, DS
, DeclAttrs
, MultiTemplateParamsArg(), false, AnonRecord
);
4879 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4880 // disambiguate entities defined in different scopes.
4881 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4883 // We will pick our mangling number depending on which version of MSVC is being
4885 static unsigned getMSManglingNumber(const LangOptions
&LO
, Scope
*S
) {
4886 return LO
.isCompatibleWithMSVC(LangOptions::MSVC2015
)
4887 ? S
->getMSCurManglingNumber()
4888 : S
->getMSLastManglingNumber();
4891 void Sema::handleTagNumbering(const TagDecl
*Tag
, Scope
*TagScope
) {
4892 if (!Context
.getLangOpts().CPlusPlus
)
4895 if (isa
<CXXRecordDecl
>(Tag
->getParent())) {
4896 // If this tag is the direct child of a class, number it if
4898 if (!Tag
->getName().empty() || Tag
->getTypedefNameForAnonDecl())
4900 MangleNumberingContext
&MCtx
=
4901 Context
.getManglingNumberContext(Tag
->getParent());
4902 Context
.setManglingNumber(
4903 Tag
, MCtx
.getManglingNumber(
4904 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4908 // If this tag isn't a direct child of a class, number it if it is local.
4909 MangleNumberingContext
*MCtx
;
4910 Decl
*ManglingContextDecl
;
4911 std::tie(MCtx
, ManglingContextDecl
) =
4912 getCurrentMangleNumberContext(Tag
->getDeclContext());
4914 Context
.setManglingNumber(
4915 Tag
, MCtx
->getManglingNumber(
4916 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4921 struct NonCLikeKind
{
4933 explicit operator bool() { return Kind
!= None
; }
4937 /// Determine whether a class is C-like, according to the rules of C++
4938 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4939 static NonCLikeKind
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl
*RD
) {
4940 if (RD
->isInvalidDecl())
4941 return {NonCLikeKind::Invalid
, {}};
4943 // C++ [dcl.typedef]p9: [P1766R1]
4944 // An unnamed class with a typedef name for linkage purposes shall not
4946 // -- have any base classes
4947 if (RD
->getNumBases())
4948 return {NonCLikeKind::BaseClass
,
4949 SourceRange(RD
->bases_begin()->getBeginLoc(),
4950 RD
->bases_end()[-1].getEndLoc())};
4951 bool Invalid
= false;
4952 for (Decl
*D
: RD
->decls()) {
4953 // Don't complain about things we already diagnosed.
4954 if (D
->isInvalidDecl()) {
4959 // -- have any [...] default member initializers
4960 if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
4961 if (FD
->hasInClassInitializer()) {
4962 auto *Init
= FD
->getInClassInitializer();
4963 return {NonCLikeKind::DefaultMemberInit
,
4964 Init
? Init
->getSourceRange() : D
->getSourceRange()};
4969 // FIXME: We don't allow friend declarations. This violates the wording of
4970 // P1766, but not the intent.
4971 if (isa
<FriendDecl
>(D
))
4972 return {NonCLikeKind::Friend
, D
->getSourceRange()};
4974 // -- declare any members other than non-static data members, member
4975 // enumerations, or member classes,
4976 if (isa
<StaticAssertDecl
>(D
) || isa
<IndirectFieldDecl
>(D
) ||
4979 auto *MemberRD
= dyn_cast
<CXXRecordDecl
>(D
);
4981 if (D
->isImplicit())
4983 return {NonCLikeKind::OtherMember
, D
->getSourceRange()};
4986 // -- contain a lambda-expression,
4987 if (MemberRD
->isLambda())
4988 return {NonCLikeKind::Lambda
, MemberRD
->getSourceRange()};
4990 // and all member classes shall also satisfy these requirements
4992 if (MemberRD
->isThisDeclarationADefinition()) {
4993 if (auto Kind
= getNonCLikeKindForAnonymousStruct(MemberRD
))
4998 return {Invalid
? NonCLikeKind::Invalid
: NonCLikeKind::None
, {}};
5001 void Sema::setTagNameForLinkagePurposes(TagDecl
*TagFromDeclSpec
,
5002 TypedefNameDecl
*NewTD
) {
5003 if (TagFromDeclSpec
->isInvalidDecl())
5006 // Do nothing if the tag already has a name for linkage purposes.
5007 if (TagFromDeclSpec
->hasNameForLinkage())
5010 // A well-formed anonymous tag must always be a TUK_Definition.
5011 assert(TagFromDeclSpec
->isThisDeclarationADefinition());
5013 // The type must match the tag exactly; no qualifiers allowed.
5014 if (!Context
.hasSameType(NewTD
->getUnderlyingType(),
5015 Context
.getTagDeclType(TagFromDeclSpec
))) {
5016 if (getLangOpts().CPlusPlus
)
5017 Context
.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec
, NewTD
);
5021 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5022 // An unnamed class with a typedef name for linkage purposes shall [be
5025 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5026 // shouldn't happen, but there are constructs that the language rule doesn't
5027 // disallow for which we can't reasonably avoid computing linkage early.
5028 const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(TagFromDeclSpec
);
5029 NonCLikeKind NonCLike
= RD
? getNonCLikeKindForAnonymousStruct(RD
)
5031 bool ChangesLinkage
= TagFromDeclSpec
->hasLinkageBeenComputed();
5032 if (NonCLike
|| ChangesLinkage
) {
5033 if (NonCLike
.Kind
== NonCLikeKind::Invalid
)
5036 unsigned DiagID
= diag::ext_non_c_like_anon_struct_in_typedef
;
5037 if (ChangesLinkage
) {
5038 // If the linkage changes, we can't accept this as an extension.
5039 if (NonCLike
.Kind
== NonCLikeKind::None
)
5040 DiagID
= diag::err_typedef_changes_linkage
;
5042 DiagID
= diag::err_non_c_like_anon_struct_in_typedef
;
5045 SourceLocation FixitLoc
=
5046 getLocForEndOfToken(TagFromDeclSpec
->getInnerLocStart());
5047 llvm::SmallString
<40> TextToInsert
;
5048 TextToInsert
+= ' ';
5049 TextToInsert
+= NewTD
->getIdentifier()->getName();
5051 Diag(FixitLoc
, DiagID
)
5052 << isa
<TypeAliasDecl
>(NewTD
)
5053 << FixItHint::CreateInsertion(FixitLoc
, TextToInsert
);
5054 if (NonCLike
.Kind
!= NonCLikeKind::None
) {
5055 Diag(NonCLike
.Range
.getBegin(), diag::note_non_c_like_anon_struct
)
5056 << NonCLike
.Kind
- 1 << NonCLike
.Range
;
5058 Diag(NewTD
->getLocation(), diag::note_typedef_for_linkage_here
)
5059 << NewTD
<< isa
<TypeAliasDecl
>(NewTD
);
5065 // Otherwise, set this as the anon-decl typedef for the tag.
5066 TagFromDeclSpec
->setTypedefNameForAnonDecl(NewTD
);
5069 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec
&DS
) {
5070 DeclSpec::TST T
= DS
.getTypeSpecType();
5072 case DeclSpec::TST_class
:
5074 case DeclSpec::TST_struct
:
5076 case DeclSpec::TST_interface
:
5078 case DeclSpec::TST_union
:
5080 case DeclSpec::TST_enum
:
5081 if (const auto *ED
= dyn_cast
<EnumDecl
>(DS
.getRepAsDecl())) {
5082 if (ED
->isScopedUsingClassTag())
5089 llvm_unreachable("unexpected type specifier");
5092 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5093 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5094 /// parameters to cope with template friend declarations.
5095 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
5097 const ParsedAttributesView
&DeclAttrs
,
5098 MultiTemplateParamsArg TemplateParams
,
5099 bool IsExplicitInstantiation
,
5100 RecordDecl
*&AnonRecord
) {
5101 Decl
*TagD
= nullptr;
5102 TagDecl
*Tag
= nullptr;
5103 if (DS
.getTypeSpecType() == DeclSpec::TST_class
||
5104 DS
.getTypeSpecType() == DeclSpec::TST_struct
||
5105 DS
.getTypeSpecType() == DeclSpec::TST_interface
||
5106 DS
.getTypeSpecType() == DeclSpec::TST_union
||
5107 DS
.getTypeSpecType() == DeclSpec::TST_enum
) {
5108 TagD
= DS
.getRepAsDecl();
5110 if (!TagD
) // We probably had an error
5113 // Note that the above type specs guarantee that the
5114 // type rep is a Decl, whereas in many of the others
5116 if (isa
<TagDecl
>(TagD
))
5117 Tag
= cast
<TagDecl
>(TagD
);
5118 else if (ClassTemplateDecl
*CTD
= dyn_cast
<ClassTemplateDecl
>(TagD
))
5119 Tag
= CTD
->getTemplatedDecl();
5123 handleTagNumbering(Tag
, S
);
5124 Tag
->setFreeStanding();
5125 if (Tag
->isInvalidDecl())
5129 if (unsigned TypeQuals
= DS
.getTypeQualifiers()) {
5130 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5131 // or incomplete types shall not be restrict-qualified."
5132 if (TypeQuals
& DeclSpec::TQ_restrict
)
5133 Diag(DS
.getRestrictSpecLoc(),
5134 diag::err_typecheck_invalid_restrict_not_pointer_noarg
)
5135 << DS
.getSourceRange();
5138 if (DS
.isInlineSpecified())
5139 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
5140 << getLangOpts().CPlusPlus17
;
5142 if (DS
.hasConstexprSpecifier()) {
5143 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5144 // and definitions of functions and variables.
5145 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5146 // the declaration of a function or function template
5148 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_tag
)
5149 << GetDiagnosticTypeSpecifierID(DS
)
5150 << static_cast<int>(DS
.getConstexprSpecifier());
5152 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind
)
5153 << static_cast<int>(DS
.getConstexprSpecifier());
5154 // Don't emit warnings after this error.
5158 DiagnoseFunctionSpecifiers(DS
);
5160 if (DS
.isFriendSpecified()) {
5161 // If we're dealing with a decl but not a TagDecl, assume that
5162 // whatever routines created it handled the friendship aspect.
5165 return ActOnFriendTypeDecl(S
, DS
, TemplateParams
);
5168 const CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
5169 bool IsExplicitSpecialization
=
5170 !TemplateParams
.empty() && TemplateParams
.back()->size() == 0;
5171 if (Tag
&& SS
.isNotEmpty() && !Tag
->isCompleteDefinition() &&
5172 !IsExplicitInstantiation
&& !IsExplicitSpecialization
&&
5173 !isa
<ClassTemplatePartialSpecializationDecl
>(Tag
)) {
5174 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5175 // nested-name-specifier unless it is an explicit instantiation
5176 // or an explicit specialization.
5178 // FIXME: We allow class template partial specializations here too, per the
5179 // obvious intent of DR1819.
5181 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5182 Diag(SS
.getBeginLoc(), diag::err_standalone_class_nested_name_specifier
)
5183 << GetDiagnosticTypeSpecifierID(DS
) << SS
.getRange();
5187 // Track whether this decl-specifier declares anything.
5188 bool DeclaresAnything
= true;
5190 // Handle anonymous struct definitions.
5191 if (RecordDecl
*Record
= dyn_cast_or_null
<RecordDecl
>(Tag
)) {
5192 if (!Record
->getDeclName() && Record
->isCompleteDefinition() &&
5193 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
) {
5194 if (getLangOpts().CPlusPlus
||
5195 Record
->getDeclContext()->isRecord()) {
5196 // If CurContext is a DeclContext that can contain statements,
5197 // RecursiveASTVisitor won't visit the decls that
5198 // BuildAnonymousStructOrUnion() will put into CurContext.
5199 // Also store them here so that they can be part of the
5200 // DeclStmt that gets created in this case.
5201 // FIXME: Also return the IndirectFieldDecls created by
5202 // BuildAnonymousStructOr union, for the same reason?
5203 if (CurContext
->isFunctionOrMethod())
5204 AnonRecord
= Record
;
5205 return BuildAnonymousStructOrUnion(S
, DS
, AS
, Record
,
5206 Context
.getPrintingPolicy());
5209 DeclaresAnything
= false;
5214 // A struct-declaration that does not declare an anonymous structure or
5215 // anonymous union shall contain a struct-declarator-list.
5217 // This rule also existed in C89 and C99; the grammar for struct-declaration
5218 // did not permit a struct-declaration without a struct-declarator-list.
5219 if (!getLangOpts().CPlusPlus
&& CurContext
->isRecord() &&
5220 DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
) {
5221 // Check for Microsoft C extension: anonymous struct/union member.
5222 // Handle 2 kinds of anonymous struct/union:
5226 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5227 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5228 if ((Tag
&& Tag
->getDeclName()) ||
5229 DS
.getTypeSpecType() == DeclSpec::TST_typename
) {
5230 RecordDecl
*Record
= nullptr;
5232 Record
= dyn_cast
<RecordDecl
>(Tag
);
5233 else if (const RecordType
*RT
=
5234 DS
.getRepAsType().get()->getAsStructureType())
5235 Record
= RT
->getDecl();
5236 else if (const RecordType
*UT
= DS
.getRepAsType().get()->getAsUnionType())
5237 Record
= UT
->getDecl();
5239 if (Record
&& getLangOpts().MicrosoftExt
) {
5240 Diag(DS
.getBeginLoc(), diag::ext_ms_anonymous_record
)
5241 << Record
->isUnion() << DS
.getSourceRange();
5242 return BuildMicrosoftCAnonymousStruct(S
, DS
, Record
);
5245 DeclaresAnything
= false;
5249 // Skip all the checks below if we have a type error.
5250 if (DS
.getTypeSpecType() == DeclSpec::TST_error
||
5251 (TagD
&& TagD
->isInvalidDecl()))
5254 if (getLangOpts().CPlusPlus
&&
5255 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
)
5256 if (EnumDecl
*Enum
= dyn_cast_or_null
<EnumDecl
>(Tag
))
5257 if (Enum
->enumerator_begin() == Enum
->enumerator_end() &&
5258 !Enum
->getIdentifier() && !Enum
->isInvalidDecl())
5259 DeclaresAnything
= false;
5261 if (!DS
.isMissingDeclaratorOk()) {
5262 // Customize diagnostic for a typedef missing a name.
5263 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
)
5264 Diag(DS
.getBeginLoc(), diag::ext_typedef_without_a_name
)
5265 << DS
.getSourceRange();
5267 DeclaresAnything
= false;
5270 if (DS
.isModulePrivateSpecified() &&
5271 Tag
&& Tag
->getDeclContext()->isFunctionOrMethod())
5272 Diag(DS
.getModulePrivateSpecLoc(), diag::err_module_private_local_class
)
5273 << Tag
->getTagKind()
5274 << FixItHint::CreateRemoval(DS
.getModulePrivateSpecLoc());
5276 ActOnDocumentableDecl(TagD
);
5279 // A declaration [...] shall declare at least a declarator [...], a tag,
5280 // or the members of an enumeration.
5282 // [If there are no declarators], and except for the declaration of an
5283 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5284 // names into the program, or shall redeclare a name introduced by a
5285 // previous declaration.
5286 if (!DeclaresAnything
) {
5287 // In C, we allow this as a (popular) extension / bug. Don't bother
5288 // producing further diagnostics for redundant qualifiers after this.
5289 Diag(DS
.getBeginLoc(), (IsExplicitInstantiation
|| !TemplateParams
.empty())
5290 ? diag::err_no_declarators
5291 : diag::ext_no_declarators
)
5292 << DS
.getSourceRange();
5297 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5298 // init-declarator-list of the declaration shall not be empty.
5299 // C++ [dcl.fct.spec]p1:
5300 // If a cv-qualifier appears in a decl-specifier-seq, the
5301 // init-declarator-list of the declaration shall not be empty.
5303 // Spurious qualifiers here appear to be valid in C.
5304 unsigned DiagID
= diag::warn_standalone_specifier
;
5305 if (getLangOpts().CPlusPlus
)
5306 DiagID
= diag::ext_standalone_specifier
;
5308 // Note that a linkage-specification sets a storage class, but
5309 // 'extern "C" struct foo;' is actually valid and not theoretically
5311 if (DeclSpec::SCS SCS
= DS
.getStorageClassSpec()) {
5312 if (SCS
== DeclSpec::SCS_mutable
)
5313 // Since mutable is not a viable storage class specifier in C, there is
5314 // no reason to treat it as an extension. Instead, diagnose as an error.
5315 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_nonmember
);
5316 else if (!DS
.isExternInLinkageSpec() && SCS
!= DeclSpec::SCS_typedef
)
5317 Diag(DS
.getStorageClassSpecLoc(), DiagID
)
5318 << DeclSpec::getSpecifierName(SCS
);
5321 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
5322 Diag(DS
.getThreadStorageClassSpecLoc(), DiagID
)
5323 << DeclSpec::getSpecifierName(TSCS
);
5324 if (DS
.getTypeQualifiers()) {
5325 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5326 Diag(DS
.getConstSpecLoc(), DiagID
) << "const";
5327 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5328 Diag(DS
.getConstSpecLoc(), DiagID
) << "volatile";
5329 // Restrict is covered above.
5330 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5331 Diag(DS
.getAtomicSpecLoc(), DiagID
) << "_Atomic";
5332 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5333 Diag(DS
.getUnalignedSpecLoc(), DiagID
) << "__unaligned";
5336 // Warn about ignored type attributes, for example:
5337 // __attribute__((aligned)) struct A;
5338 // Attributes should be placed after tag to apply to type declaration.
5339 if (!DS
.getAttributes().empty() || !DeclAttrs
.empty()) {
5340 DeclSpec::TST TypeSpecType
= DS
.getTypeSpecType();
5341 if (TypeSpecType
== DeclSpec::TST_class
||
5342 TypeSpecType
== DeclSpec::TST_struct
||
5343 TypeSpecType
== DeclSpec::TST_interface
||
5344 TypeSpecType
== DeclSpec::TST_union
||
5345 TypeSpecType
== DeclSpec::TST_enum
) {
5346 for (const ParsedAttr
&AL
: DS
.getAttributes())
5347 Diag(AL
.getLoc(), AL
.isRegularKeywordAttribute()
5348 ? diag::err_declspec_keyword_has_no_effect
5349 : diag::warn_declspec_attribute_ignored
)
5350 << AL
<< GetDiagnosticTypeSpecifierID(DS
);
5351 for (const ParsedAttr
&AL
: DeclAttrs
)
5352 Diag(AL
.getLoc(), AL
.isRegularKeywordAttribute()
5353 ? diag::err_declspec_keyword_has_no_effect
5354 : diag::warn_declspec_attribute_ignored
)
5355 << AL
<< GetDiagnosticTypeSpecifierID(DS
);
5362 /// We are trying to inject an anonymous member into the given scope;
5363 /// check if there's an existing declaration that can't be overloaded.
5365 /// \return true if this is a forbidden redeclaration
5366 static bool CheckAnonMemberRedeclaration(Sema
&SemaRef
, Scope
*S
,
5368 DeclarationName Name
,
5369 SourceLocation NameLoc
, bool IsUnion
,
5371 LookupResult
R(SemaRef
, Name
, NameLoc
,
5372 Owner
->isRecord() ? Sema::LookupMemberName
5373 : Sema::LookupOrdinaryName
,
5374 Sema::ForVisibleRedeclaration
);
5375 if (!SemaRef
.LookupName(R
, S
)) return false;
5377 // Pick a representative declaration.
5378 NamedDecl
*PrevDecl
= R
.getRepresentativeDecl()->getUnderlyingDecl();
5379 assert(PrevDecl
&& "Expected a non-null Decl");
5381 if (!SemaRef
.isDeclInScope(PrevDecl
, Owner
, S
))
5384 if (SC
== StorageClass::SC_None
&&
5385 PrevDecl
->isPlaceholderVar(SemaRef
.getLangOpts()) &&
5386 (Owner
->isFunctionOrMethod() || Owner
->isRecord())) {
5387 if (!Owner
->isRecord())
5388 SemaRef
.DiagPlaceholderVariableDefinition(NameLoc
);
5392 SemaRef
.Diag(NameLoc
, diag::err_anonymous_record_member_redecl
)
5394 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
5399 void Sema::ActOnDefinedDeclarationSpecifier(Decl
*D
) {
5400 if (auto *RD
= dyn_cast_if_present
<RecordDecl
>(D
))
5401 DiagPlaceholderFieldDeclDefinitions(RD
);
5404 /// Emit diagnostic warnings for placeholder members.
5405 /// We can only do that after the class is fully constructed,
5406 /// as anonymous union/structs can insert placeholders
5407 /// in their parent scope (which might be a Record).
5408 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl
*Record
) {
5409 if (!getLangOpts().CPlusPlus
)
5412 // This function can be parsed before we have validated the
5413 // structure as an anonymous struct
5414 if (Record
->isAnonymousStructOrUnion())
5417 const NamedDecl
*First
= 0;
5418 for (const Decl
*D
: Record
->decls()) {
5419 const NamedDecl
*ND
= dyn_cast
<NamedDecl
>(D
);
5420 if (!ND
|| !ND
->isPlaceholderVar(getLangOpts()))
5425 DiagPlaceholderVariableDefinition(ND
->getLocation());
5429 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5430 /// anonymous struct or union AnonRecord into the owning context Owner
5431 /// and scope S. This routine will be invoked just after we realize
5432 /// that an unnamed union or struct is actually an anonymous union or
5439 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5440 /// // f into the surrounding scope.x
5443 /// This routine is recursive, injecting the names of nested anonymous
5444 /// structs/unions into the owning context and scope as well.
5446 InjectAnonymousStructOrUnionMembers(Sema
&SemaRef
, Scope
*S
, DeclContext
*Owner
,
5447 RecordDecl
*AnonRecord
, AccessSpecifier AS
,
5449 SmallVectorImpl
<NamedDecl
*> &Chaining
) {
5450 bool Invalid
= false;
5452 // Look every FieldDecl and IndirectFieldDecl with a name.
5453 for (auto *D
: AnonRecord
->decls()) {
5454 if ((isa
<FieldDecl
>(D
) || isa
<IndirectFieldDecl
>(D
)) &&
5455 cast
<NamedDecl
>(D
)->getDeclName()) {
5456 ValueDecl
*VD
= cast
<ValueDecl
>(D
);
5457 if (CheckAnonMemberRedeclaration(SemaRef
, S
, Owner
, VD
->getDeclName(),
5458 VD
->getLocation(), AnonRecord
->isUnion(),
5460 // C++ [class.union]p2:
5461 // The names of the members of an anonymous union shall be
5462 // distinct from the names of any other entity in the
5463 // scope in which the anonymous union is declared.
5466 // C++ [class.union]p2:
5467 // For the purpose of name lookup, after the anonymous union
5468 // definition, the members of the anonymous union are
5469 // considered to have been defined in the scope in which the
5470 // anonymous union is declared.
5471 unsigned OldChainingSize
= Chaining
.size();
5472 if (IndirectFieldDecl
*IF
= dyn_cast
<IndirectFieldDecl
>(VD
))
5473 Chaining
.append(IF
->chain_begin(), IF
->chain_end());
5475 Chaining
.push_back(VD
);
5477 assert(Chaining
.size() >= 2);
5478 NamedDecl
**NamedChain
=
5479 new (SemaRef
.Context
)NamedDecl
*[Chaining
.size()];
5480 for (unsigned i
= 0; i
< Chaining
.size(); i
++)
5481 NamedChain
[i
] = Chaining
[i
];
5483 IndirectFieldDecl
*IndirectField
= IndirectFieldDecl::Create(
5484 SemaRef
.Context
, Owner
, VD
->getLocation(), VD
->getIdentifier(),
5485 VD
->getType(), {NamedChain
, Chaining
.size()});
5487 for (const auto *Attr
: VD
->attrs())
5488 IndirectField
->addAttr(Attr
->clone(SemaRef
.Context
));
5490 IndirectField
->setAccess(AS
);
5491 IndirectField
->setImplicit();
5492 SemaRef
.PushOnScopeChains(IndirectField
, S
);
5494 // That includes picking up the appropriate access specifier.
5495 if (AS
!= AS_none
) IndirectField
->setAccess(AS
);
5497 Chaining
.resize(OldChainingSize
);
5505 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5506 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5507 /// illegal input values are mapped to SC_None.
5509 StorageClassSpecToVarDeclStorageClass(const DeclSpec
&DS
) {
5510 DeclSpec::SCS StorageClassSpec
= DS
.getStorageClassSpec();
5511 assert(StorageClassSpec
!= DeclSpec::SCS_typedef
&&
5512 "Parser allowed 'typedef' as storage class VarDecl.");
5513 switch (StorageClassSpec
) {
5514 case DeclSpec::SCS_unspecified
: return SC_None
;
5515 case DeclSpec::SCS_extern
:
5516 if (DS
.isExternInLinkageSpec())
5519 case DeclSpec::SCS_static
: return SC_Static
;
5520 case DeclSpec::SCS_auto
: return SC_Auto
;
5521 case DeclSpec::SCS_register
: return SC_Register
;
5522 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
5523 // Illegal SCSs map to None: error reporting is up to the caller.
5524 case DeclSpec::SCS_mutable
: // Fall through.
5525 case DeclSpec::SCS_typedef
: return SC_None
;
5527 llvm_unreachable("unknown storage class specifier");
5530 static SourceLocation
findDefaultInitializer(const CXXRecordDecl
*Record
) {
5531 assert(Record
->hasInClassInitializer());
5533 for (const auto *I
: Record
->decls()) {
5534 const auto *FD
= dyn_cast
<FieldDecl
>(I
);
5535 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
5536 FD
= IFD
->getAnonField();
5537 if (FD
&& FD
->hasInClassInitializer())
5538 return FD
->getLocation();
5541 llvm_unreachable("couldn't find in-class initializer");
5544 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5545 SourceLocation DefaultInitLoc
) {
5546 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5549 S
.Diag(DefaultInitLoc
, diag::err_multiple_mem_union_initialization
);
5550 S
.Diag(findDefaultInitializer(Parent
), diag::note_previous_initializer
) << 0;
5553 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5554 CXXRecordDecl
*AnonUnion
) {
5555 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5558 checkDuplicateDefaultInit(S
, Parent
, findDefaultInitializer(AnonUnion
));
5561 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5562 /// anonymous structure or union. Anonymous unions are a C++ feature
5563 /// (C++ [class.union]) and a C11 feature; anonymous structures
5564 /// are a C11 feature and GNU C++ extension.
5565 Decl
*Sema::BuildAnonymousStructOrUnion(Scope
*S
, DeclSpec
&DS
,
5568 const PrintingPolicy
&Policy
) {
5569 DeclContext
*Owner
= Record
->getDeclContext();
5571 // Diagnose whether this anonymous struct/union is an extension.
5572 if (Record
->isUnion() && !getLangOpts().CPlusPlus
&& !getLangOpts().C11
)
5573 Diag(Record
->getLocation(), diag::ext_anonymous_union
);
5574 else if (!Record
->isUnion() && getLangOpts().CPlusPlus
)
5575 Diag(Record
->getLocation(), diag::ext_gnu_anonymous_struct
);
5576 else if (!Record
->isUnion() && !getLangOpts().C11
)
5577 Diag(Record
->getLocation(), diag::ext_c11_anonymous_struct
);
5579 // C and C++ require different kinds of checks for anonymous
5581 bool Invalid
= false;
5582 if (getLangOpts().CPlusPlus
) {
5583 const char *PrevSpec
= nullptr;
5584 if (Record
->isUnion()) {
5585 // C++ [class.union]p6:
5586 // C++17 [class.union.anon]p2:
5587 // Anonymous unions declared in a named namespace or in the
5588 // global namespace shall be declared static.
5590 DeclContext
*OwnerScope
= Owner
->getRedeclContext();
5591 if (DS
.getStorageClassSpec() != DeclSpec::SCS_static
&&
5592 (OwnerScope
->isTranslationUnit() ||
5593 (OwnerScope
->isNamespace() &&
5594 !cast
<NamespaceDecl
>(OwnerScope
)->isAnonymousNamespace()))) {
5595 Diag(Record
->getLocation(), diag::err_anonymous_union_not_static
)
5596 << FixItHint::CreateInsertion(Record
->getLocation(), "static ");
5598 // Recover by adding 'static'.
5599 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_static
, SourceLocation(),
5600 PrevSpec
, DiagID
, Policy
);
5602 // C++ [class.union]p6:
5603 // A storage class is not allowed in a declaration of an
5604 // anonymous union in a class scope.
5605 else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
&&
5606 isa
<RecordDecl
>(Owner
)) {
5607 Diag(DS
.getStorageClassSpecLoc(),
5608 diag::err_anonymous_union_with_storage_spec
)
5609 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
5611 // Recover by removing the storage specifier.
5612 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified
,
5614 PrevSpec
, DiagID
, Context
.getPrintingPolicy());
5618 // Ignore const/volatile/restrict qualifiers.
5619 if (DS
.getTypeQualifiers()) {
5620 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5621 Diag(DS
.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified
)
5622 << Record
->isUnion() << "const"
5623 << FixItHint::CreateRemoval(DS
.getConstSpecLoc());
5624 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5625 Diag(DS
.getVolatileSpecLoc(),
5626 diag::ext_anonymous_struct_union_qualified
)
5627 << Record
->isUnion() << "volatile"
5628 << FixItHint::CreateRemoval(DS
.getVolatileSpecLoc());
5629 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
5630 Diag(DS
.getRestrictSpecLoc(),
5631 diag::ext_anonymous_struct_union_qualified
)
5632 << Record
->isUnion() << "restrict"
5633 << FixItHint::CreateRemoval(DS
.getRestrictSpecLoc());
5634 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5635 Diag(DS
.getAtomicSpecLoc(),
5636 diag::ext_anonymous_struct_union_qualified
)
5637 << Record
->isUnion() << "_Atomic"
5638 << FixItHint::CreateRemoval(DS
.getAtomicSpecLoc());
5639 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5640 Diag(DS
.getUnalignedSpecLoc(),
5641 diag::ext_anonymous_struct_union_qualified
)
5642 << Record
->isUnion() << "__unaligned"
5643 << FixItHint::CreateRemoval(DS
.getUnalignedSpecLoc());
5645 DS
.ClearTypeQualifiers();
5648 // C++ [class.union]p2:
5649 // The member-specification of an anonymous union shall only
5650 // define non-static data members. [Note: nested types and
5651 // functions cannot be declared within an anonymous union. ]
5652 for (auto *Mem
: Record
->decls()) {
5653 // Ignore invalid declarations; we already diagnosed them.
5654 if (Mem
->isInvalidDecl())
5657 if (auto *FD
= dyn_cast
<FieldDecl
>(Mem
)) {
5658 // C++ [class.union]p3:
5659 // An anonymous union shall not have private or protected
5660 // members (clause 11).
5661 assert(FD
->getAccess() != AS_none
);
5662 if (FD
->getAccess() != AS_public
) {
5663 Diag(FD
->getLocation(), diag::err_anonymous_record_nonpublic_member
)
5664 << Record
->isUnion() << (FD
->getAccess() == AS_protected
);
5668 // C++ [class.union]p1
5669 // An object of a class with a non-trivial constructor, a non-trivial
5670 // copy constructor, a non-trivial destructor, or a non-trivial copy
5671 // assignment operator cannot be a member of a union, nor can an
5672 // array of such objects.
5673 if (CheckNontrivialField(FD
))
5675 } else if (Mem
->isImplicit()) {
5676 // Any implicit members are fine.
5677 } else if (isa
<TagDecl
>(Mem
) && Mem
->getDeclContext() != Record
) {
5678 // This is a type that showed up in an
5679 // elaborated-type-specifier inside the anonymous struct or
5680 // union, but which actually declares a type outside of the
5681 // anonymous struct or union. It's okay.
5682 } else if (auto *MemRecord
= dyn_cast
<RecordDecl
>(Mem
)) {
5683 if (!MemRecord
->isAnonymousStructOrUnion() &&
5684 MemRecord
->getDeclName()) {
5685 // Visual C++ allows type definition in anonymous struct or union.
5686 if (getLangOpts().MicrosoftExt
)
5687 Diag(MemRecord
->getLocation(), diag::ext_anonymous_record_with_type
)
5688 << Record
->isUnion();
5690 // This is a nested type declaration.
5691 Diag(MemRecord
->getLocation(), diag::err_anonymous_record_with_type
)
5692 << Record
->isUnion();
5696 // This is an anonymous type definition within another anonymous type.
5697 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5698 // not part of standard C++.
5699 Diag(MemRecord
->getLocation(),
5700 diag::ext_anonymous_record_with_anonymous_type
)
5701 << Record
->isUnion();
5703 } else if (isa
<AccessSpecDecl
>(Mem
)) {
5704 // Any access specifier is fine.
5705 } else if (isa
<StaticAssertDecl
>(Mem
)) {
5706 // In C++1z, static_assert declarations are also fine.
5708 // We have something that isn't a non-static data
5709 // member. Complain about it.
5710 unsigned DK
= diag::err_anonymous_record_bad_member
;
5711 if (isa
<TypeDecl
>(Mem
))
5712 DK
= diag::err_anonymous_record_with_type
;
5713 else if (isa
<FunctionDecl
>(Mem
))
5714 DK
= diag::err_anonymous_record_with_function
;
5715 else if (isa
<VarDecl
>(Mem
))
5716 DK
= diag::err_anonymous_record_with_static
;
5718 // Visual C++ allows type definition in anonymous struct or union.
5719 if (getLangOpts().MicrosoftExt
&&
5720 DK
== diag::err_anonymous_record_with_type
)
5721 Diag(Mem
->getLocation(), diag::ext_anonymous_record_with_type
)
5722 << Record
->isUnion();
5724 Diag(Mem
->getLocation(), DK
) << Record
->isUnion();
5730 // C++11 [class.union]p8 (DR1460):
5731 // At most one variant member of a union may have a
5732 // brace-or-equal-initializer.
5733 if (cast
<CXXRecordDecl
>(Record
)->hasInClassInitializer() &&
5735 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Owner
),
5736 cast
<CXXRecordDecl
>(Record
));
5739 if (!Record
->isUnion() && !Owner
->isRecord()) {
5740 Diag(Record
->getLocation(), diag::err_anonymous_struct_not_member
)
5741 << getLangOpts().CPlusPlus
;
5746 // [If there are no declarators], and except for the declaration of an
5747 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5748 // names into the program
5749 // C++ [class.mem]p2:
5750 // each such member-declaration shall either declare at least one member
5751 // name of the class or declare at least one unnamed bit-field
5753 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5754 if (getLangOpts().CPlusPlus
&& Record
->field_empty())
5755 Diag(DS
.getBeginLoc(), diag::ext_no_declarators
) << DS
.getSourceRange();
5757 // Mock up a declarator.
5758 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::Member
);
5759 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(DS
);
5760 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5761 assert(TInfo
&& "couldn't build declarator info for anonymous struct/union");
5763 // Create a declaration for this anonymous struct/union.
5764 NamedDecl
*Anon
= nullptr;
5765 if (RecordDecl
*OwningClass
= dyn_cast
<RecordDecl
>(Owner
)) {
5766 Anon
= FieldDecl::Create(
5767 Context
, OwningClass
, DS
.getBeginLoc(), Record
->getLocation(),
5768 /*IdentifierInfo=*/nullptr, Context
.getTypeDeclType(Record
), TInfo
,
5769 /*BitWidth=*/nullptr, /*Mutable=*/false,
5770 /*InitStyle=*/ICIS_NoInit
);
5771 Anon
->setAccess(AS
);
5772 ProcessDeclAttributes(S
, Anon
, Dc
);
5774 if (getLangOpts().CPlusPlus
)
5775 FieldCollector
->Add(cast
<FieldDecl
>(Anon
));
5777 DeclSpec::SCS SCSpec
= DS
.getStorageClassSpec();
5778 if (SCSpec
== DeclSpec::SCS_mutable
) {
5779 // mutable can only appear on non-static class members, so it's always
5781 Diag(Record
->getLocation(), diag::err_mutable_nonmember
);
5786 Anon
= VarDecl::Create(Context
, Owner
, DS
.getBeginLoc(),
5787 Record
->getLocation(), /*IdentifierInfo=*/nullptr,
5788 Context
.getTypeDeclType(Record
), TInfo
, SC
);
5789 ProcessDeclAttributes(S
, Anon
, Dc
);
5791 // Default-initialize the implicit variable. This initialization will be
5792 // trivial in almost all cases, except if a union member has an in-class
5794 // union { int n = 0; };
5795 ActOnUninitializedDecl(Anon
);
5797 Anon
->setImplicit();
5799 // Mark this as an anonymous struct/union type.
5800 Record
->setAnonymousStructOrUnion(true);
5802 // Add the anonymous struct/union object to the current
5803 // context. We'll be referencing this object when we refer to one of
5805 Owner
->addDecl(Anon
);
5807 // Inject the members of the anonymous struct/union into the owning
5808 // context and into the identifier resolver chain for name lookup
5810 SmallVector
<NamedDecl
*, 2> Chain
;
5811 Chain
.push_back(Anon
);
5813 if (InjectAnonymousStructOrUnionMembers(*this, S
, Owner
, Record
, AS
, SC
,
5817 if (VarDecl
*NewVD
= dyn_cast
<VarDecl
>(Anon
)) {
5818 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
5819 MangleNumberingContext
*MCtx
;
5820 Decl
*ManglingContextDecl
;
5821 std::tie(MCtx
, ManglingContextDecl
) =
5822 getCurrentMangleNumberContext(NewVD
->getDeclContext());
5824 Context
.setManglingNumber(
5825 NewVD
, MCtx
->getManglingNumber(
5826 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
5827 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
5833 Anon
->setInvalidDecl();
5838 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5839 /// Microsoft C anonymous structure.
5840 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5843 /// struct A { int a; };
5844 /// struct B { struct A; int b; };
5851 Decl
*Sema::BuildMicrosoftCAnonymousStruct(Scope
*S
, DeclSpec
&DS
,
5852 RecordDecl
*Record
) {
5853 assert(Record
&& "expected a record!");
5855 // Mock up a declarator.
5856 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::TypeName
);
5857 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5858 assert(TInfo
&& "couldn't build declarator info for anonymous struct");
5860 auto *ParentDecl
= cast
<RecordDecl
>(CurContext
);
5861 QualType RecTy
= Context
.getTypeDeclType(Record
);
5863 // Create a declaration for this anonymous struct.
5865 FieldDecl::Create(Context
, ParentDecl
, DS
.getBeginLoc(), DS
.getBeginLoc(),
5866 /*IdentifierInfo=*/nullptr, RecTy
, TInfo
,
5867 /*BitWidth=*/nullptr, /*Mutable=*/false,
5868 /*InitStyle=*/ICIS_NoInit
);
5869 Anon
->setImplicit();
5871 // Add the anonymous struct object to the current context.
5872 CurContext
->addDecl(Anon
);
5874 // Inject the members of the anonymous struct into the current
5875 // context and into the identifier resolver chain for name lookup
5877 SmallVector
<NamedDecl
*, 2> Chain
;
5878 Chain
.push_back(Anon
);
5880 RecordDecl
*RecordDef
= Record
->getDefinition();
5881 if (RequireCompleteSizedType(Anon
->getLocation(), RecTy
,
5882 diag::err_field_incomplete_or_sizeless
) ||
5883 InjectAnonymousStructOrUnionMembers(
5884 *this, S
, CurContext
, RecordDef
, AS_none
,
5885 StorageClassSpecToVarDeclStorageClass(DS
), Chain
)) {
5886 Anon
->setInvalidDecl();
5887 ParentDecl
->setInvalidDecl();
5893 /// GetNameForDeclarator - Determine the full declaration name for the
5894 /// given Declarator.
5895 DeclarationNameInfo
Sema::GetNameForDeclarator(Declarator
&D
) {
5896 return GetNameFromUnqualifiedId(D
.getName());
5899 /// Retrieves the declaration name from a parsed unqualified-id.
5901 Sema::GetNameFromUnqualifiedId(const UnqualifiedId
&Name
) {
5902 DeclarationNameInfo NameInfo
;
5903 NameInfo
.setLoc(Name
.StartLocation
);
5905 switch (Name
.getKind()) {
5907 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
5908 case UnqualifiedIdKind::IK_Identifier
:
5909 NameInfo
.setName(Name
.Identifier
);
5912 case UnqualifiedIdKind::IK_DeductionGuideName
: {
5913 // C++ [temp.deduct.guide]p3:
5914 // The simple-template-id shall name a class template specialization.
5915 // The template-name shall be the same identifier as the template-name
5916 // of the simple-template-id.
5917 // These together intend to imply that the template-name shall name a
5919 // FIXME: template<typename T> struct X {};
5920 // template<typename T> using Y = X<T>;
5921 // Y(int) -> Y<int>;
5922 // satisfies these rules but does not name a class template.
5923 TemplateName TN
= Name
.TemplateName
.get().get();
5924 auto *Template
= TN
.getAsTemplateDecl();
5925 if (!Template
|| !isa
<ClassTemplateDecl
>(Template
)) {
5926 Diag(Name
.StartLocation
,
5927 diag::err_deduction_guide_name_not_class_template
)
5928 << (int)getTemplateNameKindForDiagnostics(TN
) << TN
;
5930 Diag(Template
->getLocation(), diag::note_template_decl_here
);
5931 return DeclarationNameInfo();
5935 Context
.DeclarationNames
.getCXXDeductionGuideName(Template
));
5939 case UnqualifiedIdKind::IK_OperatorFunctionId
:
5940 NameInfo
.setName(Context
.DeclarationNames
.getCXXOperatorName(
5941 Name
.OperatorFunctionId
.Operator
));
5942 NameInfo
.setCXXOperatorNameRange(SourceRange(
5943 Name
.OperatorFunctionId
.SymbolLocations
[0], Name
.EndLocation
));
5946 case UnqualifiedIdKind::IK_LiteralOperatorId
:
5947 NameInfo
.setName(Context
.DeclarationNames
.getCXXLiteralOperatorName(
5949 NameInfo
.setCXXLiteralOperatorNameLoc(Name
.EndLocation
);
5952 case UnqualifiedIdKind::IK_ConversionFunctionId
: {
5953 TypeSourceInfo
*TInfo
;
5954 QualType Ty
= GetTypeFromParser(Name
.ConversionFunctionId
, &TInfo
);
5956 return DeclarationNameInfo();
5957 NameInfo
.setName(Context
.DeclarationNames
.getCXXConversionFunctionName(
5958 Context
.getCanonicalType(Ty
)));
5959 NameInfo
.setNamedTypeInfo(TInfo
);
5963 case UnqualifiedIdKind::IK_ConstructorName
: {
5964 TypeSourceInfo
*TInfo
;
5965 QualType Ty
= GetTypeFromParser(Name
.ConstructorName
, &TInfo
);
5967 return DeclarationNameInfo();
5968 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5969 Context
.getCanonicalType(Ty
)));
5970 NameInfo
.setNamedTypeInfo(TInfo
);
5974 case UnqualifiedIdKind::IK_ConstructorTemplateId
: {
5975 // In well-formed code, we can only have a constructor
5976 // template-id that refers to the current context, so go there
5977 // to find the actual type being constructed.
5978 CXXRecordDecl
*CurClass
= dyn_cast
<CXXRecordDecl
>(CurContext
);
5979 if (!CurClass
|| CurClass
->getIdentifier() != Name
.TemplateId
->Name
)
5980 return DeclarationNameInfo();
5982 // Determine the type of the class being constructed.
5983 QualType CurClassType
= Context
.getTypeDeclType(CurClass
);
5985 // FIXME: Check two things: that the template-id names the same type as
5986 // CurClassType, and that the template-id does not occur when the name
5989 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5990 Context
.getCanonicalType(CurClassType
)));
5991 // FIXME: should we retrieve TypeSourceInfo?
5992 NameInfo
.setNamedTypeInfo(nullptr);
5996 case UnqualifiedIdKind::IK_DestructorName
: {
5997 TypeSourceInfo
*TInfo
;
5998 QualType Ty
= GetTypeFromParser(Name
.DestructorName
, &TInfo
);
6000 return DeclarationNameInfo();
6001 NameInfo
.setName(Context
.DeclarationNames
.getCXXDestructorName(
6002 Context
.getCanonicalType(Ty
)));
6003 NameInfo
.setNamedTypeInfo(TInfo
);
6007 case UnqualifiedIdKind::IK_TemplateId
: {
6008 TemplateName TName
= Name
.TemplateId
->Template
.get();
6009 SourceLocation TNameLoc
= Name
.TemplateId
->TemplateNameLoc
;
6010 return Context
.getNameForTemplate(TName
, TNameLoc
);
6013 } // switch (Name.getKind())
6015 llvm_unreachable("Unknown name kind");
6018 static QualType
getCoreType(QualType Ty
) {
6020 if (Ty
->isPointerType() || Ty
->isReferenceType())
6021 Ty
= Ty
->getPointeeType();
6022 else if (Ty
->isArrayType())
6023 Ty
= Ty
->castAsArrayTypeUnsafe()->getElementType();
6025 return Ty
.withoutLocalFastQualifiers();
6029 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6030 /// and Definition have "nearly" matching parameters. This heuristic is
6031 /// used to improve diagnostics in the case where an out-of-line function
6032 /// definition doesn't match any declaration within the class or namespace.
6033 /// Also sets Params to the list of indices to the parameters that differ
6034 /// between the declaration and the definition. If hasSimilarParameters
6035 /// returns true and Params is empty, then all of the parameters match.
6036 static bool hasSimilarParameters(ASTContext
&Context
,
6037 FunctionDecl
*Declaration
,
6038 FunctionDecl
*Definition
,
6039 SmallVectorImpl
<unsigned> &Params
) {
6041 if (Declaration
->param_size() != Definition
->param_size())
6043 for (unsigned Idx
= 0; Idx
< Declaration
->param_size(); ++Idx
) {
6044 QualType DeclParamTy
= Declaration
->getParamDecl(Idx
)->getType();
6045 QualType DefParamTy
= Definition
->getParamDecl(Idx
)->getType();
6047 // The parameter types are identical
6048 if (Context
.hasSameUnqualifiedType(DefParamTy
, DeclParamTy
))
6051 QualType DeclParamBaseTy
= getCoreType(DeclParamTy
);
6052 QualType DefParamBaseTy
= getCoreType(DefParamTy
);
6053 const IdentifierInfo
*DeclTyName
= DeclParamBaseTy
.getBaseTypeIdentifier();
6054 const IdentifierInfo
*DefTyName
= DefParamBaseTy
.getBaseTypeIdentifier();
6056 if (Context
.hasSameUnqualifiedType(DeclParamBaseTy
, DefParamBaseTy
) ||
6057 (DeclTyName
&& DeclTyName
== DefTyName
))
6058 Params
.push_back(Idx
);
6059 else // The two parameters aren't even close
6066 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6067 /// declarator needs to be rebuilt in the current instantiation.
6068 /// Any bits of declarator which appear before the name are valid for
6069 /// consideration here. That's specifically the type in the decl spec
6070 /// and the base type in any member-pointer chunks.
6071 static bool RebuildDeclaratorInCurrentInstantiation(Sema
&S
, Declarator
&D
,
6072 DeclarationName Name
) {
6073 // The types we specifically need to rebuild are:
6074 // - typenames, typeofs, and decltypes
6075 // - types which will become injected class names
6076 // Of course, we also need to rebuild any type referencing such a
6077 // type. It's safest to just say "dependent", but we call out a
6080 DeclSpec
&DS
= D
.getMutableDeclSpec();
6081 switch (DS
.getTypeSpecType()) {
6082 case DeclSpec::TST_typename
:
6083 case DeclSpec::TST_typeofType
:
6084 case DeclSpec::TST_typeof_unqualType
:
6085 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6086 #include "clang/Basic/TransformTypeTraits.def"
6087 case DeclSpec::TST_atomic
: {
6088 // Grab the type from the parser.
6089 TypeSourceInfo
*TSI
= nullptr;
6090 QualType T
= S
.GetTypeFromParser(DS
.getRepAsType(), &TSI
);
6091 if (T
.isNull() || !T
->isInstantiationDependentType()) break;
6093 // Make sure there's a type source info. This isn't really much
6094 // of a waste; most dependent types should have type source info
6095 // attached already.
6097 TSI
= S
.Context
.getTrivialTypeSourceInfo(T
, DS
.getTypeSpecTypeLoc());
6099 // Rebuild the type in the current instantiation.
6100 TSI
= S
.RebuildTypeInCurrentInstantiation(TSI
, D
.getIdentifierLoc(), Name
);
6101 if (!TSI
) return true;
6103 // Store the new type back in the decl spec.
6104 ParsedType LocType
= S
.CreateParsedType(TSI
->getType(), TSI
);
6105 DS
.UpdateTypeRep(LocType
);
6109 case DeclSpec::TST_decltype
:
6110 case DeclSpec::TST_typeof_unqualExpr
:
6111 case DeclSpec::TST_typeofExpr
: {
6112 Expr
*E
= DS
.getRepAsExpr();
6113 ExprResult Result
= S
.RebuildExprInCurrentInstantiation(E
);
6114 if (Result
.isInvalid()) return true;
6115 DS
.UpdateExprRep(Result
.get());
6120 // Nothing to do for these decl specs.
6124 // It doesn't matter what order we do this in.
6125 for (unsigned I
= 0, E
= D
.getNumTypeObjects(); I
!= E
; ++I
) {
6126 DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
6128 // The only type information in the declarator which can come
6129 // before the declaration name is the base type of a member
6131 if (Chunk
.Kind
!= DeclaratorChunk::MemberPointer
)
6134 // Rebuild the scope specifier in-place.
6135 CXXScopeSpec
&SS
= Chunk
.Mem
.Scope();
6136 if (S
.RebuildNestedNameSpecifierInCurrentInstantiation(SS
))
6143 /// Returns true if the declaration is declared in a system header or from a
6145 static bool isFromSystemHeader(SourceManager
&SM
, const Decl
*D
) {
6146 return SM
.isInSystemHeader(D
->getLocation()) ||
6147 SM
.isInSystemMacro(D
->getLocation());
6150 void Sema::warnOnReservedIdentifier(const NamedDecl
*D
) {
6151 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6153 if (D
->getPreviousDecl() || D
->isImplicit())
6155 ReservedIdentifierStatus Status
= D
->isReserved(getLangOpts());
6156 if (Status
!= ReservedIdentifierStatus::NotReserved
&&
6157 !isFromSystemHeader(Context
.getSourceManager(), D
)) {
6158 Diag(D
->getLocation(), diag::warn_reserved_extern_symbol
)
6159 << D
<< static_cast<int>(Status
);
6163 Decl
*Sema::ActOnDeclarator(Scope
*S
, Declarator
&D
) {
6164 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration
);
6166 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6167 // declaration only if the `bind_to_declaration` extension is set.
6168 SmallVector
<FunctionDecl
*, 4> Bases
;
6169 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
6170 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6171 implementation_extension_bind_to_declaration
))
6172 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6173 S
, D
, MultiTemplateParamsArg(), Bases
);
6175 Decl
*Dcl
= HandleDeclarator(S
, D
, MultiTemplateParamsArg());
6177 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer() &&
6178 Dcl
&& Dcl
->getDeclContext()->isFileContext())
6179 Dcl
->setTopLevelDeclInObjCContainer();
6182 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
6187 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6188 /// If T is the name of a class, then each of the following shall have a
6189 /// name different from T:
6190 /// - every static data member of class T;
6191 /// - every member function of class T
6192 /// - every member of class T that is itself a type;
6193 /// \returns true if the declaration name violates these rules.
6194 bool Sema::DiagnoseClassNameShadow(DeclContext
*DC
,
6195 DeclarationNameInfo NameInfo
) {
6196 DeclarationName Name
= NameInfo
.getName();
6198 CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
);
6199 while (Record
&& Record
->isAnonymousStructOrUnion())
6200 Record
= dyn_cast
<CXXRecordDecl
>(Record
->getParent());
6201 if (Record
&& Record
->getIdentifier() && Record
->getDeclName() == Name
) {
6202 Diag(NameInfo
.getLoc(), diag::err_member_name_of_class
) << Name
;
6209 /// Diagnose a declaration whose declarator-id has the given
6210 /// nested-name-specifier.
6212 /// \param SS The nested-name-specifier of the declarator-id.
6214 /// \param DC The declaration context to which the nested-name-specifier
6217 /// \param Name The name of the entity being declared.
6219 /// \param Loc The location of the name of the entity being declared.
6221 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6222 /// we're declaring an explicit / partial specialization / instantiation.
6224 /// \returns true if we cannot safely recover from this error, false otherwise.
6225 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec
&SS
, DeclContext
*DC
,
6226 DeclarationName Name
,
6227 SourceLocation Loc
, bool IsTemplateId
) {
6228 DeclContext
*Cur
= CurContext
;
6229 while (isa
<LinkageSpecDecl
>(Cur
) || isa
<CapturedDecl
>(Cur
))
6230 Cur
= Cur
->getParent();
6232 // If the user provided a superfluous scope specifier that refers back to the
6233 // class in which the entity is already declared, diagnose and ignore it.
6239 // Note, it was once ill-formed to give redundant qualification in all
6240 // contexts, but that rule was removed by DR482.
6241 if (Cur
->Equals(DC
)) {
6242 if (Cur
->isRecord()) {
6243 Diag(Loc
, LangOpts
.MicrosoftExt
? diag::warn_member_extra_qualification
6244 : diag::err_member_extra_qualification
)
6245 << Name
<< FixItHint::CreateRemoval(SS
.getRange());
6248 Diag(Loc
, diag::warn_namespace_member_extra_qualification
) << Name
;
6253 // Check whether the qualifying scope encloses the scope of the original
6254 // declaration. For a template-id, we perform the checks in
6255 // CheckTemplateSpecializationScope.
6256 if (!Cur
->Encloses(DC
) && !IsTemplateId
) {
6257 if (Cur
->isRecord())
6258 Diag(Loc
, diag::err_member_qualification
)
6259 << Name
<< SS
.getRange();
6260 else if (isa
<TranslationUnitDecl
>(DC
))
6261 Diag(Loc
, diag::err_invalid_declarator_global_scope
)
6262 << Name
<< SS
.getRange();
6263 else if (isa
<FunctionDecl
>(Cur
))
6264 Diag(Loc
, diag::err_invalid_declarator_in_function
)
6265 << Name
<< SS
.getRange();
6266 else if (isa
<BlockDecl
>(Cur
))
6267 Diag(Loc
, diag::err_invalid_declarator_in_block
)
6268 << Name
<< SS
.getRange();
6269 else if (isa
<ExportDecl
>(Cur
)) {
6270 if (!isa
<NamespaceDecl
>(DC
))
6271 Diag(Loc
, diag::err_export_non_namespace_scope_name
)
6272 << Name
<< SS
.getRange();
6274 // The cases that DC is not NamespaceDecl should be handled in
6275 // CheckRedeclarationExported.
6278 Diag(Loc
, diag::err_invalid_declarator_scope
)
6279 << Name
<< cast
<NamedDecl
>(Cur
) << cast
<NamedDecl
>(DC
) << SS
.getRange();
6284 if (Cur
->isRecord()) {
6285 // Cannot qualify members within a class.
6286 Diag(Loc
, diag::err_member_qualification
)
6287 << Name
<< SS
.getRange();
6290 // C++ constructors and destructors with incorrect scopes can break
6291 // our AST invariants by having the wrong underlying types. If
6292 // that's the case, then drop this declaration entirely.
6293 if ((Name
.getNameKind() == DeclarationName::CXXConstructorName
||
6294 Name
.getNameKind() == DeclarationName::CXXDestructorName
) &&
6295 !Context
.hasSameType(Name
.getCXXNameType(),
6296 Context
.getTypeDeclType(cast
<CXXRecordDecl
>(Cur
))))
6302 // C++11 [dcl.meaning]p1:
6303 // [...] "The nested-name-specifier of the qualified declarator-id shall
6304 // not begin with a decltype-specifer"
6305 NestedNameSpecifierLoc
SpecLoc(SS
.getScopeRep(), SS
.location_data());
6306 while (SpecLoc
.getPrefix())
6307 SpecLoc
= SpecLoc
.getPrefix();
6308 if (isa_and_nonnull
<DecltypeType
>(
6309 SpecLoc
.getNestedNameSpecifier()->getAsType()))
6310 Diag(Loc
, diag::err_decltype_in_declarator
)
6311 << SpecLoc
.getTypeLoc().getSourceRange();
6316 NamedDecl
*Sema::HandleDeclarator(Scope
*S
, Declarator
&D
,
6317 MultiTemplateParamsArg TemplateParamLists
) {
6318 // TODO: consider using NameInfo for diagnostic.
6319 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
6320 DeclarationName Name
= NameInfo
.getName();
6322 // All of these full declarators require an identifier. If it doesn't have
6323 // one, the ParsedFreeStandingDeclSpec action should be used.
6324 if (D
.isDecompositionDeclarator()) {
6325 return ActOnDecompositionDeclarator(S
, D
, TemplateParamLists
);
6327 if (!D
.isInvalidType()) // Reject this if we think it is valid.
6328 Diag(D
.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident
)
6329 << D
.getDeclSpec().getSourceRange() << D
.getSourceRange();
6331 } else if (DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_DeclarationType
))
6334 // The scope passed in may not be a decl scope. Zip up the scope tree until
6335 // we find one that is.
6336 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
6337 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
6340 DeclContext
*DC
= CurContext
;
6341 if (D
.getCXXScopeSpec().isInvalid())
6343 else if (D
.getCXXScopeSpec().isSet()) {
6344 if (DiagnoseUnexpandedParameterPack(D
.getCXXScopeSpec(),
6345 UPPC_DeclarationQualifier
))
6348 bool EnteringContext
= !D
.getDeclSpec().isFriendSpecified();
6349 DC
= computeDeclContext(D
.getCXXScopeSpec(), EnteringContext
);
6350 if (!DC
|| isa
<EnumDecl
>(DC
)) {
6351 // If we could not compute the declaration context, it's because the
6352 // declaration context is dependent but does not refer to a class,
6353 // class template, or class template partial specialization. Complain
6354 // and return early, to avoid the coming semantic disaster.
6355 Diag(D
.getIdentifierLoc(),
6356 diag::err_template_qualified_declarator_no_match
)
6357 << D
.getCXXScopeSpec().getScopeRep()
6358 << D
.getCXXScopeSpec().getRange();
6361 bool IsDependentContext
= DC
->isDependentContext();
6363 if (!IsDependentContext
&&
6364 RequireCompleteDeclContext(D
.getCXXScopeSpec(), DC
))
6367 // If a class is incomplete, do not parse entities inside it.
6368 if (isa
<CXXRecordDecl
>(DC
) && !cast
<CXXRecordDecl
>(DC
)->hasDefinition()) {
6369 Diag(D
.getIdentifierLoc(),
6370 diag::err_member_def_undefined_record
)
6371 << Name
<< DC
<< D
.getCXXScopeSpec().getRange();
6374 if (!D
.getDeclSpec().isFriendSpecified()) {
6375 if (diagnoseQualifiedDeclaration(
6376 D
.getCXXScopeSpec(), DC
, Name
, D
.getIdentifierLoc(),
6377 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
)) {
6385 // Check whether we need to rebuild the type of the given
6386 // declaration in the current instantiation.
6387 if (EnteringContext
&& IsDependentContext
&&
6388 TemplateParamLists
.size() != 0) {
6389 ContextRAII
SavedContext(*this, DC
);
6390 if (RebuildDeclaratorInCurrentInstantiation(*this, D
, Name
))
6395 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6396 QualType R
= TInfo
->getType();
6398 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6399 UPPC_DeclarationType
))
6402 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
6403 forRedeclarationInCurContext());
6405 // See if this is a redefinition of a variable in the same scope.
6406 if (!D
.getCXXScopeSpec().isSet()) {
6407 bool IsLinkageLookup
= false;
6408 bool CreateBuiltins
= false;
6410 // If the declaration we're planning to build will be a function
6411 // or object with linkage, then look for another declaration with
6412 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6414 // If the declaration we're planning to build will be declared with
6415 // external linkage in the translation unit, create any builtin with
6417 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
6419 else if (CurContext
->isFunctionOrMethod() &&
6420 (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern
||
6421 R
->isFunctionType())) {
6422 IsLinkageLookup
= true;
6424 CurContext
->getEnclosingNamespaceContext()->isTranslationUnit();
6425 } else if (CurContext
->getRedeclContext()->isTranslationUnit() &&
6426 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
)
6427 CreateBuiltins
= true;
6429 if (IsLinkageLookup
) {
6430 Previous
.clear(LookupRedeclarationWithLinkage
);
6431 Previous
.setRedeclarationKind(ForExternalRedeclaration
);
6434 LookupName(Previous
, S
, CreateBuiltins
);
6435 } else { // Something like "int foo::x;"
6436 LookupQualifiedName(Previous
, DC
);
6438 // C++ [dcl.meaning]p1:
6439 // When the declarator-id is qualified, the declaration shall refer to a
6440 // previously declared member of the class or namespace to which the
6441 // qualifier refers (or, in the case of a namespace, of an element of the
6442 // inline namespace set of that namespace (7.3.1)) or to a specialization
6445 // Note that we already checked the context above, and that we do not have
6446 // enough information to make sure that Previous contains the declaration
6447 // we want to match. For example, given:
6454 // void X::f(int) { } // ill-formed
6456 // In this case, Previous will point to the overload set
6457 // containing the two f's declared in X, but neither of them
6460 RemoveUsingDecls(Previous
);
6463 if (Previous
.isSingleResult() &&
6464 Previous
.getFoundDecl()->isTemplateParameter()) {
6465 // Maybe we will complain about the shadowed template parameter.
6466 if (!D
.isInvalidType())
6467 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
6468 Previous
.getFoundDecl());
6470 // Just pretend that we didn't see the previous declaration.
6474 if (!R
->isFunctionType() && DiagnoseClassNameShadow(DC
, NameInfo
))
6475 // Forget that the previous declaration is the injected-class-name.
6478 // In C++, the previous declaration we find might be a tag type
6479 // (class or enum). In this case, the new declaration will hide the
6480 // tag type. Note that this applies to functions, function templates, and
6481 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6482 if (Previous
.isSingleTagDecl() &&
6483 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
6484 (TemplateParamLists
.size() == 0 || R
->isFunctionType()))
6487 // Check that there are no default arguments other than in the parameters
6488 // of a function declaration (C++ only).
6489 if (getLangOpts().CPlusPlus
)
6490 CheckExtraCXXDefaultArguments(D
);
6494 bool AddToScope
= true;
6495 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
6496 if (TemplateParamLists
.size()) {
6497 Diag(D
.getIdentifierLoc(), diag::err_template_typedef
);
6501 New
= ActOnTypedefDeclarator(S
, D
, DC
, TInfo
, Previous
);
6502 } else if (R
->isFunctionType()) {
6503 New
= ActOnFunctionDeclarator(S
, D
, DC
, TInfo
, Previous
,
6507 New
= ActOnVariableDeclarator(S
, D
, DC
, TInfo
, Previous
, TemplateParamLists
,
6514 // If this has an identifier and is not a function template specialization,
6515 // add it to the scope stack.
6516 if (New
->getDeclName() && AddToScope
)
6517 PushOnScopeChains(New
, S
);
6519 if (isInOpenMPDeclareTargetContext())
6520 checkDeclIsAllowedInOpenMPTarget(nullptr, New
);
6525 /// Helper method to turn variable array types into constant array
6526 /// types in certain situations which would otherwise be errors (for
6527 /// GCC compatibility).
6528 static QualType
TryToFixInvalidVariablyModifiedType(QualType T
,
6529 ASTContext
&Context
,
6530 bool &SizeIsNegative
,
6531 llvm::APSInt
&Oversized
) {
6532 // This method tries to turn a variable array into a constant
6533 // array even when the size isn't an ICE. This is necessary
6534 // for compatibility with code that depends on gcc's buggy
6535 // constant expression folding, like struct {char x[(int)(char*)2];}
6536 SizeIsNegative
= false;
6539 if (T
->isDependentType())
6542 QualifierCollector Qs
;
6543 const Type
*Ty
= Qs
.strip(T
);
6545 if (const PointerType
* PTy
= dyn_cast
<PointerType
>(Ty
)) {
6546 QualType Pointee
= PTy
->getPointeeType();
6547 QualType FixedType
=
6548 TryToFixInvalidVariablyModifiedType(Pointee
, Context
, SizeIsNegative
,
6550 if (FixedType
.isNull()) return FixedType
;
6551 FixedType
= Context
.getPointerType(FixedType
);
6552 return Qs
.apply(Context
, FixedType
);
6554 if (const ParenType
* PTy
= dyn_cast
<ParenType
>(Ty
)) {
6555 QualType Inner
= PTy
->getInnerType();
6556 QualType FixedType
=
6557 TryToFixInvalidVariablyModifiedType(Inner
, Context
, SizeIsNegative
,
6559 if (FixedType
.isNull()) return FixedType
;
6560 FixedType
= Context
.getParenType(FixedType
);
6561 return Qs
.apply(Context
, FixedType
);
6564 const VariableArrayType
* VLATy
= dyn_cast
<VariableArrayType
>(T
);
6568 QualType ElemTy
= VLATy
->getElementType();
6569 if (ElemTy
->isVariablyModifiedType()) {
6570 ElemTy
= TryToFixInvalidVariablyModifiedType(ElemTy
, Context
,
6571 SizeIsNegative
, Oversized
);
6572 if (ElemTy
.isNull())
6576 Expr::EvalResult Result
;
6577 if (!VLATy
->getSizeExpr() ||
6578 !VLATy
->getSizeExpr()->EvaluateAsInt(Result
, Context
))
6581 llvm::APSInt Res
= Result
.Val
.getInt();
6583 // Check whether the array size is negative.
6584 if (Res
.isSigned() && Res
.isNegative()) {
6585 SizeIsNegative
= true;
6589 // Check whether the array is too large to be addressed.
6590 unsigned ActiveSizeBits
=
6591 (!ElemTy
->isDependentType() && !ElemTy
->isVariablyModifiedType() &&
6592 !ElemTy
->isIncompleteType() && !ElemTy
->isUndeducedType())
6593 ? ConstantArrayType::getNumAddressingBits(Context
, ElemTy
, Res
)
6594 : Res
.getActiveBits();
6595 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
)) {
6600 QualType FoldedArrayType
= Context
.getConstantArrayType(
6601 ElemTy
, Res
, VLATy
->getSizeExpr(), ArraySizeModifier::Normal
, 0);
6602 return Qs
.apply(Context
, FoldedArrayType
);
6606 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL
, TypeLoc DstTL
) {
6607 SrcTL
= SrcTL
.getUnqualifiedLoc();
6608 DstTL
= DstTL
.getUnqualifiedLoc();
6609 if (PointerTypeLoc SrcPTL
= SrcTL
.getAs
<PointerTypeLoc
>()) {
6610 PointerTypeLoc DstPTL
= DstTL
.castAs
<PointerTypeLoc
>();
6611 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getPointeeLoc(),
6612 DstPTL
.getPointeeLoc());
6613 DstPTL
.setStarLoc(SrcPTL
.getStarLoc());
6616 if (ParenTypeLoc SrcPTL
= SrcTL
.getAs
<ParenTypeLoc
>()) {
6617 ParenTypeLoc DstPTL
= DstTL
.castAs
<ParenTypeLoc
>();
6618 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getInnerLoc(),
6619 DstPTL
.getInnerLoc());
6620 DstPTL
.setLParenLoc(SrcPTL
.getLParenLoc());
6621 DstPTL
.setRParenLoc(SrcPTL
.getRParenLoc());
6624 ArrayTypeLoc SrcATL
= SrcTL
.castAs
<ArrayTypeLoc
>();
6625 ArrayTypeLoc DstATL
= DstTL
.castAs
<ArrayTypeLoc
>();
6626 TypeLoc SrcElemTL
= SrcATL
.getElementLoc();
6627 TypeLoc DstElemTL
= DstATL
.getElementLoc();
6628 if (VariableArrayTypeLoc SrcElemATL
=
6629 SrcElemTL
.getAs
<VariableArrayTypeLoc
>()) {
6630 ConstantArrayTypeLoc DstElemATL
= DstElemTL
.castAs
<ConstantArrayTypeLoc
>();
6631 FixInvalidVariablyModifiedTypeLoc(SrcElemATL
, DstElemATL
);
6633 DstElemTL
.initializeFullCopy(SrcElemTL
);
6635 DstATL
.setLBracketLoc(SrcATL
.getLBracketLoc());
6636 DstATL
.setSizeExpr(SrcATL
.getSizeExpr());
6637 DstATL
.setRBracketLoc(SrcATL
.getRBracketLoc());
6640 /// Helper method to turn variable array types into constant array
6641 /// types in certain situations which would otherwise be errors (for
6642 /// GCC compatibility).
6643 static TypeSourceInfo
*
6644 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo
*TInfo
,
6645 ASTContext
&Context
,
6646 bool &SizeIsNegative
,
6647 llvm::APSInt
&Oversized
) {
6649 = TryToFixInvalidVariablyModifiedType(TInfo
->getType(), Context
,
6650 SizeIsNegative
, Oversized
);
6651 if (FixedTy
.isNull())
6653 TypeSourceInfo
*FixedTInfo
= Context
.getTrivialTypeSourceInfo(FixedTy
);
6654 FixInvalidVariablyModifiedTypeLoc(TInfo
->getTypeLoc(),
6655 FixedTInfo
->getTypeLoc());
6659 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6660 /// true if we were successful.
6661 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo
*&TInfo
,
6662 QualType
&T
, SourceLocation Loc
,
6663 unsigned FailedFoldDiagID
) {
6664 bool SizeIsNegative
;
6665 llvm::APSInt Oversized
;
6666 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
6667 TInfo
, Context
, SizeIsNegative
, Oversized
);
6669 Diag(Loc
, diag::ext_vla_folded_to_constant
);
6671 T
= FixedTInfo
->getType();
6676 Diag(Loc
, diag::err_typecheck_negative_array_size
);
6677 else if (Oversized
.getBoolValue())
6678 Diag(Loc
, diag::err_array_too_large
) << toString(Oversized
, 10);
6679 else if (FailedFoldDiagID
)
6680 Diag(Loc
, FailedFoldDiagID
);
6684 /// Register the given locally-scoped extern "C" declaration so
6685 /// that it can be found later for redeclarations. We include any extern "C"
6686 /// declaration that is not visible in the translation unit here, not just
6687 /// function-scope declarations.
6689 Sema::RegisterLocallyScopedExternCDecl(NamedDecl
*ND
, Scope
*S
) {
6690 if (!getLangOpts().CPlusPlus
&&
6691 ND
->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6692 // Don't need to track declarations in the TU in C.
6695 // Note that we have a locally-scoped external with this name.
6696 Context
.getExternCContextDecl()->makeDeclVisibleInContext(ND
);
6699 NamedDecl
*Sema::findLocallyScopedExternCDecl(DeclarationName Name
) {
6700 // FIXME: We can have multiple results via __attribute__((overloadable)).
6701 auto Result
= Context
.getExternCContextDecl()->lookup(Name
);
6702 return Result
.empty() ? nullptr : *Result
.begin();
6705 /// Diagnose function specifiers on a declaration of an identifier that
6706 /// does not identify a function.
6707 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec
&DS
) {
6708 // FIXME: We should probably indicate the identifier in question to avoid
6709 // confusion for constructs like "virtual int a(), b;"
6710 if (DS
.isVirtualSpecified())
6711 Diag(DS
.getVirtualSpecLoc(),
6712 diag::err_virtual_non_function
);
6714 if (DS
.hasExplicitSpecifier())
6715 Diag(DS
.getExplicitSpecLoc(),
6716 diag::err_explicit_non_function
);
6718 if (DS
.isNoreturnSpecified())
6719 Diag(DS
.getNoreturnSpecLoc(),
6720 diag::err_noreturn_non_function
);
6724 Sema::ActOnTypedefDeclarator(Scope
* S
, Declarator
& D
, DeclContext
* DC
,
6725 TypeSourceInfo
*TInfo
, LookupResult
&Previous
) {
6726 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6727 if (D
.getCXXScopeSpec().isSet()) {
6728 Diag(D
.getIdentifierLoc(), diag::err_qualified_typedef_declarator
)
6729 << D
.getCXXScopeSpec().getRange();
6731 // Pretend we didn't see the scope specifier.
6736 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
6738 if (D
.getDeclSpec().isInlineSpecified())
6739 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
6740 << getLangOpts().CPlusPlus17
;
6741 if (D
.getDeclSpec().hasConstexprSpecifier())
6742 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr
)
6743 << 1 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
6745 if (D
.getName().getKind() != UnqualifiedIdKind::IK_Identifier
) {
6746 if (D
.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName
)
6747 Diag(D
.getName().StartLocation
,
6748 diag::err_deduction_guide_invalid_specifier
)
6751 Diag(D
.getName().StartLocation
, diag::err_typedef_not_identifier
)
6752 << D
.getName().getSourceRange();
6756 TypedefDecl
*NewTD
= ParseTypedefDecl(S
, D
, TInfo
->getType(), TInfo
);
6757 if (!NewTD
) return nullptr;
6759 // Handle attributes prior to checking for duplicates in MergeVarDecl
6760 ProcessDeclAttributes(S
, NewTD
, D
);
6762 CheckTypedefForVariablyModifiedType(S
, NewTD
);
6764 bool Redeclaration
= D
.isRedeclaration();
6765 NamedDecl
*ND
= ActOnTypedefNameDecl(S
, DC
, NewTD
, Previous
, Redeclaration
);
6766 D
.setRedeclaration(Redeclaration
);
6771 Sema::CheckTypedefForVariablyModifiedType(Scope
*S
, TypedefNameDecl
*NewTD
) {
6772 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6773 // then it shall have block scope.
6774 // Note that variably modified types must be fixed before merging the decl so
6775 // that redeclarations will match.
6776 TypeSourceInfo
*TInfo
= NewTD
->getTypeSourceInfo();
6777 QualType T
= TInfo
->getType();
6778 if (T
->isVariablyModifiedType()) {
6779 setFunctionHasBranchProtectedScope();
6781 if (S
->getFnParent() == nullptr) {
6782 bool SizeIsNegative
;
6783 llvm::APSInt Oversized
;
6784 TypeSourceInfo
*FixedTInfo
=
6785 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo
, Context
,
6789 Diag(NewTD
->getLocation(), diag::ext_vla_folded_to_constant
);
6790 NewTD
->setTypeSourceInfo(FixedTInfo
);
6793 Diag(NewTD
->getLocation(), diag::err_typecheck_negative_array_size
);
6794 else if (T
->isVariableArrayType())
6795 Diag(NewTD
->getLocation(), diag::err_vla_decl_in_file_scope
);
6796 else if (Oversized
.getBoolValue())
6797 Diag(NewTD
->getLocation(), diag::err_array_too_large
)
6798 << toString(Oversized
, 10);
6800 Diag(NewTD
->getLocation(), diag::err_vm_decl_in_file_scope
);
6801 NewTD
->setInvalidDecl();
6807 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6808 /// declares a typedef-name, either using the 'typedef' type specifier or via
6809 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6811 Sema::ActOnTypedefNameDecl(Scope
*S
, DeclContext
*DC
, TypedefNameDecl
*NewTD
,
6812 LookupResult
&Previous
, bool &Redeclaration
) {
6814 // Find the shadowed declaration before filtering for scope.
6815 NamedDecl
*ShadowedDecl
= getShadowedDeclaration(NewTD
, Previous
);
6817 // Merge the decl with the existing one if appropriate. If the decl is
6818 // in an outer scope, it isn't the same thing.
6819 FilterLookupForScope(Previous
, DC
, S
, /*ConsiderLinkage*/false,
6820 /*AllowInlineNamespace*/false);
6821 filterNonConflictingPreviousTypedefDecls(*this, NewTD
, Previous
);
6822 if (!Previous
.empty()) {
6823 Redeclaration
= true;
6824 MergeTypedefNameDecl(S
, NewTD
, Previous
);
6826 inferGslPointerAttribute(NewTD
);
6829 if (ShadowedDecl
&& !Redeclaration
)
6830 CheckShadow(NewTD
, ShadowedDecl
, Previous
);
6832 // If this is the C FILE type, notify the AST context.
6833 if (IdentifierInfo
*II
= NewTD
->getIdentifier())
6834 if (!NewTD
->isInvalidDecl() &&
6835 NewTD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6836 switch (II
->getInterestingIdentifierID()) {
6837 case tok::InterestingIdentifierKind::FILE:
6838 Context
.setFILEDecl(NewTD
);
6840 case tok::InterestingIdentifierKind::jmp_buf:
6841 Context
.setjmp_bufDecl(NewTD
);
6843 case tok::InterestingIdentifierKind::sigjmp_buf
:
6844 Context
.setsigjmp_bufDecl(NewTD
);
6846 case tok::InterestingIdentifierKind::ucontext_t
:
6847 Context
.setucontext_tDecl(NewTD
);
6849 case tok::InterestingIdentifierKind::float_t
:
6850 case tok::InterestingIdentifierKind::double_t
:
6851 NewTD
->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context
));
6861 /// Determines whether the given declaration is an out-of-scope
6862 /// previous declaration.
6864 /// This routine should be invoked when name lookup has found a
6865 /// previous declaration (PrevDecl) that is not in the scope where a
6866 /// new declaration by the same name is being introduced. If the new
6867 /// declaration occurs in a local scope, previous declarations with
6868 /// linkage may still be considered previous declarations (C99
6869 /// 6.2.2p4-5, C++ [basic.link]p6).
6871 /// \param PrevDecl the previous declaration found by name
6874 /// \param DC the context in which the new declaration is being
6877 /// \returns true if PrevDecl is an out-of-scope previous declaration
6878 /// for a new delcaration with the same name.
6880 isOutOfScopePreviousDeclaration(NamedDecl
*PrevDecl
, DeclContext
*DC
,
6881 ASTContext
&Context
) {
6885 if (!PrevDecl
->hasLinkage())
6888 if (Context
.getLangOpts().CPlusPlus
) {
6889 // C++ [basic.link]p6:
6890 // If there is a visible declaration of an entity with linkage
6891 // having the same name and type, ignoring entities declared
6892 // outside the innermost enclosing namespace scope, the block
6893 // scope declaration declares that same entity and receives the
6894 // linkage of the previous declaration.
6895 DeclContext
*OuterContext
= DC
->getRedeclContext();
6896 if (!OuterContext
->isFunctionOrMethod())
6897 // This rule only applies to block-scope declarations.
6900 DeclContext
*PrevOuterContext
= PrevDecl
->getDeclContext();
6901 if (PrevOuterContext
->isRecord())
6902 // We found a member function: ignore it.
6905 // Find the innermost enclosing namespace for the new and
6906 // previous declarations.
6907 OuterContext
= OuterContext
->getEnclosingNamespaceContext();
6908 PrevOuterContext
= PrevOuterContext
->getEnclosingNamespaceContext();
6910 // The previous declaration is in a different namespace, so it
6911 // isn't the same function.
6912 if (!OuterContext
->Equals(PrevOuterContext
))
6919 static void SetNestedNameSpecifier(Sema
&S
, DeclaratorDecl
*DD
, Declarator
&D
) {
6920 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
6921 if (!SS
.isSet()) return;
6922 DD
->setQualifierInfo(SS
.getWithLocInContext(S
.Context
));
6925 bool Sema::inferObjCARCLifetime(ValueDecl
*decl
) {
6926 QualType type
= decl
->getType();
6927 Qualifiers::ObjCLifetime lifetime
= type
.getObjCLifetime();
6928 if (lifetime
== Qualifiers::OCL_Autoreleasing
) {
6929 // Various kinds of declaration aren't allowed to be __autoreleasing.
6930 unsigned kind
= -1U;
6931 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6932 if (var
->hasAttr
<BlocksAttr
>())
6933 kind
= 0; // __block
6934 else if (!var
->hasLocalStorage())
6936 } else if (isa
<ObjCIvarDecl
>(decl
)) {
6938 } else if (isa
<FieldDecl
>(decl
)) {
6943 Diag(decl
->getLocation(), diag::err_arc_autoreleasing_var
)
6946 } else if (lifetime
== Qualifiers::OCL_None
) {
6947 // Try to infer lifetime.
6948 if (!type
->isObjCLifetimeType())
6951 lifetime
= type
->getObjCARCImplicitLifetime();
6952 type
= Context
.getLifetimeQualifiedType(type
, lifetime
);
6953 decl
->setType(type
);
6956 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6957 // Thread-local variables cannot have lifetime.
6958 if (lifetime
&& lifetime
!= Qualifiers::OCL_ExplicitNone
&&
6959 var
->getTLSKind()) {
6960 Diag(var
->getLocation(), diag::err_arc_thread_ownership
)
6969 void Sema::deduceOpenCLAddressSpace(ValueDecl
*Decl
) {
6970 if (Decl
->getType().hasAddressSpace())
6972 if (Decl
->getType()->isDependentType())
6974 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(Decl
)) {
6975 QualType Type
= Var
->getType();
6976 if (Type
->isSamplerT() || Type
->isVoidType())
6978 LangAS ImplAS
= LangAS::opencl_private
;
6979 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6980 // __opencl_c_program_scope_global_variables feature, the address space
6981 // for a variable at program scope or a static or extern variable inside
6982 // a function are inferred to be __global.
6983 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6984 Var
->hasGlobalStorage())
6985 ImplAS
= LangAS::opencl_global
;
6986 // If the original type from a decayed type is an array type and that array
6987 // type has no address space yet, deduce it now.
6988 if (auto DT
= dyn_cast
<DecayedType
>(Type
)) {
6989 auto OrigTy
= DT
->getOriginalType();
6990 if (!OrigTy
.hasAddressSpace() && OrigTy
->isArrayType()) {
6991 // Add the address space to the original array type and then propagate
6992 // that to the element type through `getAsArrayType`.
6993 OrigTy
= Context
.getAddrSpaceQualType(OrigTy
, ImplAS
);
6994 OrigTy
= QualType(Context
.getAsArrayType(OrigTy
), 0);
6995 // Re-generate the decayed type.
6996 Type
= Context
.getDecayedType(OrigTy
);
6999 Type
= Context
.getAddrSpaceQualType(Type
, ImplAS
);
7000 // Apply any qualifiers (including address space) from the array type to
7001 // the element type. This implements C99 6.7.3p8: "If the specification of
7002 // an array type includes any type qualifiers, the element type is so
7003 // qualified, not the array type."
7004 if (Type
->isArrayType())
7005 Type
= QualType(Context
.getAsArrayType(Type
), 0);
7006 Decl
->setType(Type
);
7010 static void checkAttributesAfterMerging(Sema
&S
, NamedDecl
&ND
) {
7011 // Ensure that an auto decl is deduced otherwise the checks below might cache
7012 // the wrong linkage.
7013 assert(S
.ParsingInitForAutoVars
.count(&ND
) == 0);
7015 // 'weak' only applies to declarations with external linkage.
7016 if (WeakAttr
*Attr
= ND
.getAttr
<WeakAttr
>()) {
7017 if (!ND
.isExternallyVisible()) {
7018 S
.Diag(Attr
->getLocation(), diag::err_attribute_weak_static
);
7019 ND
.dropAttr
<WeakAttr
>();
7022 if (WeakRefAttr
*Attr
= ND
.getAttr
<WeakRefAttr
>()) {
7023 if (ND
.isExternallyVisible()) {
7024 S
.Diag(Attr
->getLocation(), diag::err_attribute_weakref_not_static
);
7025 ND
.dropAttr
<WeakRefAttr
>();
7026 ND
.dropAttr
<AliasAttr
>();
7030 if (auto *VD
= dyn_cast
<VarDecl
>(&ND
)) {
7031 if (VD
->hasInit()) {
7032 if (const auto *Attr
= VD
->getAttr
<AliasAttr
>()) {
7033 assert(VD
->isThisDeclarationADefinition() &&
7034 !VD
->isExternallyVisible() && "Broken AliasAttr handled late!");
7035 S
.Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << VD
<< 0;
7036 VD
->dropAttr
<AliasAttr
>();
7041 // 'selectany' only applies to externally visible variable declarations.
7042 // It does not apply to functions.
7043 if (SelectAnyAttr
*Attr
= ND
.getAttr
<SelectAnyAttr
>()) {
7044 if (isa
<FunctionDecl
>(ND
) || !ND
.isExternallyVisible()) {
7045 S
.Diag(Attr
->getLocation(),
7046 diag::err_attribute_selectany_non_extern_data
);
7047 ND
.dropAttr
<SelectAnyAttr
>();
7051 if (const InheritableAttr
*Attr
= getDLLAttr(&ND
)) {
7052 auto *VD
= dyn_cast
<VarDecl
>(&ND
);
7053 bool IsAnonymousNS
= false;
7054 bool IsMicrosoft
= S
.Context
.getTargetInfo().getCXXABI().isMicrosoft();
7056 const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(VD
->getDeclContext());
7057 while (NS
&& !IsAnonymousNS
) {
7058 IsAnonymousNS
= NS
->isAnonymousNamespace();
7059 NS
= dyn_cast
<NamespaceDecl
>(NS
->getParent());
7062 // dll attributes require external linkage. Static locals may have external
7063 // linkage but still cannot be explicitly imported or exported.
7064 // In Microsoft mode, a variable defined in anonymous namespace must have
7065 // external linkage in order to be exported.
7066 bool AnonNSInMicrosoftMode
= IsAnonymousNS
&& IsMicrosoft
;
7067 if ((ND
.isExternallyVisible() && AnonNSInMicrosoftMode
) ||
7068 (!AnonNSInMicrosoftMode
&&
7069 (!ND
.isExternallyVisible() || (VD
&& VD
->isStaticLocal())))) {
7070 S
.Diag(ND
.getLocation(), diag::err_attribute_dll_not_extern
)
7072 ND
.setInvalidDecl();
7076 // Check the attributes on the function type, if any.
7077 if (const auto *FD
= dyn_cast
<FunctionDecl
>(&ND
)) {
7078 // Don't declare this variable in the second operand of the for-statement;
7079 // GCC miscompiles that by ending its lifetime before evaluating the
7080 // third operand. See gcc.gnu.org/PR86769.
7081 AttributedTypeLoc ATL
;
7082 for (TypeLoc TL
= FD
->getTypeSourceInfo()->getTypeLoc();
7083 (ATL
= TL
.getAsAdjusted
<AttributedTypeLoc
>());
7084 TL
= ATL
.getModifiedLoc()) {
7085 // The [[lifetimebound]] attribute can be applied to the implicit object
7086 // parameter of a non-static member function (other than a ctor or dtor)
7087 // by applying it to the function type.
7088 if (const auto *A
= ATL
.getAttrAs
<LifetimeBoundAttr
>()) {
7089 const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
7090 if (!MD
|| MD
->isStatic()) {
7091 S
.Diag(A
->getLocation(), diag::err_lifetimebound_no_object_param
)
7092 << !MD
<< A
->getRange();
7093 } else if (isa
<CXXConstructorDecl
>(MD
) || isa
<CXXDestructorDecl
>(MD
)) {
7094 S
.Diag(A
->getLocation(), diag::err_lifetimebound_ctor_dtor
)
7095 << isa
<CXXDestructorDecl
>(MD
) << A
->getRange();
7102 static void checkDLLAttributeRedeclaration(Sema
&S
, NamedDecl
*OldDecl
,
7104 bool IsSpecialization
,
7105 bool IsDefinition
) {
7106 if (OldDecl
->isInvalidDecl() || NewDecl
->isInvalidDecl())
7109 bool IsTemplate
= false;
7110 if (TemplateDecl
*OldTD
= dyn_cast
<TemplateDecl
>(OldDecl
)) {
7111 OldDecl
= OldTD
->getTemplatedDecl();
7113 if (!IsSpecialization
)
7114 IsDefinition
= false;
7116 if (TemplateDecl
*NewTD
= dyn_cast
<TemplateDecl
>(NewDecl
)) {
7117 NewDecl
= NewTD
->getTemplatedDecl();
7121 if (!OldDecl
|| !NewDecl
)
7124 const DLLImportAttr
*OldImportAttr
= OldDecl
->getAttr
<DLLImportAttr
>();
7125 const DLLExportAttr
*OldExportAttr
= OldDecl
->getAttr
<DLLExportAttr
>();
7126 const DLLImportAttr
*NewImportAttr
= NewDecl
->getAttr
<DLLImportAttr
>();
7127 const DLLExportAttr
*NewExportAttr
= NewDecl
->getAttr
<DLLExportAttr
>();
7129 // dllimport and dllexport are inheritable attributes so we have to exclude
7130 // inherited attribute instances.
7131 bool HasNewAttr
= (NewImportAttr
&& !NewImportAttr
->isInherited()) ||
7132 (NewExportAttr
&& !NewExportAttr
->isInherited());
7134 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7135 // the only exception being explicit specializations.
7136 // Implicitly generated declarations are also excluded for now because there
7137 // is no other way to switch these to use dllimport or dllexport.
7138 bool AddsAttr
= !(OldImportAttr
|| OldExportAttr
) && HasNewAttr
;
7140 if (AddsAttr
&& !IsSpecialization
&& !OldDecl
->isImplicit()) {
7141 // Allow with a warning for free functions and global variables.
7142 bool JustWarn
= false;
7143 if (!OldDecl
->isCXXClassMember()) {
7144 auto *VD
= dyn_cast
<VarDecl
>(OldDecl
);
7145 if (VD
&& !VD
->getDescribedVarTemplate())
7147 auto *FD
= dyn_cast
<FunctionDecl
>(OldDecl
);
7148 if (FD
&& FD
->getTemplatedKind() == FunctionDecl::TK_NonTemplate
)
7152 // We cannot change a declaration that's been used because IR has already
7153 // been emitted. Dllimported functions will still work though (modulo
7154 // address equality) as they can use the thunk.
7155 if (OldDecl
->isUsed())
7156 if (!isa
<FunctionDecl
>(OldDecl
) || !NewImportAttr
)
7159 unsigned DiagID
= JustWarn
? diag::warn_attribute_dll_redeclaration
7160 : diag::err_attribute_dll_redeclaration
;
7161 S
.Diag(NewDecl
->getLocation(), DiagID
)
7163 << (NewImportAttr
? (const Attr
*)NewImportAttr
: NewExportAttr
);
7164 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7166 NewDecl
->setInvalidDecl();
7171 // A redeclaration is not allowed to drop a dllimport attribute, the only
7172 // exceptions being inline function definitions (except for function
7173 // templates), local extern declarations, qualified friend declarations or
7174 // special MSVC extension: in the last case, the declaration is treated as if
7175 // it were marked dllexport.
7176 bool IsInline
= false, IsStaticDataMember
= false, IsQualifiedFriend
= false;
7177 bool IsMicrosoftABI
= S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols();
7178 if (const auto *VD
= dyn_cast
<VarDecl
>(NewDecl
)) {
7179 // Ignore static data because out-of-line definitions are diagnosed
7181 IsStaticDataMember
= VD
->isStaticDataMember();
7182 IsDefinition
= VD
->isThisDeclarationADefinition(S
.Context
) !=
7183 VarDecl::DeclarationOnly
;
7184 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(NewDecl
)) {
7185 IsInline
= FD
->isInlined();
7186 IsQualifiedFriend
= FD
->getQualifier() &&
7187 FD
->getFriendObjectKind() == Decl::FOK_Declared
;
7190 if (OldImportAttr
&& !HasNewAttr
&&
7191 (!IsInline
|| (IsMicrosoftABI
&& IsTemplate
)) && !IsStaticDataMember
&&
7192 !NewDecl
->isLocalExternDecl() && !IsQualifiedFriend
) {
7193 if (IsMicrosoftABI
&& IsDefinition
) {
7194 if (IsSpecialization
) {
7196 NewDecl
->getLocation(),
7197 diag::err_attribute_dllimport_function_specialization_definition
);
7198 S
.Diag(OldImportAttr
->getLocation(), diag::note_attribute
);
7199 NewDecl
->dropAttr
<DLLImportAttr
>();
7201 S
.Diag(NewDecl
->getLocation(),
7202 diag::warn_redeclaration_without_import_attribute
)
7204 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7205 NewDecl
->dropAttr
<DLLImportAttr
>();
7206 NewDecl
->addAttr(DLLExportAttr::CreateImplicit(
7207 S
.Context
, NewImportAttr
->getRange()));
7209 } else if (IsMicrosoftABI
&& IsSpecialization
) {
7210 assert(!IsDefinition
);
7211 // MSVC allows this. Keep the inherited attribute.
7213 S
.Diag(NewDecl
->getLocation(),
7214 diag::warn_redeclaration_without_attribute_prev_attribute_ignored
)
7215 << NewDecl
<< OldImportAttr
;
7216 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7217 S
.Diag(OldImportAttr
->getLocation(), diag::note_previous_attribute
);
7218 OldDecl
->dropAttr
<DLLImportAttr
>();
7219 NewDecl
->dropAttr
<DLLImportAttr
>();
7221 } else if (IsInline
&& OldImportAttr
&& !IsMicrosoftABI
) {
7222 // In MinGW, seeing a function declared inline drops the dllimport
7224 OldDecl
->dropAttr
<DLLImportAttr
>();
7225 NewDecl
->dropAttr
<DLLImportAttr
>();
7226 S
.Diag(NewDecl
->getLocation(),
7227 diag::warn_dllimport_dropped_from_inline_function
)
7228 << NewDecl
<< OldImportAttr
;
7231 // A specialization of a class template member function is processed here
7232 // since it's a redeclaration. If the parent class is dllexport, the
7233 // specialization inherits that attribute. This doesn't happen automatically
7234 // since the parent class isn't instantiated until later.
7235 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDecl
)) {
7236 if (MD
->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
&&
7237 !NewImportAttr
&& !NewExportAttr
) {
7238 if (const DLLExportAttr
*ParentExportAttr
=
7239 MD
->getParent()->getAttr
<DLLExportAttr
>()) {
7240 DLLExportAttr
*NewAttr
= ParentExportAttr
->clone(S
.Context
);
7241 NewAttr
->setInherited(true);
7242 NewDecl
->addAttr(NewAttr
);
7248 /// Given that we are within the definition of the given function,
7249 /// will that definition behave like C99's 'inline', where the
7250 /// definition is discarded except for optimization purposes?
7251 static bool isFunctionDefinitionDiscarded(Sema
&S
, FunctionDecl
*FD
) {
7252 // Try to avoid calling GetGVALinkageForFunction.
7254 // All cases of this require the 'inline' keyword.
7255 if (!FD
->isInlined()) return false;
7257 // This is only possible in C++ with the gnu_inline attribute.
7258 if (S
.getLangOpts().CPlusPlus
&& !FD
->hasAttr
<GNUInlineAttr
>())
7261 // Okay, go ahead and call the relatively-more-expensive function.
7262 return S
.Context
.GetGVALinkageForFunction(FD
) == GVA_AvailableExternally
;
7265 /// Determine whether a variable is extern "C" prior to attaching
7266 /// an initializer. We can't just call isExternC() here, because that
7267 /// will also compute and cache whether the declaration is externally
7268 /// visible, which might change when we attach the initializer.
7270 /// This can only be used if the declaration is known to not be a
7271 /// redeclaration of an internal linkage declaration.
7277 /// Attaching the initializer here makes this declaration not externally
7278 /// visible, because its type has internal linkage.
7280 /// FIXME: This is a hack.
7281 template<typename T
>
7282 static bool isIncompleteDeclExternC(Sema
&S
, const T
*D
) {
7283 if (S
.getLangOpts().CPlusPlus
) {
7284 // In C++, the overloadable attribute negates the effects of extern "C".
7285 if (!D
->isInExternCContext() || D
->template hasAttr
<OverloadableAttr
>())
7288 // So do CUDA's host/device attributes.
7289 if (S
.getLangOpts().CUDA
&& (D
->template hasAttr
<CUDADeviceAttr
>() ||
7290 D
->template hasAttr
<CUDAHostAttr
>()))
7293 return D
->isExternC();
7296 static bool shouldConsiderLinkage(const VarDecl
*VD
) {
7297 const DeclContext
*DC
= VD
->getDeclContext()->getRedeclContext();
7298 if (DC
->isFunctionOrMethod() || isa
<OMPDeclareReductionDecl
>(DC
) ||
7299 isa
<OMPDeclareMapperDecl
>(DC
))
7300 return VD
->hasExternalStorage();
7301 if (DC
->isFileContext())
7305 if (DC
->getDeclKind() == Decl::HLSLBuffer
)
7308 if (isa
<RequiresExprBodyDecl
>(DC
))
7310 llvm_unreachable("Unexpected context");
7313 static bool shouldConsiderLinkage(const FunctionDecl
*FD
) {
7314 const DeclContext
*DC
= FD
->getDeclContext()->getRedeclContext();
7315 if (DC
->isFileContext() || DC
->isFunctionOrMethod() ||
7316 isa
<OMPDeclareReductionDecl
>(DC
) || isa
<OMPDeclareMapperDecl
>(DC
))
7320 llvm_unreachable("Unexpected context");
7323 static bool hasParsedAttr(Scope
*S
, const Declarator
&PD
,
7324 ParsedAttr::Kind Kind
) {
7325 // Check decl attributes on the DeclSpec.
7326 if (PD
.getDeclSpec().getAttributes().hasAttribute(Kind
))
7329 // Walk the declarator structure, checking decl attributes that were in a type
7330 // position to the decl itself.
7331 for (unsigned I
= 0, E
= PD
.getNumTypeObjects(); I
!= E
; ++I
) {
7332 if (PD
.getTypeObject(I
).getAttrs().hasAttribute(Kind
))
7336 // Finally, check attributes on the decl itself.
7337 return PD
.getAttributes().hasAttribute(Kind
) ||
7338 PD
.getDeclarationAttributes().hasAttribute(Kind
);
7341 /// Adjust the \c DeclContext for a function or variable that might be a
7342 /// function-local external declaration.
7343 bool Sema::adjustContextForLocalExternDecl(DeclContext
*&DC
) {
7344 if (!DC
->isFunctionOrMethod())
7347 // If this is a local extern function or variable declared within a function
7348 // template, don't add it into the enclosing namespace scope until it is
7349 // instantiated; it might have a dependent type right now.
7350 if (DC
->isDependentContext())
7353 // C++11 [basic.link]p7:
7354 // When a block scope declaration of an entity with linkage is not found to
7355 // refer to some other declaration, then that entity is a member of the
7356 // innermost enclosing namespace.
7358 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7359 // semantically-enclosing namespace, not a lexically-enclosing one.
7360 while (!DC
->isFileContext() && !isa
<LinkageSpecDecl
>(DC
))
7361 DC
= DC
->getParent();
7365 /// Returns true if given declaration has external C language linkage.
7366 static bool isDeclExternC(const Decl
*D
) {
7367 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
7368 return FD
->isExternC();
7369 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
7370 return VD
->isExternC();
7372 llvm_unreachable("Unknown type of decl!");
7375 /// Returns true if there hasn't been any invalid type diagnosed.
7376 static bool diagnoseOpenCLTypes(Sema
&Se
, VarDecl
*NewVD
) {
7377 DeclContext
*DC
= NewVD
->getDeclContext();
7378 QualType R
= NewVD
->getType();
7380 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7381 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7383 if (R
->isImageType() || R
->isPipeType()) {
7384 Se
.Diag(NewVD
->getLocation(),
7385 diag::err_opencl_type_can_only_be_used_as_function_parameter
)
7387 NewVD
->setInvalidDecl();
7391 // OpenCL v1.2 s6.9.r:
7392 // The event type cannot be used to declare a program scope variable.
7393 // OpenCL v2.0 s6.9.q:
7394 // The clk_event_t and reserve_id_t types cannot be declared in program
7396 if (NewVD
->hasGlobalStorage() && !NewVD
->isStaticLocal()) {
7397 if (R
->isReserveIDT() || R
->isClkEventT() || R
->isEventT()) {
7398 Se
.Diag(NewVD
->getLocation(),
7399 diag::err_invalid_type_for_program_scope_var
)
7401 NewVD
->setInvalidDecl();
7406 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7407 if (!Se
.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7408 Se
.getLangOpts())) {
7409 QualType NR
= R
.getCanonicalType();
7410 while (NR
->isPointerType() || NR
->isMemberFunctionPointerType() ||
7411 NR
->isReferenceType()) {
7412 if (NR
->isFunctionPointerType() || NR
->isMemberFunctionPointerType() ||
7413 NR
->isFunctionReferenceType()) {
7414 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_function_pointer
)
7415 << NR
->isReferenceType();
7416 NewVD
->setInvalidDecl();
7419 NR
= NR
->getPointeeType();
7423 if (!Se
.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7424 Se
.getLangOpts())) {
7425 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7426 // half array type (unless the cl_khr_fp16 extension is enabled).
7427 if (Se
.Context
.getBaseElementType(R
)->isHalfType()) {
7428 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_half_declaration
) << R
;
7429 NewVD
->setInvalidDecl();
7434 // OpenCL v1.2 s6.9.r:
7435 // The event type cannot be used with the __local, __constant and __global
7436 // address space qualifiers.
7437 if (R
->isEventT()) {
7438 if (R
.getAddressSpace() != LangAS::opencl_private
) {
7439 Se
.Diag(NewVD
->getBeginLoc(), diag::err_event_t_addr_space_qual
);
7440 NewVD
->setInvalidDecl();
7445 if (R
->isSamplerT()) {
7446 // OpenCL v1.2 s6.9.b p4:
7447 // The sampler type cannot be used with the __local and __global address
7448 // space qualifiers.
7449 if (R
.getAddressSpace() == LangAS::opencl_local
||
7450 R
.getAddressSpace() == LangAS::opencl_global
) {
7451 Se
.Diag(NewVD
->getLocation(), diag::err_wrong_sampler_addressspace
);
7452 NewVD
->setInvalidDecl();
7455 // OpenCL v1.2 s6.12.14.1:
7456 // A global sampler must be declared with either the constant address
7457 // space qualifier or with the const qualifier.
7458 if (DC
->isTranslationUnit() &&
7459 !(R
.getAddressSpace() == LangAS::opencl_constant
||
7460 R
.isConstQualified())) {
7461 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_nonconst_global_sampler
);
7462 NewVD
->setInvalidDecl();
7464 if (NewVD
->isInvalidDecl())
7471 template <typename AttrTy
>
7472 static void copyAttrFromTypedefToDecl(Sema
&S
, Decl
*D
, const TypedefType
*TT
) {
7473 const TypedefNameDecl
*TND
= TT
->getDecl();
7474 if (const auto *Attribute
= TND
->getAttr
<AttrTy
>()) {
7475 AttrTy
*Clone
= Attribute
->clone(S
.Context
);
7476 Clone
->setInherited(true);
7481 // This function emits warning and a corresponding note based on the
7482 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7483 // declarations of an annotated type must be const qualified.
7484 void emitReadOnlyPlacementAttrWarning(Sema
&S
, const VarDecl
*VD
) {
7485 QualType VarType
= VD
->getType().getCanonicalType();
7487 // Ignore local declarations (for now) and those with const qualification.
7488 // TODO: Local variables should not be allowed if their type declaration has
7489 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7490 if (!VD
|| VD
->hasLocalStorage() || VD
->getType().isConstQualified())
7493 if (VarType
->isArrayType()) {
7494 // Retrieve element type for array declarations.
7495 VarType
= S
.getASTContext().getBaseElementType(VarType
);
7498 const RecordDecl
*RD
= VarType
->getAsRecordDecl();
7500 // Check if the record declaration is present and if it has any attributes.
7504 if (const auto *ConstDecl
= RD
->getAttr
<ReadOnlyPlacementAttr
>()) {
7505 S
.Diag(VD
->getLocation(), diag::warn_var_decl_not_read_only
) << RD
;
7506 S
.Diag(ConstDecl
->getLocation(), diag::note_enforce_read_only_placement
);
7511 NamedDecl
*Sema::ActOnVariableDeclarator(
7512 Scope
*S
, Declarator
&D
, DeclContext
*DC
, TypeSourceInfo
*TInfo
,
7513 LookupResult
&Previous
, MultiTemplateParamsArg TemplateParamLists
,
7514 bool &AddToScope
, ArrayRef
<BindingDecl
*> Bindings
) {
7515 QualType R
= TInfo
->getType();
7516 DeclarationName Name
= GetNameForDeclarator(D
).getName();
7518 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
7519 bool IsPlaceholderVariable
= false;
7521 if (D
.isDecompositionDeclarator()) {
7522 // Take the name of the first declarator as our name for diagnostic
7524 auto &Decomp
= D
.getDecompositionDeclarator();
7525 if (!Decomp
.bindings().empty()) {
7526 II
= Decomp
.bindings()[0].Name
;
7530 Diag(D
.getIdentifierLoc(), diag::err_bad_variable_name
) << Name
;
7535 DeclSpec::SCS SCSpec
= D
.getDeclSpec().getStorageClassSpec();
7536 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(D
.getDeclSpec());
7538 if (LangOpts
.CPlusPlus
&& (DC
->isClosure() || DC
->isFunctionOrMethod()) &&
7539 SC
!= SC_Static
&& SC
!= SC_Extern
&& II
&& II
->isPlaceholder()) {
7540 IsPlaceholderVariable
= true;
7541 if (!Previous
.empty()) {
7542 NamedDecl
*PrevDecl
= *Previous
.begin();
7543 bool SameDC
= PrevDecl
->getDeclContext()->getRedeclContext()->Equals(
7544 DC
->getRedeclContext());
7545 if (SameDC
&& isDeclInScope(PrevDecl
, CurContext
, S
, false))
7546 DiagPlaceholderVariableDefinition(D
.getIdentifierLoc());
7550 // dllimport globals without explicit storage class are treated as extern. We
7551 // have to change the storage class this early to get the right DeclContext.
7552 if (SC
== SC_None
&& !DC
->isRecord() &&
7553 hasParsedAttr(S
, D
, ParsedAttr::AT_DLLImport
) &&
7554 !hasParsedAttr(S
, D
, ParsedAttr::AT_DLLExport
))
7557 DeclContext
*OriginalDC
= DC
;
7558 bool IsLocalExternDecl
= SC
== SC_Extern
&&
7559 adjustContextForLocalExternDecl(DC
);
7561 if (SCSpec
== DeclSpec::SCS_mutable
) {
7562 // mutable can only appear on non-static class members, so it's always
7564 Diag(D
.getIdentifierLoc(), diag::err_mutable_nonmember
);
7569 if (getLangOpts().CPlusPlus11
&& SCSpec
== DeclSpec::SCS_register
&&
7570 !D
.getAsmLabel() && !getSourceManager().isInSystemMacro(
7571 D
.getDeclSpec().getStorageClassSpecLoc())) {
7572 // In C++11, the 'register' storage class specifier is deprecated.
7573 // Suppress the warning in system macros, it's used in macros in some
7574 // popular C system headers, such as in glibc's htonl() macro.
7575 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7576 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
7577 : diag::warn_deprecated_register
)
7578 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7581 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
7583 if (!DC
->isRecord() && S
->getFnParent() == nullptr) {
7584 // C99 6.9p2: The storage-class specifiers auto and register shall not
7585 // appear in the declaration specifiers in an external declaration.
7586 // Global Register+Asm is a GNU extension we support.
7587 if (SC
== SC_Auto
|| (SC
== SC_Register
&& !D
.getAsmLabel())) {
7588 Diag(D
.getIdentifierLoc(), diag::err_typecheck_sclass_fscope
);
7593 // If this variable has a VLA type and an initializer, try to
7594 // fold to a constant-sized type. This is otherwise invalid.
7595 if (D
.hasInitializer() && R
->isVariableArrayType())
7596 tryToFixVariablyModifiedVarType(TInfo
, R
, D
.getIdentifierLoc(),
7599 bool IsMemberSpecialization
= false;
7600 bool IsVariableTemplateSpecialization
= false;
7601 bool IsPartialSpecialization
= false;
7602 bool IsVariableTemplate
= false;
7603 VarDecl
*NewVD
= nullptr;
7604 VarTemplateDecl
*NewTemplate
= nullptr;
7605 TemplateParameterList
*TemplateParams
= nullptr;
7606 if (!getLangOpts().CPlusPlus
) {
7607 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(),
7610 if (R
->getContainedDeducedType())
7611 ParsingInitForAutoVars
.insert(NewVD
);
7613 if (D
.isInvalidType())
7614 NewVD
->setInvalidDecl();
7616 if (NewVD
->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7617 NewVD
->hasLocalStorage())
7618 checkNonTrivialCUnion(NewVD
->getType(), NewVD
->getLocation(),
7619 NTCUC_AutoVar
, NTCUK_Destruct
);
7621 bool Invalid
= false;
7623 if (DC
->isRecord() && !CurContext
->isRecord()) {
7624 // This is an out-of-line definition of a static data member.
7629 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7630 diag::err_static_out_of_line
)
7631 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7636 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7637 // to names of variables declared in a block or to function parameters.
7638 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7641 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7642 diag::err_storage_class_for_static_member
)
7643 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7645 case SC_PrivateExtern
:
7646 llvm_unreachable("C storage class in c++!");
7650 if (SC
== SC_Static
&& CurContext
->isRecord()) {
7651 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
7652 // Walk up the enclosing DeclContexts to check for any that are
7653 // incompatible with static data members.
7654 const DeclContext
*FunctionOrMethod
= nullptr;
7655 const CXXRecordDecl
*AnonStruct
= nullptr;
7656 for (DeclContext
*Ctxt
= DC
; Ctxt
; Ctxt
= Ctxt
->getParent()) {
7657 if (Ctxt
->isFunctionOrMethod()) {
7658 FunctionOrMethod
= Ctxt
;
7661 const CXXRecordDecl
*ParentDecl
= dyn_cast
<CXXRecordDecl
>(Ctxt
);
7662 if (ParentDecl
&& !ParentDecl
->getDeclName()) {
7663 AnonStruct
= ParentDecl
;
7667 if (FunctionOrMethod
) {
7668 // C++ [class.static.data]p5: A local class shall not have static data
7670 Diag(D
.getIdentifierLoc(),
7671 diag::err_static_data_member_not_allowed_in_local_class
)
7672 << Name
<< RD
->getDeclName() << RD
->getTagKind();
7673 } else if (AnonStruct
) {
7674 // C++ [class.static.data]p4: Unnamed classes and classes contained
7675 // directly or indirectly within unnamed classes shall not contain
7676 // static data members.
7677 Diag(D
.getIdentifierLoc(),
7678 diag::err_static_data_member_not_allowed_in_anon_struct
)
7679 << Name
<< AnonStruct
->getTagKind();
7681 } else if (RD
->isUnion()) {
7682 // C++98 [class.union]p1: If a union contains a static data member,
7683 // the program is ill-formed. C++11 drops this restriction.
7684 Diag(D
.getIdentifierLoc(),
7685 getLangOpts().CPlusPlus11
7686 ? diag::warn_cxx98_compat_static_data_member_in_union
7687 : diag::ext_static_data_member_in_union
) << Name
;
7692 // Match up the template parameter lists with the scope specifier, then
7693 // determine whether we have a template or a template specialization.
7694 bool InvalidScope
= false;
7695 TemplateParams
= MatchTemplateParametersToScopeSpecifier(
7696 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
7697 D
.getCXXScopeSpec(),
7698 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7699 ? D
.getName().TemplateId
7702 /*never a friend*/ false, IsMemberSpecialization
, InvalidScope
);
7703 Invalid
|= InvalidScope
;
7705 if (TemplateParams
) {
7706 if (!TemplateParams
->size() &&
7707 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
7708 // There is an extraneous 'template<>' for this variable. Complain
7709 // about it, but allow the declaration of the variable.
7710 Diag(TemplateParams
->getTemplateLoc(),
7711 diag::err_template_variable_noparams
)
7713 << SourceRange(TemplateParams
->getTemplateLoc(),
7714 TemplateParams
->getRAngleLoc());
7715 TemplateParams
= nullptr;
7717 // Check that we can declare a template here.
7718 if (CheckTemplateDeclScope(S
, TemplateParams
))
7721 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
7722 // This is an explicit specialization or a partial specialization.
7723 IsVariableTemplateSpecialization
= true;
7724 IsPartialSpecialization
= TemplateParams
->size() > 0;
7725 } else { // if (TemplateParams->size() > 0)
7726 // This is a template declaration.
7727 IsVariableTemplate
= true;
7729 // Only C++1y supports variable templates (N3651).
7730 Diag(D
.getIdentifierLoc(),
7731 getLangOpts().CPlusPlus14
7732 ? diag::warn_cxx11_compat_variable_template
7733 : diag::ext_variable_template
);
7737 // Check that we can declare a member specialization here.
7738 if (!TemplateParamLists
.empty() && IsMemberSpecialization
&&
7739 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
7742 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) &&
7743 "should have a 'template<>' for this decl");
7746 if (IsVariableTemplateSpecialization
) {
7747 SourceLocation TemplateKWLoc
=
7748 TemplateParamLists
.size() > 0
7749 ? TemplateParamLists
[0]->getTemplateLoc()
7751 DeclResult Res
= ActOnVarTemplateSpecialization(
7752 S
, D
, TInfo
, TemplateKWLoc
, TemplateParams
, SC
,
7753 IsPartialSpecialization
);
7754 if (Res
.isInvalid())
7756 NewVD
= cast
<VarDecl
>(Res
.get());
7758 } else if (D
.isDecompositionDeclarator()) {
7759 NewVD
= DecompositionDecl::Create(Context
, DC
, D
.getBeginLoc(),
7760 D
.getIdentifierLoc(), R
, TInfo
, SC
,
7763 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(),
7764 D
.getIdentifierLoc(), II
, R
, TInfo
, SC
);
7766 // If this is supposed to be a variable template, create it as such.
7767 if (IsVariableTemplate
) {
7769 VarTemplateDecl::Create(Context
, DC
, D
.getIdentifierLoc(), Name
,
7770 TemplateParams
, NewVD
);
7771 NewVD
->setDescribedVarTemplate(NewTemplate
);
7774 // If this decl has an auto type in need of deduction, make a note of the
7775 // Decl so we can diagnose uses of it in its own initializer.
7776 if (R
->getContainedDeducedType())
7777 ParsingInitForAutoVars
.insert(NewVD
);
7779 if (D
.isInvalidType() || Invalid
) {
7780 NewVD
->setInvalidDecl();
7782 NewTemplate
->setInvalidDecl();
7785 SetNestedNameSpecifier(*this, NewVD
, D
);
7787 // If we have any template parameter lists that don't directly belong to
7788 // the variable (matching the scope specifier), store them.
7789 // An explicit variable template specialization does not own any template
7791 bool IsExplicitSpecialization
=
7792 IsVariableTemplateSpecialization
&& !IsPartialSpecialization
;
7793 unsigned VDTemplateParamLists
=
7794 (TemplateParams
&& !IsExplicitSpecialization
) ? 1 : 0;
7795 if (TemplateParamLists
.size() > VDTemplateParamLists
)
7796 NewVD
->setTemplateParameterListsInfo(
7797 Context
, TemplateParamLists
.drop_back(VDTemplateParamLists
));
7800 if (D
.getDeclSpec().isInlineSpecified()) {
7801 if (!getLangOpts().CPlusPlus
) {
7802 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
7804 } else if (CurContext
->isFunctionOrMethod()) {
7805 // 'inline' is not allowed on block scope variable declaration.
7806 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7807 diag::err_inline_declaration_block_scope
) << Name
7808 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
7810 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7811 getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_inline_variable
7812 : diag::ext_inline_variable
);
7813 NewVD
->setInlineSpecified();
7817 // Set the lexical context. If the declarator has a C++ scope specifier, the
7818 // lexical context will be different from the semantic context.
7819 NewVD
->setLexicalDeclContext(CurContext
);
7821 NewTemplate
->setLexicalDeclContext(CurContext
);
7823 if (IsLocalExternDecl
) {
7824 if (D
.isDecompositionDeclarator())
7825 for (auto *B
: Bindings
)
7826 B
->setLocalExternDecl();
7828 NewVD
->setLocalExternDecl();
7831 bool EmitTLSUnsupportedError
= false;
7832 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec()) {
7833 // C++11 [dcl.stc]p4:
7834 // When thread_local is applied to a variable of block scope the
7835 // storage-class-specifier static is implied if it does not appear
7837 // Core issue: 'static' is not implied if the variable is declared
7839 if (NewVD
->hasLocalStorage() &&
7840 (SCSpec
!= DeclSpec::SCS_unspecified
||
7841 TSCS
!= DeclSpec::TSCS_thread_local
||
7842 !DC
->isFunctionOrMethod()))
7843 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7844 diag::err_thread_non_global
)
7845 << DeclSpec::getSpecifierName(TSCS
);
7846 else if (!Context
.getTargetInfo().isTLSSupported()) {
7847 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsTargetDevice
||
7848 getLangOpts().SYCLIsDevice
) {
7849 // Postpone error emission until we've collected attributes required to
7850 // figure out whether it's a host or device variable and whether the
7851 // error should be ignored.
7852 EmitTLSUnsupportedError
= true;
7853 // We still need to mark the variable as TLS so it shows up in AST with
7854 // proper storage class for other tools to use even if we're not going
7855 // to emit any code for it.
7856 NewVD
->setTSCSpec(TSCS
);
7858 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7859 diag::err_thread_unsupported
);
7861 NewVD
->setTSCSpec(TSCS
);
7864 switch (D
.getDeclSpec().getConstexprSpecifier()) {
7865 case ConstexprSpecKind::Unspecified
:
7868 case ConstexprSpecKind::Consteval
:
7869 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7870 diag::err_constexpr_wrong_decl_kind
)
7871 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
7874 case ConstexprSpecKind::Constexpr
:
7875 NewVD
->setConstexpr(true);
7876 // C++1z [dcl.spec.constexpr]p1:
7877 // A static data member declared with the constexpr specifier is
7878 // implicitly an inline variable.
7879 if (NewVD
->isStaticDataMember() &&
7880 (getLangOpts().CPlusPlus17
||
7881 Context
.getTargetInfo().getCXXABI().isMicrosoft()))
7882 NewVD
->setImplicitlyInline();
7885 case ConstexprSpecKind::Constinit
:
7886 if (!NewVD
->hasGlobalStorage())
7887 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7888 diag::err_constinit_local_variable
);
7891 ConstInitAttr::Create(Context
, D
.getDeclSpec().getConstexprSpecLoc(),
7892 ConstInitAttr::Keyword_constinit
));
7897 // An inline definition of a function with external linkage shall
7898 // not contain a definition of a modifiable object with static or
7899 // thread storage duration...
7900 // We only apply this when the function is required to be defined
7901 // elsewhere, i.e. when the function is not 'extern inline'. Note
7902 // that a local variable with thread storage duration still has to
7903 // be marked 'static'. Also note that it's possible to get these
7904 // semantics in C++ using __attribute__((gnu_inline)).
7905 if (SC
== SC_Static
&& S
->getFnParent() != nullptr &&
7906 !NewVD
->getType().isConstQualified()) {
7907 FunctionDecl
*CurFD
= getCurFunctionDecl();
7908 if (CurFD
&& isFunctionDefinitionDiscarded(*this, CurFD
)) {
7909 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7910 diag::warn_static_local_in_extern_inline
);
7911 MaybeSuggestAddingStaticToDecl(CurFD
);
7915 if (D
.getDeclSpec().isModulePrivateSpecified()) {
7916 if (IsVariableTemplateSpecialization
)
7917 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7918 << (IsPartialSpecialization
? 1 : 0)
7919 << FixItHint::CreateRemoval(
7920 D
.getDeclSpec().getModulePrivateSpecLoc());
7921 else if (IsMemberSpecialization
)
7922 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7924 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
7925 else if (NewVD
->hasLocalStorage())
7926 Diag(NewVD
->getLocation(), diag::err_module_private_local
)
7928 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
7929 << FixItHint::CreateRemoval(
7930 D
.getDeclSpec().getModulePrivateSpecLoc());
7932 NewVD
->setModulePrivate();
7934 NewTemplate
->setModulePrivate();
7935 for (auto *B
: Bindings
)
7936 B
->setModulePrivate();
7940 if (getLangOpts().OpenCL
) {
7941 deduceOpenCLAddressSpace(NewVD
);
7943 DeclSpec::TSCS TSC
= D
.getDeclSpec().getThreadStorageClassSpec();
7944 if (TSC
!= TSCS_unspecified
) {
7945 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7946 diag::err_opencl_unknown_type_specifier
)
7947 << getLangOpts().getOpenCLVersionString()
7948 << DeclSpec::getSpecifierName(TSC
) << 1;
7949 NewVD
->setInvalidDecl();
7953 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7954 // address space if the table has local storage (semantic checks elsewhere
7955 // will produce an error anyway).
7956 if (const auto *ATy
= dyn_cast
<ArrayType
>(NewVD
->getType())) {
7957 if (ATy
&& ATy
->getElementType().isWebAssemblyReferenceType() &&
7958 !NewVD
->hasLocalStorage()) {
7959 QualType Type
= Context
.getAddrSpaceQualType(
7960 NewVD
->getType(), Context
.getLangASForBuiltinAddressSpace(1));
7961 NewVD
->setType(Type
);
7965 // Handle attributes prior to checking for duplicates in MergeVarDecl
7966 ProcessDeclAttributes(S
, NewVD
, D
);
7968 // FIXME: This is probably the wrong location to be doing this and we should
7969 // probably be doing this for more attributes (especially for function
7970 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7971 // the code to copy attributes would be generated by TableGen.
7972 if (R
->isFunctionPointerType())
7973 if (const auto *TT
= R
->getAs
<TypedefType
>())
7974 copyAttrFromTypedefToDecl
<AllocSizeAttr
>(*this, NewVD
, TT
);
7976 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsTargetDevice
||
7977 getLangOpts().SYCLIsDevice
) {
7978 if (EmitTLSUnsupportedError
&&
7979 ((getLangOpts().CUDA
&& DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) ||
7980 (getLangOpts().OpenMPIsTargetDevice
&&
7981 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD
))))
7982 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7983 diag::err_thread_unsupported
);
7985 if (EmitTLSUnsupportedError
&&
7986 (LangOpts
.SYCLIsDevice
||
7987 (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
)))
7988 targetDiag(D
.getIdentifierLoc(), diag::err_thread_unsupported
);
7989 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7990 // storage [duration]."
7991 if (SC
== SC_None
&& S
->getFnParent() != nullptr &&
7992 (NewVD
->hasAttr
<CUDASharedAttr
>() ||
7993 NewVD
->hasAttr
<CUDAConstantAttr
>())) {
7994 NewVD
->setStorageClass(SC_Static
);
7998 // Ensure that dllimport globals without explicit storage class are treated as
7999 // extern. The storage class is set above using parsed attributes. Now we can
8000 // check the VarDecl itself.
8001 assert(!NewVD
->hasAttr
<DLLImportAttr
>() ||
8002 NewVD
->getAttr
<DLLImportAttr
>()->isInherited() ||
8003 NewVD
->isStaticDataMember() || NewVD
->getStorageClass() != SC_None
);
8005 // In auto-retain/release, infer strong retension for variables of
8007 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewVD
))
8008 NewVD
->setInvalidDecl();
8010 // Handle GNU asm-label extension (encoded as an attribute).
8011 if (Expr
*E
= (Expr
*)D
.getAsmLabel()) {
8012 // The parser guarantees this is a string.
8013 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
8014 StringRef Label
= SE
->getString();
8015 if (S
->getFnParent() != nullptr) {
8019 Diag(E
->getExprLoc(), diag::warn_asm_label_on_auto_decl
) << Label
;
8022 // Local Named register
8023 if (!Context
.getTargetInfo().isValidGCCRegisterName(Label
) &&
8024 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8025 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
8029 case SC_PrivateExtern
:
8032 } else if (SC
== SC_Register
) {
8033 // Global Named register
8034 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) {
8035 const auto &TI
= Context
.getTargetInfo();
8036 bool HasSizeMismatch
;
8038 if (!TI
.isValidGCCRegisterName(Label
))
8039 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
8040 else if (!TI
.validateGlobalRegisterVariable(Label
,
8041 Context
.getTypeSize(R
),
8043 Diag(E
->getExprLoc(), diag::err_asm_invalid_global_var_reg
) << Label
;
8044 else if (HasSizeMismatch
)
8045 Diag(E
->getExprLoc(), diag::err_asm_register_size_mismatch
) << Label
;
8048 if (!R
->isIntegralType(Context
) && !R
->isPointerType()) {
8049 Diag(D
.getBeginLoc(), diag::err_asm_bad_register_type
);
8050 NewVD
->setInvalidDecl(true);
8054 NewVD
->addAttr(AsmLabelAttr::Create(Context
, Label
,
8055 /*IsLiteralLabel=*/true,
8056 SE
->getStrTokenLoc(0)));
8057 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
8058 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
8059 ExtnameUndeclaredIdentifiers
.find(NewVD
->getIdentifier());
8060 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
8061 if (isDeclExternC(NewVD
)) {
8062 NewVD
->addAttr(I
->second
);
8063 ExtnameUndeclaredIdentifiers
.erase(I
);
8065 Diag(NewVD
->getLocation(), diag::warn_redefine_extname_not_applied
)
8066 << /*Variable*/1 << NewVD
;
8070 // Find the shadowed declaration before filtering for scope.
8071 NamedDecl
*ShadowedDecl
= D
.getCXXScopeSpec().isEmpty()
8072 ? getShadowedDeclaration(NewVD
, Previous
)
8075 // Don't consider existing declarations that are in a different
8076 // scope and are out-of-semantic-context declarations (if the new
8077 // declaration has linkage).
8078 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewVD
),
8079 D
.getCXXScopeSpec().isNotEmpty() ||
8080 IsMemberSpecialization
||
8081 IsVariableTemplateSpecialization
);
8083 // Check whether the previous declaration is in the same block scope. This
8084 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8085 if (getLangOpts().CPlusPlus
&&
8086 NewVD
->isLocalVarDecl() && NewVD
->hasExternalStorage())
8087 NewVD
->setPreviousDeclInSameBlockScope(
8088 Previous
.isSingleResult() && !Previous
.isShadowed() &&
8089 isDeclInScope(Previous
.getFoundDecl(), OriginalDC
, S
, false));
8091 if (!getLangOpts().CPlusPlus
) {
8092 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
8094 // If this is an explicit specialization of a static data member, check it.
8095 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl() &&
8096 CheckMemberSpecialization(NewVD
, Previous
))
8097 NewVD
->setInvalidDecl();
8099 // Merge the decl with the existing one if appropriate.
8100 if (!Previous
.empty()) {
8101 if (Previous
.isSingleResult() &&
8102 isa
<FieldDecl
>(Previous
.getFoundDecl()) &&
8103 D
.getCXXScopeSpec().isSet()) {
8104 // The user tried to define a non-static data member
8105 // out-of-line (C++ [dcl.meaning]p1).
8106 Diag(NewVD
->getLocation(), diag::err_nonstatic_member_out_of_line
)
8107 << D
.getCXXScopeSpec().getRange();
8109 NewVD
->setInvalidDecl();
8111 } else if (D
.getCXXScopeSpec().isSet()) {
8112 // No previous declaration in the qualifying scope.
8113 Diag(D
.getIdentifierLoc(), diag::err_no_member
)
8114 << Name
<< computeDeclContext(D
.getCXXScopeSpec(), true)
8115 << D
.getCXXScopeSpec().getRange();
8116 NewVD
->setInvalidDecl();
8119 if (!IsVariableTemplateSpecialization
&& !IsPlaceholderVariable
)
8120 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
8122 // CheckVariableDeclaration will set NewVD as invalid if something is in
8123 // error like WebAssembly tables being declared as arrays with a non-zero
8124 // size, but then parsing continues and emits further errors on that line.
8125 // To avoid that we check here if it happened and return nullptr.
8126 if (NewVD
->getType()->isWebAssemblyTableType() && NewVD
->isInvalidDecl())
8130 VarTemplateDecl
*PrevVarTemplate
=
8131 NewVD
->getPreviousDecl()
8132 ? NewVD
->getPreviousDecl()->getDescribedVarTemplate()
8135 // Check the template parameter list of this declaration, possibly
8136 // merging in the template parameter list from the previous variable
8137 // template declaration.
8138 if (CheckTemplateParameterList(
8140 PrevVarTemplate
? PrevVarTemplate
->getTemplateParameters()
8142 (D
.getCXXScopeSpec().isSet() && DC
&& DC
->isRecord() &&
8143 DC
->isDependentContext())
8144 ? TPC_ClassTemplateMember
8146 NewVD
->setInvalidDecl();
8148 // If we are providing an explicit specialization of a static variable
8149 // template, make a note of that.
8150 if (PrevVarTemplate
&&
8151 PrevVarTemplate
->getInstantiatedFromMemberTemplate())
8152 PrevVarTemplate
->setMemberSpecialization();
8156 // Diagnose shadowed variables iff this isn't a redeclaration.
8157 if (!IsPlaceholderVariable
&& ShadowedDecl
&& !D
.isRedeclaration())
8158 CheckShadow(NewVD
, ShadowedDecl
, Previous
);
8160 ProcessPragmaWeak(S
, NewVD
);
8162 // If this is the first declaration of an extern C variable, update
8163 // the map of such variables.
8164 if (NewVD
->isFirstDecl() && !NewVD
->isInvalidDecl() &&
8165 isIncompleteDeclExternC(*this, NewVD
))
8166 RegisterLocallyScopedExternCDecl(NewVD
, S
);
8168 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
8169 MangleNumberingContext
*MCtx
;
8170 Decl
*ManglingContextDecl
;
8171 std::tie(MCtx
, ManglingContextDecl
) =
8172 getCurrentMangleNumberContext(NewVD
->getDeclContext());
8174 Context
.setManglingNumber(
8175 NewVD
, MCtx
->getManglingNumber(
8176 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
8177 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
8181 // Special handling of variable named 'main'.
8182 if (Name
.getAsIdentifierInfo() && Name
.getAsIdentifierInfo()->isStr("main") &&
8183 NewVD
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8184 !getLangOpts().Freestanding
&& !NewVD
->getDescribedVarTemplate()) {
8186 // C++ [basic.start.main]p3
8187 // A program that declares a variable main at global scope is ill-formed.
8188 if (getLangOpts().CPlusPlus
)
8189 Diag(D
.getBeginLoc(), diag::err_main_global_variable
);
8191 // In C, and external-linkage variable named main results in undefined
8193 else if (NewVD
->hasExternalFormalLinkage())
8194 Diag(D
.getBeginLoc(), diag::warn_main_redefined
);
8197 if (D
.isRedeclaration() && !Previous
.empty()) {
8198 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
8199 checkDLLAttributeRedeclaration(*this, Prev
, NewVD
, IsMemberSpecialization
,
8200 D
.isFunctionDefinition());
8204 if (NewVD
->isInvalidDecl())
8205 NewTemplate
->setInvalidDecl();
8206 ActOnDocumentableDecl(NewTemplate
);
8210 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl())
8211 CompleteMemberSpecialization(NewVD
, Previous
);
8213 emitReadOnlyPlacementAttrWarning(*this, NewVD
);
8218 /// Enum describing the %select options in diag::warn_decl_shadow.
8219 enum ShadowedDeclKind
{
8226 SDK_StructuredBinding
8229 /// Determine what kind of declaration we're shadowing.
8230 static ShadowedDeclKind
computeShadowedDeclKind(const NamedDecl
*ShadowedDecl
,
8231 const DeclContext
*OldDC
) {
8232 if (isa
<TypeAliasDecl
>(ShadowedDecl
))
8234 else if (isa
<TypedefDecl
>(ShadowedDecl
))
8236 else if (isa
<BindingDecl
>(ShadowedDecl
))
8237 return SDK_StructuredBinding
;
8238 else if (isa
<RecordDecl
>(OldDC
))
8239 return isa
<FieldDecl
>(ShadowedDecl
) ? SDK_Field
: SDK_StaticMember
;
8241 return OldDC
->isFileContext() ? SDK_Global
: SDK_Local
;
8244 /// Return the location of the capture if the given lambda captures the given
8245 /// variable \p VD, or an invalid source location otherwise.
8246 static SourceLocation
getCaptureLocation(const LambdaScopeInfo
*LSI
,
8247 const VarDecl
*VD
) {
8248 for (const Capture
&Capture
: LSI
->Captures
) {
8249 if (Capture
.isVariableCapture() && Capture
.getVariable() == VD
)
8250 return Capture
.getLocation();
8252 return SourceLocation();
8255 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine
&Diags
,
8256 const LookupResult
&R
) {
8257 // Only diagnose if we're shadowing an unambiguous field or variable.
8258 if (R
.getResultKind() != LookupResult::Found
)
8261 // Return false if warning is ignored.
8262 return !Diags
.isIgnored(diag::warn_decl_shadow
, R
.getNameLoc());
8265 /// Return the declaration shadowed by the given variable \p D, or null
8266 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8267 NamedDecl
*Sema::getShadowedDeclaration(const VarDecl
*D
,
8268 const LookupResult
&R
) {
8269 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8272 // Don't diagnose declarations at file scope.
8273 if (D
->hasGlobalStorage() && !D
->isStaticLocal())
8276 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8277 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8281 /// Return the declaration shadowed by the given typedef \p D, or null
8282 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8283 NamedDecl
*Sema::getShadowedDeclaration(const TypedefNameDecl
*D
,
8284 const LookupResult
&R
) {
8285 // Don't warn if typedef declaration is part of a class
8286 if (D
->getDeclContext()->isRecord())
8289 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8292 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8293 return isa
<TypedefNameDecl
>(ShadowedDecl
) ? ShadowedDecl
: nullptr;
8296 /// Return the declaration shadowed by the given variable \p D, or null
8297 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8298 NamedDecl
*Sema::getShadowedDeclaration(const BindingDecl
*D
,
8299 const LookupResult
&R
) {
8300 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8303 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8304 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8308 /// Diagnose variable or built-in function shadowing. Implements
8311 /// This method is called whenever a VarDecl is added to a "useful"
8314 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8315 /// \param R the lookup of the name
8317 void Sema::CheckShadow(NamedDecl
*D
, NamedDecl
*ShadowedDecl
,
8318 const LookupResult
&R
) {
8319 DeclContext
*NewDC
= D
->getDeclContext();
8321 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ShadowedDecl
)) {
8322 // Fields are not shadowed by variables in C++ static methods.
8323 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDC
))
8327 // Fields shadowed by constructor parameters are a special case. Usually
8328 // the constructor initializes the field with the parameter.
8329 if (isa
<CXXConstructorDecl
>(NewDC
))
8330 if (const auto PVD
= dyn_cast
<ParmVarDecl
>(D
)) {
8331 // Remember that this was shadowed so we can either warn about its
8332 // modification or its existence depending on warning settings.
8333 ShadowingDecls
.insert({PVD
->getCanonicalDecl(), FD
});
8338 if (VarDecl
*shadowedVar
= dyn_cast
<VarDecl
>(ShadowedDecl
))
8339 if (shadowedVar
->isExternC()) {
8340 // For shadowing external vars, make sure that we point to the global
8341 // declaration, not a locally scoped extern declaration.
8342 for (auto *I
: shadowedVar
->redecls())
8343 if (I
->isFileVarDecl()) {
8349 DeclContext
*OldDC
= ShadowedDecl
->getDeclContext()->getRedeclContext();
8351 unsigned WarningDiag
= diag::warn_decl_shadow
;
8352 SourceLocation CaptureLoc
;
8353 if (isa
<VarDecl
>(D
) && isa
<VarDecl
>(ShadowedDecl
) && NewDC
&&
8354 isa
<CXXMethodDecl
>(NewDC
)) {
8355 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(NewDC
->getParent())) {
8356 if (RD
->isLambda() && OldDC
->Encloses(NewDC
->getLexicalParent())) {
8357 if (RD
->getLambdaCaptureDefault() == LCD_None
) {
8358 // Try to avoid warnings for lambdas with an explicit capture list.
8359 const auto *LSI
= cast
<LambdaScopeInfo
>(getCurFunction());
8360 // Warn only when the lambda captures the shadowed decl explicitly.
8361 CaptureLoc
= getCaptureLocation(LSI
, cast
<VarDecl
>(ShadowedDecl
));
8362 if (CaptureLoc
.isInvalid())
8363 WarningDiag
= diag::warn_decl_shadow_uncaptured_local
;
8365 // Remember that this was shadowed so we can avoid the warning if the
8366 // shadowed decl isn't captured and the warning settings allow it.
8367 cast
<LambdaScopeInfo
>(getCurFunction())
8368 ->ShadowingDecls
.push_back(
8369 {cast
<VarDecl
>(D
), cast
<VarDecl
>(ShadowedDecl
)});
8374 if (cast
<VarDecl
>(ShadowedDecl
)->hasLocalStorage()) {
8375 // A variable can't shadow a local variable in an enclosing scope, if
8376 // they are separated by a non-capturing declaration context.
8377 for (DeclContext
*ParentDC
= NewDC
;
8378 ParentDC
&& !ParentDC
->Equals(OldDC
);
8379 ParentDC
= getLambdaAwareParentOfDeclContext(ParentDC
)) {
8380 // Only block literals, captured statements, and lambda expressions
8381 // can capture; other scopes don't.
8382 if (!isa
<BlockDecl
>(ParentDC
) && !isa
<CapturedDecl
>(ParentDC
) &&
8383 !isLambdaCallOperator(ParentDC
)) {
8391 // Never warn about shadowing a placeholder variable.
8392 if (ShadowedDecl
->isPlaceholderVar(getLangOpts()))
8395 // Only warn about certain kinds of shadowing for class members.
8396 if (NewDC
&& NewDC
->isRecord()) {
8397 // In particular, don't warn about shadowing non-class members.
8398 if (!OldDC
->isRecord())
8401 // TODO: should we warn about static data members shadowing
8402 // static data members from base classes?
8404 // TODO: don't diagnose for inaccessible shadowed members.
8405 // This is hard to do perfectly because we might friend the
8406 // shadowing context, but that's just a false negative.
8410 DeclarationName Name
= R
.getLookupName();
8412 // Emit warning and note.
8413 ShadowedDeclKind Kind
= computeShadowedDeclKind(ShadowedDecl
, OldDC
);
8414 Diag(R
.getNameLoc(), WarningDiag
) << Name
<< Kind
<< OldDC
;
8415 if (!CaptureLoc
.isInvalid())
8416 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8417 << Name
<< /*explicitly*/ 1;
8418 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8421 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8422 /// when these variables are captured by the lambda.
8423 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo
*LSI
) {
8424 for (const auto &Shadow
: LSI
->ShadowingDecls
) {
8425 const VarDecl
*ShadowedDecl
= Shadow
.ShadowedDecl
;
8426 // Try to avoid the warning when the shadowed decl isn't captured.
8427 SourceLocation CaptureLoc
= getCaptureLocation(LSI
, ShadowedDecl
);
8428 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8429 Diag(Shadow
.VD
->getLocation(), CaptureLoc
.isInvalid()
8430 ? diag::warn_decl_shadow_uncaptured_local
8431 : diag::warn_decl_shadow
)
8432 << Shadow
.VD
->getDeclName()
8433 << computeShadowedDeclKind(ShadowedDecl
, OldDC
) << OldDC
;
8434 if (!CaptureLoc
.isInvalid())
8435 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8436 << Shadow
.VD
->getDeclName() << /*explicitly*/ 0;
8437 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8441 /// Check -Wshadow without the advantage of a previous lookup.
8442 void Sema::CheckShadow(Scope
*S
, VarDecl
*D
) {
8443 if (Diags
.isIgnored(diag::warn_decl_shadow
, D
->getLocation()))
8446 LookupResult
R(*this, D
->getDeclName(), D
->getLocation(),
8447 Sema::LookupOrdinaryName
, Sema::ForVisibleRedeclaration
);
8449 if (NamedDecl
*ShadowedDecl
= getShadowedDeclaration(D
, R
))
8450 CheckShadow(D
, ShadowedDecl
, R
);
8453 /// Check if 'E', which is an expression that is about to be modified, refers
8454 /// to a constructor parameter that shadows a field.
8455 void Sema::CheckShadowingDeclModification(Expr
*E
, SourceLocation Loc
) {
8456 // Quickly ignore expressions that can't be shadowing ctor parameters.
8457 if (!getLangOpts().CPlusPlus
|| ShadowingDecls
.empty())
8459 E
= E
->IgnoreParenImpCasts();
8460 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
);
8463 const NamedDecl
*D
= cast
<NamedDecl
>(DRE
->getDecl()->getCanonicalDecl());
8464 auto I
= ShadowingDecls
.find(D
);
8465 if (I
== ShadowingDecls
.end())
8467 const NamedDecl
*ShadowedDecl
= I
->second
;
8468 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8469 Diag(Loc
, diag::warn_modifying_shadowing_decl
) << D
<< OldDC
;
8470 Diag(D
->getLocation(), diag::note_var_declared_here
) << D
;
8471 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8473 // Avoid issuing multiple warnings about the same decl.
8474 ShadowingDecls
.erase(I
);
8477 /// Check for conflict between this global or extern "C" declaration and
8478 /// previous global or extern "C" declarations. This is only used in C++.
8479 template<typename T
>
8480 static bool checkGlobalOrExternCConflict(
8481 Sema
&S
, const T
*ND
, bool IsGlobal
, LookupResult
&Previous
) {
8482 assert(S
.getLangOpts().CPlusPlus
&& "only C++ has extern \"C\"");
8483 NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName());
8485 if (!Prev
&& IsGlobal
&& !isIncompleteDeclExternC(S
, ND
)) {
8486 // The common case: this global doesn't conflict with any extern "C"
8492 if (!IsGlobal
|| isIncompleteDeclExternC(S
, ND
)) {
8493 // Both the old and new declarations have C language linkage. This is a
8496 Previous
.addDecl(Prev
);
8500 // This is a global, non-extern "C" declaration, and there is a previous
8501 // non-global extern "C" declaration. Diagnose if this is a variable
8503 if (!isa
<VarDecl
>(ND
))
8506 // The declaration is extern "C". Check for any declaration in the
8507 // translation unit which might conflict.
8509 // We have already performed the lookup into the translation unit.
8511 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
8513 if (isa
<VarDecl
>(*I
)) {
8519 DeclContext::lookup_result R
=
8520 S
.Context
.getTranslationUnitDecl()->lookup(ND
->getDeclName());
8521 for (DeclContext::lookup_result::iterator I
= R
.begin(), E
= R
.end();
8523 if (isa
<VarDecl
>(*I
)) {
8527 // FIXME: If we have any other entity with this name in global scope,
8528 // the declaration is ill-formed, but that is a defect: it breaks the
8529 // 'stat' hack, for instance. Only variables can have mangled name
8530 // clashes with extern "C" declarations, so only they deserve a
8539 // Use the first declaration's location to ensure we point at something which
8540 // is lexically inside an extern "C" linkage-spec.
8541 assert(Prev
&& "should have found a previous declaration to diagnose");
8542 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(Prev
))
8543 Prev
= FD
->getFirstDecl();
8545 Prev
= cast
<VarDecl
>(Prev
)->getFirstDecl();
8547 S
.Diag(ND
->getLocation(), diag::err_extern_c_global_conflict
)
8549 S
.Diag(Prev
->getLocation(), diag::note_extern_c_global_conflict
)
8554 /// Apply special rules for handling extern "C" declarations. Returns \c true
8555 /// if we have found that this is a redeclaration of some prior entity.
8557 /// Per C++ [dcl.link]p6:
8558 /// Two declarations [for a function or variable] with C language linkage
8559 /// with the same name that appear in different scopes refer to the same
8560 /// [entity]. An entity with C language linkage shall not be declared with
8561 /// the same name as an entity in global scope.
8562 template<typename T
>
8563 static bool checkForConflictWithNonVisibleExternC(Sema
&S
, const T
*ND
,
8564 LookupResult
&Previous
) {
8565 if (!S
.getLangOpts().CPlusPlus
) {
8566 // In C, when declaring a global variable, look for a corresponding 'extern'
8567 // variable declared in function scope. We don't need this in C++, because
8568 // we find local extern decls in the surrounding file-scope DeclContext.
8569 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8570 if (NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName())) {
8572 Previous
.addDecl(Prev
);
8579 // A declaration in the translation unit can conflict with an extern "C"
8581 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit())
8582 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/true, Previous
);
8584 // An extern "C" declaration can conflict with a declaration in the
8585 // translation unit or can be a redeclaration of an extern "C" declaration
8586 // in another scope.
8587 if (isIncompleteDeclExternC(S
,ND
))
8588 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/false, Previous
);
8590 // Neither global nor extern "C": nothing to do.
8594 void Sema::CheckVariableDeclarationType(VarDecl
*NewVD
) {
8595 // If the decl is already known invalid, don't check it.
8596 if (NewVD
->isInvalidDecl())
8599 QualType T
= NewVD
->getType();
8601 // Defer checking an 'auto' type until its initializer is attached.
8602 if (T
->isUndeducedType())
8605 if (NewVD
->hasAttrs())
8606 CheckAlignasUnderalignment(NewVD
);
8608 if (T
->isObjCObjectType()) {
8609 Diag(NewVD
->getLocation(), diag::err_statically_allocated_object
)
8610 << FixItHint::CreateInsertion(NewVD
->getLocation(), "*");
8611 T
= Context
.getObjCObjectPointerType(T
);
8615 // Emit an error if an address space was applied to decl with local storage.
8616 // This includes arrays of objects with address space qualifiers, but not
8617 // automatic variables that point to other address spaces.
8618 // ISO/IEC TR 18037 S5.1.2
8619 if (!getLangOpts().OpenCL
&& NewVD
->hasLocalStorage() &&
8620 T
.getAddressSpace() != LangAS::Default
) {
8621 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 0;
8622 NewVD
->setInvalidDecl();
8626 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8628 if (getLangOpts().OpenCLVersion
== 120 &&
8629 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8631 NewVD
->isStaticLocal()) {
8632 Diag(NewVD
->getLocation(), diag::err_static_function_scope
);
8633 NewVD
->setInvalidDecl();
8637 if (getLangOpts().OpenCL
) {
8638 if (!diagnoseOpenCLTypes(*this, NewVD
))
8641 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8642 if (NewVD
->hasAttr
<BlocksAttr
>()) {
8643 Diag(NewVD
->getLocation(), diag::err_opencl_block_storage_type
);
8647 if (T
->isBlockPointerType()) {
8648 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8649 // can't use 'extern' storage class.
8650 if (!T
.isConstQualified()) {
8651 Diag(NewVD
->getLocation(), diag::err_opencl_invalid_block_declaration
)
8653 NewVD
->setInvalidDecl();
8656 if (NewVD
->hasExternalStorage()) {
8657 Diag(NewVD
->getLocation(), diag::err_opencl_extern_block_declaration
);
8658 NewVD
->setInvalidDecl();
8663 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8664 if (NewVD
->isFileVarDecl() || NewVD
->isStaticLocal() ||
8665 NewVD
->hasExternalStorage()) {
8666 if (!T
->isSamplerT() && !T
->isDependentType() &&
8667 !(T
.getAddressSpace() == LangAS::opencl_constant
||
8668 (T
.getAddressSpace() == LangAS::opencl_global
&&
8669 getOpenCLOptions().areProgramScopeVariablesSupported(
8671 int Scope
= NewVD
->isStaticLocal() | NewVD
->hasExternalStorage() << 1;
8672 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8673 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8674 << Scope
<< "global or constant";
8676 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8677 << Scope
<< "constant";
8678 NewVD
->setInvalidDecl();
8682 if (T
.getAddressSpace() == LangAS::opencl_global
) {
8683 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8684 << 1 /*is any function*/ << "global";
8685 NewVD
->setInvalidDecl();
8688 if (T
.getAddressSpace() == LangAS::opencl_constant
||
8689 T
.getAddressSpace() == LangAS::opencl_local
) {
8690 FunctionDecl
*FD
= getCurFunctionDecl();
8691 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8693 if (FD
&& !FD
->hasAttr
<OpenCLKernelAttr
>()) {
8694 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8695 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8696 << 0 /*non-kernel only*/ << "constant";
8698 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8699 << 0 /*non-kernel only*/ << "local";
8700 NewVD
->setInvalidDecl();
8703 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8704 // in the outermost scope of a kernel function.
8705 if (FD
&& FD
->hasAttr
<OpenCLKernelAttr
>()) {
8706 if (!getCurScope()->isFunctionScope()) {
8707 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8708 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8711 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8713 NewVD
->setInvalidDecl();
8717 } else if (T
.getAddressSpace() != LangAS::opencl_private
&&
8718 // If we are parsing a template we didn't deduce an addr
8720 T
.getAddressSpace() != LangAS::Default
) {
8721 // Do not allow other address spaces on automatic variable.
8722 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 1;
8723 NewVD
->setInvalidDecl();
8729 if (NewVD
->hasLocalStorage() && T
.isObjCGCWeak()
8730 && !NewVD
->hasAttr
<BlocksAttr
>()) {
8731 if (getLangOpts().getGC() != LangOptions::NonGC
)
8732 Diag(NewVD
->getLocation(), diag::warn_gc_attribute_weak_on_local
);
8734 assert(!getLangOpts().ObjCAutoRefCount
);
8735 Diag(NewVD
->getLocation(), diag::warn_attribute_weak_on_local
);
8739 // WebAssembly tables must be static with a zero length and can't be
8740 // declared within functions.
8741 if (T
->isWebAssemblyTableType()) {
8742 if (getCurScope()->getParent()) { // Parent is null at top-level
8743 Diag(NewVD
->getLocation(), diag::err_wasm_table_in_function
);
8744 NewVD
->setInvalidDecl();
8747 if (NewVD
->getStorageClass() != SC_Static
) {
8748 Diag(NewVD
->getLocation(), diag::err_wasm_table_must_be_static
);
8749 NewVD
->setInvalidDecl();
8752 const auto *ATy
= dyn_cast
<ConstantArrayType
>(T
.getTypePtr());
8753 if (!ATy
|| ATy
->getSize().getSExtValue() != 0) {
8754 Diag(NewVD
->getLocation(),
8755 diag::err_typecheck_wasm_table_must_have_zero_length
);
8756 NewVD
->setInvalidDecl();
8761 bool isVM
= T
->isVariablyModifiedType();
8762 if (isVM
|| NewVD
->hasAttr
<CleanupAttr
>() ||
8763 NewVD
->hasAttr
<BlocksAttr
>())
8764 setFunctionHasBranchProtectedScope();
8766 if ((isVM
&& NewVD
->hasLinkage()) ||
8767 (T
->isVariableArrayType() && NewVD
->hasGlobalStorage())) {
8768 bool SizeIsNegative
;
8769 llvm::APSInt Oversized
;
8770 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
8771 NewVD
->getTypeSourceInfo(), Context
, SizeIsNegative
, Oversized
);
8773 if (FixedTInfo
&& T
== NewVD
->getTypeSourceInfo()->getType())
8774 FixedT
= FixedTInfo
->getType();
8775 else if (FixedTInfo
) {
8776 // Type and type-as-written are canonically different. We need to fix up
8777 // both types separately.
8778 FixedT
= TryToFixInvalidVariablyModifiedType(T
, Context
, SizeIsNegative
,
8781 if ((!FixedTInfo
|| FixedT
.isNull()) && T
->isVariableArrayType()) {
8782 const VariableArrayType
*VAT
= Context
.getAsVariableArrayType(T
);
8783 // FIXME: This won't give the correct result for
8785 SourceRange SizeRange
= VAT
->getSizeExpr()->getSourceRange();
8787 if (NewVD
->isFileVarDecl())
8788 Diag(NewVD
->getLocation(), diag::err_vla_decl_in_file_scope
)
8790 else if (NewVD
->isStaticLocal())
8791 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_static_storage
)
8794 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_extern_linkage
)
8796 NewVD
->setInvalidDecl();
8801 if (NewVD
->isFileVarDecl())
8802 Diag(NewVD
->getLocation(), diag::err_vm_decl_in_file_scope
);
8804 Diag(NewVD
->getLocation(), diag::err_vm_decl_has_extern_linkage
);
8805 NewVD
->setInvalidDecl();
8809 Diag(NewVD
->getLocation(), diag::ext_vla_folded_to_constant
);
8810 NewVD
->setType(FixedT
);
8811 NewVD
->setTypeSourceInfo(FixedTInfo
);
8814 if (T
->isVoidType()) {
8815 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8816 // of objects and functions.
8817 if (NewVD
->isThisDeclarationADefinition() || getLangOpts().CPlusPlus
) {
8818 Diag(NewVD
->getLocation(), diag::err_typecheck_decl_incomplete_type
)
8820 NewVD
->setInvalidDecl();
8825 if (!NewVD
->hasLocalStorage() && NewVD
->hasAttr
<BlocksAttr
>()) {
8826 Diag(NewVD
->getLocation(), diag::err_block_on_nonlocal
);
8827 NewVD
->setInvalidDecl();
8831 if (!NewVD
->hasLocalStorage() && T
->isSizelessType() &&
8832 !T
.isWebAssemblyReferenceType()) {
8833 Diag(NewVD
->getLocation(), diag::err_sizeless_nonlocal
) << T
;
8834 NewVD
->setInvalidDecl();
8838 if (isVM
&& NewVD
->hasAttr
<BlocksAttr
>()) {
8839 Diag(NewVD
->getLocation(), diag::err_block_on_vm
);
8840 NewVD
->setInvalidDecl();
8844 if (NewVD
->isConstexpr() && !T
->isDependentType() &&
8845 RequireLiteralType(NewVD
->getLocation(), T
,
8846 diag::err_constexpr_var_non_literal
)) {
8847 NewVD
->setInvalidDecl();
8851 // PPC MMA non-pointer types are not allowed as non-local variable types.
8852 if (Context
.getTargetInfo().getTriple().isPPC64() &&
8853 !NewVD
->isLocalVarDecl() &&
8854 CheckPPCMMAType(T
, NewVD
->getLocation())) {
8855 NewVD
->setInvalidDecl();
8859 // Check that SVE types are only used in functions with SVE available.
8860 if (T
->isSVESizelessBuiltinType() && isa
<FunctionDecl
>(CurContext
)) {
8861 const FunctionDecl
*FD
= cast
<FunctionDecl
>(CurContext
);
8862 llvm::StringMap
<bool> CallerFeatureMap
;
8863 Context
.getFunctionFeatureMap(CallerFeatureMap
, FD
);
8864 if (!Builtin::evaluateRequiredTargetFeatures(
8865 "sve", CallerFeatureMap
)) {
8866 Diag(NewVD
->getLocation(), diag::err_sve_vector_in_non_sve_target
) << T
;
8867 NewVD
->setInvalidDecl();
8873 checkRVVTypeSupport(T
, NewVD
->getLocation(), cast
<Decl
>(CurContext
));
8876 /// Perform semantic checking on a newly-created variable
8879 /// This routine performs all of the type-checking required for a
8880 /// variable declaration once it has been built. It is used both to
8881 /// check variables after they have been parsed and their declarators
8882 /// have been translated into a declaration, and to check variables
8883 /// that have been instantiated from a template.
8885 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8887 /// Returns true if the variable declaration is a redeclaration.
8888 bool Sema::CheckVariableDeclaration(VarDecl
*NewVD
, LookupResult
&Previous
) {
8889 CheckVariableDeclarationType(NewVD
);
8891 // If the decl is already known invalid, don't check it.
8892 if (NewVD
->isInvalidDecl())
8895 // If we did not find anything by this name, look for a non-visible
8896 // extern "C" declaration with the same name.
8897 if (Previous
.empty() &&
8898 checkForConflictWithNonVisibleExternC(*this, NewVD
, Previous
))
8899 Previous
.setShadowed();
8901 if (!Previous
.empty()) {
8902 MergeVarDecl(NewVD
, Previous
);
8908 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8909 /// and if so, check that it's a valid override and remember it.
8910 bool Sema::AddOverriddenMethods(CXXRecordDecl
*DC
, CXXMethodDecl
*MD
) {
8911 llvm::SmallPtrSet
<const CXXMethodDecl
*, 4> Overridden
;
8913 // Look for methods in base classes that this method might override.
8914 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8915 /*DetectVirtual=*/false);
8916 auto VisitBase
= [&] (const CXXBaseSpecifier
*Specifier
, CXXBasePath
&Path
) {
8917 CXXRecordDecl
*BaseRecord
= Specifier
->getType()->getAsCXXRecordDecl();
8918 DeclarationName Name
= MD
->getDeclName();
8920 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
8921 // We really want to find the base class destructor here.
8922 QualType T
= Context
.getTypeDeclType(BaseRecord
);
8923 CanQualType CT
= Context
.getCanonicalType(T
);
8924 Name
= Context
.DeclarationNames
.getCXXDestructorName(CT
);
8927 for (NamedDecl
*BaseND
: BaseRecord
->lookup(Name
)) {
8928 CXXMethodDecl
*BaseMD
=
8929 dyn_cast
<CXXMethodDecl
>(BaseND
->getCanonicalDecl());
8930 if (!BaseMD
|| !BaseMD
->isVirtual() ||
8931 IsOverride(MD
, BaseMD
, /*UseMemberUsingDeclRules=*/false,
8932 /*ConsiderCudaAttrs=*/true))
8934 if (!CheckExplicitObjectOverride(MD
, BaseMD
))
8936 if (Overridden
.insert(BaseMD
).second
) {
8937 MD
->addOverriddenMethod(BaseMD
);
8938 CheckOverridingFunctionReturnType(MD
, BaseMD
);
8939 CheckOverridingFunctionAttributes(MD
, BaseMD
);
8940 CheckOverridingFunctionExceptionSpec(MD
, BaseMD
);
8941 CheckIfOverriddenFunctionIsMarkedFinal(MD
, BaseMD
);
8944 // A method can only override one function from each base class. We
8945 // don't track indirectly overridden methods from bases of bases.
8952 DC
->lookupInBases(VisitBase
, Paths
);
8953 return !Overridden
.empty();
8957 // Struct for holding all of the extra arguments needed by
8958 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8959 struct ActOnFDArgs
{
8962 MultiTemplateParamsArg TemplateParamLists
;
8965 } // end anonymous namespace
8969 // Callback to only accept typo corrections that have a non-zero edit distance.
8970 // Also only accept corrections that have the same parent decl.
8971 class DifferentNameValidatorCCC final
: public CorrectionCandidateCallback
{
8973 DifferentNameValidatorCCC(ASTContext
&Context
, FunctionDecl
*TypoFD
,
8974 CXXRecordDecl
*Parent
)
8975 : Context(Context
), OriginalFD(TypoFD
),
8976 ExpectedParent(Parent
? Parent
->getCanonicalDecl() : nullptr) {}
8978 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
8979 if (candidate
.getEditDistance() == 0)
8982 SmallVector
<unsigned, 1> MismatchedParams
;
8983 for (TypoCorrection::const_decl_iterator CDecl
= candidate
.begin(),
8984 CDeclEnd
= candidate
.end();
8985 CDecl
!= CDeclEnd
; ++CDecl
) {
8986 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
8988 if (FD
&& !FD
->hasBody() &&
8989 hasSimilarParameters(Context
, FD
, OriginalFD
, MismatchedParams
)) {
8990 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
8991 CXXRecordDecl
*Parent
= MD
->getParent();
8992 if (Parent
&& Parent
->getCanonicalDecl() == ExpectedParent
)
8994 } else if (!ExpectedParent
) {
9003 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
9004 return std::make_unique
<DifferentNameValidatorCCC
>(*this);
9008 ASTContext
&Context
;
9009 FunctionDecl
*OriginalFD
;
9010 CXXRecordDecl
*ExpectedParent
;
9013 } // end anonymous namespace
9015 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl
*F
) {
9016 TypoCorrectedFunctionDefinitions
.insert(F
);
9019 /// Generate diagnostics for an invalid function redeclaration.
9021 /// This routine handles generating the diagnostic messages for an invalid
9022 /// function redeclaration, including finding possible similar declarations
9023 /// or performing typo correction if there are no previous declarations with
9026 /// Returns a NamedDecl iff typo correction was performed and substituting in
9027 /// the new declaration name does not cause new errors.
9028 static NamedDecl
*DiagnoseInvalidRedeclaration(
9029 Sema
&SemaRef
, LookupResult
&Previous
, FunctionDecl
*NewFD
,
9030 ActOnFDArgs
&ExtraArgs
, bool IsLocalFriend
, Scope
*S
) {
9031 DeclarationName Name
= NewFD
->getDeclName();
9032 DeclContext
*NewDC
= NewFD
->getDeclContext();
9033 SmallVector
<unsigned, 1> MismatchedParams
;
9034 SmallVector
<std::pair
<FunctionDecl
*, unsigned>, 1> NearMatches
;
9035 TypoCorrection Correction
;
9036 bool IsDefinition
= ExtraArgs
.D
.isFunctionDefinition();
9038 IsLocalFriend
? diag::err_no_matching_local_friend
:
9039 NewFD
->getFriendObjectKind() ? diag::err_qualified_friend_no_match
:
9040 diag::err_member_decl_does_not_match
;
9041 LookupResult
Prev(SemaRef
, Name
, NewFD
->getLocation(),
9042 IsLocalFriend
? Sema::LookupLocalFriendName
9043 : Sema::LookupOrdinaryName
,
9044 Sema::ForVisibleRedeclaration
);
9046 NewFD
->setInvalidDecl();
9048 SemaRef
.LookupName(Prev
, S
);
9050 SemaRef
.LookupQualifiedName(Prev
, NewDC
);
9051 assert(!Prev
.isAmbiguous() &&
9052 "Cannot have an ambiguity in previous-declaration lookup");
9053 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
9054 DifferentNameValidatorCCC
CCC(SemaRef
.Context
, NewFD
,
9055 MD
? MD
->getParent() : nullptr);
9056 if (!Prev
.empty()) {
9057 for (LookupResult::iterator Func
= Prev
.begin(), FuncEnd
= Prev
.end();
9058 Func
!= FuncEnd
; ++Func
) {
9059 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*Func
);
9061 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
9062 // Add 1 to the index so that 0 can mean the mismatch didn't
9063 // involve a parameter
9065 MismatchedParams
.empty() ? 0 : MismatchedParams
.front() + 1;
9066 NearMatches
.push_back(std::make_pair(FD
, ParamNum
));
9069 // If the qualified name lookup yielded nothing, try typo correction
9070 } else if ((Correction
= SemaRef
.CorrectTypo(
9071 Prev
.getLookupNameInfo(), Prev
.getLookupKind(), S
,
9072 &ExtraArgs
.D
.getCXXScopeSpec(), CCC
, Sema::CTK_ErrorRecovery
,
9073 IsLocalFriend
? nullptr : NewDC
))) {
9074 // Set up everything for the call to ActOnFunctionDeclarator
9075 ExtraArgs
.D
.SetIdentifier(Correction
.getCorrectionAsIdentifierInfo(),
9076 ExtraArgs
.D
.getIdentifierLoc());
9078 Previous
.setLookupName(Correction
.getCorrection());
9079 for (TypoCorrection::decl_iterator CDecl
= Correction
.begin(),
9080 CDeclEnd
= Correction
.end();
9081 CDecl
!= CDeclEnd
; ++CDecl
) {
9082 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
9083 if (FD
&& !FD
->hasBody() &&
9084 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
9085 Previous
.addDecl(FD
);
9088 bool wasRedeclaration
= ExtraArgs
.D
.isRedeclaration();
9091 // Retry building the function declaration with the new previous
9092 // declarations, and with errors suppressed.
9095 Sema::SFINAETrap
Trap(SemaRef
);
9097 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9098 // pieces need to verify the typo-corrected C++ declaration and hopefully
9099 // eliminate the need for the parameter pack ExtraArgs.
9100 Result
= SemaRef
.ActOnFunctionDeclarator(
9101 ExtraArgs
.S
, ExtraArgs
.D
,
9102 Correction
.getCorrectionDecl()->getDeclContext(),
9103 NewFD
->getTypeSourceInfo(), Previous
, ExtraArgs
.TemplateParamLists
,
9104 ExtraArgs
.AddToScope
);
9106 if (Trap
.hasErrorOccurred())
9111 // Determine which correction we picked.
9112 Decl
*Canonical
= Result
->getCanonicalDecl();
9113 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
9115 if ((*I
)->getCanonicalDecl() == Canonical
)
9116 Correction
.setCorrectionDecl(*I
);
9118 // Let Sema know about the correction.
9119 SemaRef
.MarkTypoCorrectedFunctionDefinition(Result
);
9120 SemaRef
.diagnoseTypo(
9122 SemaRef
.PDiag(IsLocalFriend
9123 ? diag::err_no_matching_local_friend_suggest
9124 : diag::err_member_decl_does_not_match_suggest
)
9125 << Name
<< NewDC
<< IsDefinition
);
9129 // Pretend the typo correction never occurred
9130 ExtraArgs
.D
.SetIdentifier(Name
.getAsIdentifierInfo(),
9131 ExtraArgs
.D
.getIdentifierLoc());
9132 ExtraArgs
.D
.setRedeclaration(wasRedeclaration
);
9134 Previous
.setLookupName(Name
);
9137 SemaRef
.Diag(NewFD
->getLocation(), DiagMsg
)
9138 << Name
<< NewDC
<< IsDefinition
<< NewFD
->getLocation();
9140 bool NewFDisConst
= false;
9141 if (CXXMethodDecl
*NewMD
= dyn_cast
<CXXMethodDecl
>(NewFD
))
9142 NewFDisConst
= NewMD
->isConst();
9144 for (SmallVectorImpl
<std::pair
<FunctionDecl
*, unsigned> >::iterator
9145 NearMatch
= NearMatches
.begin(), NearMatchEnd
= NearMatches
.end();
9146 NearMatch
!= NearMatchEnd
; ++NearMatch
) {
9147 FunctionDecl
*FD
= NearMatch
->first
;
9148 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
9149 bool FDisConst
= MD
&& MD
->isConst();
9150 bool IsMember
= MD
|| !IsLocalFriend
;
9152 // FIXME: These notes are poorly worded for the local friend case.
9153 if (unsigned Idx
= NearMatch
->second
) {
9154 ParmVarDecl
*FDParam
= FD
->getParamDecl(Idx
-1);
9155 SourceLocation Loc
= FDParam
->getTypeSpecStartLoc();
9156 if (Loc
.isInvalid()) Loc
= FD
->getLocation();
9157 SemaRef
.Diag(Loc
, IsMember
? diag::note_member_def_close_param_match
9158 : diag::note_local_decl_close_param_match
)
9159 << Idx
<< FDParam
->getType()
9160 << NewFD
->getParamDecl(Idx
- 1)->getType();
9161 } else if (FDisConst
!= NewFDisConst
) {
9162 SemaRef
.Diag(FD
->getLocation(), diag::note_member_def_close_const_match
)
9163 << NewFDisConst
<< FD
->getSourceRange().getEnd()
9165 ? FixItHint::CreateRemoval(ExtraArgs
.D
.getFunctionTypeInfo()
9166 .getConstQualifierLoc())
9167 : FixItHint::CreateInsertion(ExtraArgs
.D
.getFunctionTypeInfo()
9169 .getLocWithOffset(1),
9172 SemaRef
.Diag(FD
->getLocation(),
9173 IsMember
? diag::note_member_def_close_match
9174 : diag::note_local_decl_close_match
);
9179 static StorageClass
getFunctionStorageClass(Sema
&SemaRef
, Declarator
&D
) {
9180 switch (D
.getDeclSpec().getStorageClassSpec()) {
9181 default: llvm_unreachable("Unknown storage class!");
9182 case DeclSpec::SCS_auto
:
9183 case DeclSpec::SCS_register
:
9184 case DeclSpec::SCS_mutable
:
9185 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9186 diag::err_typecheck_sclass_func
);
9187 D
.getMutableDeclSpec().ClearStorageClassSpecs();
9190 case DeclSpec::SCS_unspecified
: break;
9191 case DeclSpec::SCS_extern
:
9192 if (D
.getDeclSpec().isExternInLinkageSpec())
9195 case DeclSpec::SCS_static
: {
9196 if (SemaRef
.CurContext
->getRedeclContext()->isFunctionOrMethod()) {
9198 // The declaration of an identifier for a function that has
9199 // block scope shall have no explicit storage-class specifier
9200 // other than extern
9201 // See also (C++ [dcl.stc]p4).
9202 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9203 diag::err_static_block_func
);
9208 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
9211 // No explicit storage class has already been returned
9215 static FunctionDecl
*CreateNewFunctionDecl(Sema
&SemaRef
, Declarator
&D
,
9216 DeclContext
*DC
, QualType
&R
,
9217 TypeSourceInfo
*TInfo
,
9219 bool &IsVirtualOkay
) {
9220 DeclarationNameInfo NameInfo
= SemaRef
.GetNameForDeclarator(D
);
9221 DeclarationName Name
= NameInfo
.getName();
9223 FunctionDecl
*NewFD
= nullptr;
9224 bool isInline
= D
.getDeclSpec().isInlineSpecified();
9226 if (!SemaRef
.getLangOpts().CPlusPlus
) {
9227 // Determine whether the function was written with a prototype. This is
9229 // - there is a prototype in the declarator, or
9230 // - the type R of the function is some kind of typedef or other non-
9231 // attributed reference to a type name (which eventually refers to a
9232 // function type). Note, we can't always look at the adjusted type to
9233 // check this case because attributes may cause a non-function
9234 // declarator to still have a function type. e.g.,
9235 // typedef void func(int a);
9236 // __attribute__((noreturn)) func other_func; // This has a prototype
9238 (D
.isFunctionDeclarator() && D
.getFunctionTypeInfo().hasPrototype
) ||
9239 (D
.getDeclSpec().isTypeRep() &&
9240 SemaRef
.GetTypeFromParser(D
.getDeclSpec().getRepAsType(), nullptr)
9241 ->isFunctionProtoType()) ||
9242 (!R
->getAsAdjusted
<FunctionType
>() && R
->isFunctionProtoType());
9244 (HasPrototype
|| !SemaRef
.getLangOpts().requiresStrictPrototypes()) &&
9245 "Strict prototypes are required");
9247 NewFD
= FunctionDecl::Create(
9248 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
9249 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
, HasPrototype
,
9250 ConstexprSpecKind::Unspecified
,
9251 /*TrailingRequiresClause=*/nullptr);
9252 if (D
.isInvalidType())
9253 NewFD
->setInvalidDecl();
9258 ExplicitSpecifier ExplicitSpecifier
= D
.getDeclSpec().getExplicitSpecifier();
9260 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
9261 if (ConstexprKind
== ConstexprSpecKind::Constinit
) {
9262 SemaRef
.Diag(D
.getDeclSpec().getConstexprSpecLoc(),
9263 diag::err_constexpr_wrong_decl_kind
)
9264 << static_cast<int>(ConstexprKind
);
9265 ConstexprKind
= ConstexprSpecKind::Unspecified
;
9266 D
.getMutableDeclSpec().ClearConstexprSpec();
9268 Expr
*TrailingRequiresClause
= D
.getTrailingRequiresClause();
9270 SemaRef
.CheckExplicitObjectMemberFunction(DC
, D
, Name
, R
);
9272 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
) {
9273 // This is a C++ constructor declaration.
9274 assert(DC
->isRecord() &&
9275 "Constructors can only be declared in a member context");
9277 R
= SemaRef
.CheckConstructorDeclarator(D
, R
, SC
);
9278 return CXXConstructorDecl::Create(
9279 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9280 TInfo
, ExplicitSpecifier
, SemaRef
.getCurFPFeatures().isFPConstrained(),
9281 isInline
, /*isImplicitlyDeclared=*/false, ConstexprKind
,
9282 InheritedConstructor(), TrailingRequiresClause
);
9284 } else if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
9285 // This is a C++ destructor declaration.
9286 if (DC
->isRecord()) {
9287 R
= SemaRef
.CheckDestructorDeclarator(D
, R
, SC
);
9288 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
9289 CXXDestructorDecl
*NewDD
= CXXDestructorDecl::Create(
9290 SemaRef
.Context
, Record
, D
.getBeginLoc(), NameInfo
, R
, TInfo
,
9291 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9292 /*isImplicitlyDeclared=*/false, ConstexprKind
,
9293 TrailingRequiresClause
);
9294 // User defined destructors start as not selected if the class definition is still
9296 if (Record
->isBeingDefined())
9297 NewDD
->setIneligibleOrNotSelected(true);
9299 // If the destructor needs an implicit exception specification, set it
9300 // now. FIXME: It'd be nice to be able to create the right type to start
9301 // with, but the type needs to reference the destructor declaration.
9302 if (SemaRef
.getLangOpts().CPlusPlus11
)
9303 SemaRef
.AdjustDestructorExceptionSpec(NewDD
);
9305 IsVirtualOkay
= true;
9309 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_destructor_not_member
);
9312 // Create a FunctionDecl to satisfy the function definition parsing
9314 return FunctionDecl::Create(
9315 SemaRef
.Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(), Name
, R
,
9316 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9317 /*hasPrototype=*/true, ConstexprKind
, TrailingRequiresClause
);
9320 } else if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
9321 if (!DC
->isRecord()) {
9322 SemaRef
.Diag(D
.getIdentifierLoc(),
9323 diag::err_conv_function_not_member
);
9327 SemaRef
.CheckConversionDeclarator(D
, R
, SC
);
9328 if (D
.isInvalidType())
9331 IsVirtualOkay
= true;
9332 return CXXConversionDecl::Create(
9333 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9334 TInfo
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9335 ExplicitSpecifier
, ConstexprKind
, SourceLocation(),
9336 TrailingRequiresClause
);
9338 } else if (Name
.getNameKind() == DeclarationName::CXXDeductionGuideName
) {
9339 if (TrailingRequiresClause
)
9340 SemaRef
.Diag(TrailingRequiresClause
->getBeginLoc(),
9341 diag::err_trailing_requires_clause_on_deduction_guide
)
9342 << TrailingRequiresClause
->getSourceRange();
9343 if (SemaRef
.CheckDeductionGuideDeclarator(D
, R
, SC
))
9345 return CXXDeductionGuideDecl::Create(SemaRef
.Context
, DC
, D
.getBeginLoc(),
9346 ExplicitSpecifier
, NameInfo
, R
, TInfo
,
9348 } else if (DC
->isRecord()) {
9349 // If the name of the function is the same as the name of the record,
9350 // then this must be an invalid constructor that has a return type.
9351 // (The parser checks for a return type and makes the declarator a
9352 // constructor if it has no return type).
9353 if (Name
.getAsIdentifierInfo() &&
9354 Name
.getAsIdentifierInfo() == cast
<CXXRecordDecl
>(DC
)->getIdentifier()){
9355 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_constructor_return_type
)
9356 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
9357 << SourceRange(D
.getIdentifierLoc());
9361 // This is a C++ method declaration.
9362 CXXMethodDecl
*Ret
= CXXMethodDecl::Create(
9363 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9364 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9365 ConstexprKind
, SourceLocation(), TrailingRequiresClause
);
9366 IsVirtualOkay
= !Ret
->isStatic();
9370 SemaRef
.getLangOpts().CPlusPlus
&& D
.getDeclSpec().isFriendSpecified();
9371 if (!isFriend
&& SemaRef
.CurContext
->isRecord())
9374 // Determine whether the function was written with a
9375 // prototype. This true when:
9376 // - we're in C++ (where every function has a prototype),
9377 return FunctionDecl::Create(
9378 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
9379 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9380 true /*HasPrototype*/, ConstexprKind
, TrailingRequiresClause
);
9384 enum OpenCLParamType
{
9388 InvalidAddrSpacePtrKernelParam
,
9393 static bool isOpenCLSizeDependentType(ASTContext
&C
, QualType Ty
) {
9394 // Size dependent types are just typedefs to normal integer types
9395 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9396 // integers other than by their names.
9397 StringRef SizeTypeNames
[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9399 // Remove typedefs one by one until we reach a typedef
9400 // for a size dependent type.
9401 QualType DesugaredTy
= Ty
;
9403 ArrayRef
<StringRef
> Names(SizeTypeNames
);
9404 auto Match
= llvm::find(Names
, DesugaredTy
.getUnqualifiedType().getAsString());
9405 if (Names
.end() != Match
)
9409 DesugaredTy
= Ty
.getSingleStepDesugaredType(C
);
9410 } while (DesugaredTy
!= Ty
);
9415 static OpenCLParamType
getOpenCLKernelParameterType(Sema
&S
, QualType PT
) {
9416 if (PT
->isDependentType())
9417 return InvalidKernelParam
;
9419 if (PT
->isPointerType() || PT
->isReferenceType()) {
9420 QualType PointeeType
= PT
->getPointeeType();
9421 if (PointeeType
.getAddressSpace() == LangAS::opencl_generic
||
9422 PointeeType
.getAddressSpace() == LangAS::opencl_private
||
9423 PointeeType
.getAddressSpace() == LangAS::Default
)
9424 return InvalidAddrSpacePtrKernelParam
;
9426 if (PointeeType
->isPointerType()) {
9427 // This is a pointer to pointer parameter.
9428 // Recursively check inner type.
9429 OpenCLParamType ParamKind
= getOpenCLKernelParameterType(S
, PointeeType
);
9430 if (ParamKind
== InvalidAddrSpacePtrKernelParam
||
9431 ParamKind
== InvalidKernelParam
)
9434 // OpenCL v3.0 s6.11.a:
9435 // A restriction to pass pointers to pointers only applies to OpenCL C
9437 if (S
.getLangOpts().getOpenCLCompatibleVersion() > 120)
9438 return ValidKernelParam
;
9440 return PtrPtrKernelParam
;
9443 // C++ for OpenCL v1.0 s2.4:
9444 // Moreover the types used in parameters of the kernel functions must be:
9445 // Standard layout types for pointer parameters. The same applies to
9446 // reference if an implementation supports them in kernel parameters.
9447 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9448 !S
.getOpenCLOptions().isAvailableOption(
9449 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts())) {
9450 auto CXXRec
= PointeeType
.getCanonicalType()->getAsCXXRecordDecl();
9451 bool IsStandardLayoutType
= true;
9453 // If template type is not ODR-used its definition is only available
9454 // in the template definition not its instantiation.
9455 // FIXME: This logic doesn't work for types that depend on template
9456 // parameter (PR58590).
9457 if (!CXXRec
->hasDefinition())
9458 CXXRec
= CXXRec
->getTemplateInstantiationPattern();
9459 if (!CXXRec
|| !CXXRec
->hasDefinition() || !CXXRec
->isStandardLayout())
9460 IsStandardLayoutType
= false;
9462 if (!PointeeType
->isAtomicType() && !PointeeType
->isVoidType() &&
9463 !IsStandardLayoutType
)
9464 return InvalidKernelParam
;
9467 // OpenCL v1.2 s6.9.p:
9468 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9469 if (S
.getLangOpts().getOpenCLCompatibleVersion() > 120)
9470 return ValidKernelParam
;
9472 return PtrKernelParam
;
9475 // OpenCL v1.2 s6.9.k:
9476 // Arguments to kernel functions in a program cannot be declared with the
9477 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9478 // uintptr_t or a struct and/or union that contain fields declared to be one
9479 // of these built-in scalar types.
9480 if (isOpenCLSizeDependentType(S
.getASTContext(), PT
))
9481 return InvalidKernelParam
;
9483 if (PT
->isImageType())
9484 return PtrKernelParam
;
9486 if (PT
->isBooleanType() || PT
->isEventT() || PT
->isReserveIDT())
9487 return InvalidKernelParam
;
9489 // OpenCL extension spec v1.2 s9.5:
9490 // This extension adds support for half scalar and vector types as built-in
9491 // types that can be used for arithmetic operations, conversions etc.
9492 if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S
.getLangOpts()) &&
9494 return InvalidKernelParam
;
9496 // Look into an array argument to check if it has a forbidden type.
9497 if (PT
->isArrayType()) {
9498 const Type
*UnderlyingTy
= PT
->getPointeeOrArrayElementType();
9499 // Call ourself to check an underlying type of an array. Since the
9500 // getPointeeOrArrayElementType returns an innermost type which is not an
9501 // array, this recursive call only happens once.
9502 return getOpenCLKernelParameterType(S
, QualType(UnderlyingTy
, 0));
9505 // C++ for OpenCL v1.0 s2.4:
9506 // Moreover the types used in parameters of the kernel functions must be:
9507 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9508 // types) for parameters passed by value;
9509 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9510 !S
.getOpenCLOptions().isAvailableOption(
9511 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts()) &&
9512 !PT
->isOpenCLSpecificType() && !PT
.isPODType(S
.Context
))
9513 return InvalidKernelParam
;
9515 if (PT
->isRecordType())
9516 return RecordKernelParam
;
9518 return ValidKernelParam
;
9521 static void checkIsValidOpenCLKernelParameter(
9525 llvm::SmallPtrSetImpl
<const Type
*> &ValidTypes
) {
9526 QualType PT
= Param
->getType();
9528 // Cache the valid types we encounter to avoid rechecking structs that are
9530 if (ValidTypes
.count(PT
.getTypePtr()))
9533 switch (getOpenCLKernelParameterType(S
, PT
)) {
9534 case PtrPtrKernelParam
:
9535 // OpenCL v3.0 s6.11.a:
9536 // A kernel function argument cannot be declared as a pointer to a pointer
9537 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9538 S
.Diag(Param
->getLocation(), diag::err_opencl_ptrptr_kernel_param
);
9542 case InvalidAddrSpacePtrKernelParam
:
9543 // OpenCL v1.0 s6.5:
9544 // __kernel function arguments declared to be a pointer of a type can point
9545 // to one of the following address spaces only : __global, __local or
9547 S
.Diag(Param
->getLocation(), diag::err_kernel_arg_address_space
);
9551 // OpenCL v1.2 s6.9.k:
9552 // Arguments to kernel functions in a program cannot be declared with the
9553 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9554 // uintptr_t or a struct and/or union that contain fields declared to be
9555 // one of these built-in scalar types.
9557 case InvalidKernelParam
:
9558 // OpenCL v1.2 s6.8 n:
9559 // A kernel function argument cannot be declared
9561 // Do not diagnose half type since it is diagnosed as invalid argument
9562 // type for any function elsewhere.
9563 if (!PT
->isHalfType()) {
9564 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9566 // Explain what typedefs are involved.
9567 const TypedefType
*Typedef
= nullptr;
9568 while ((Typedef
= PT
->getAs
<TypedefType
>())) {
9569 SourceLocation Loc
= Typedef
->getDecl()->getLocation();
9570 // SourceLocation may be invalid for a built-in type.
9572 S
.Diag(Loc
, diag::note_entity_declared_at
) << PT
;
9573 PT
= Typedef
->desugar();
9580 case PtrKernelParam
:
9581 case ValidKernelParam
:
9582 ValidTypes
.insert(PT
.getTypePtr());
9585 case RecordKernelParam
:
9589 // Track nested structs we will inspect
9590 SmallVector
<const Decl
*, 4> VisitStack
;
9592 // Track where we are in the nested structs. Items will migrate from
9593 // VisitStack to HistoryStack as we do the DFS for bad field.
9594 SmallVector
<const FieldDecl
*, 4> HistoryStack
;
9595 HistoryStack
.push_back(nullptr);
9597 // At this point we already handled everything except of a RecordType or
9598 // an ArrayType of a RecordType.
9599 assert((PT
->isArrayType() || PT
->isRecordType()) && "Unexpected type.");
9600 const RecordType
*RecTy
=
9601 PT
->getPointeeOrArrayElementType()->getAs
<RecordType
>();
9602 const RecordDecl
*OrigRecDecl
= RecTy
->getDecl();
9604 VisitStack
.push_back(RecTy
->getDecl());
9605 assert(VisitStack
.back() && "First decl null?");
9608 const Decl
*Next
= VisitStack
.pop_back_val();
9610 assert(!HistoryStack
.empty());
9611 // Found a marker, we have gone up a level
9612 if (const FieldDecl
*Hist
= HistoryStack
.pop_back_val())
9613 ValidTypes
.insert(Hist
->getType().getTypePtr());
9618 // Adds everything except the original parameter declaration (which is not a
9619 // field itself) to the history stack.
9620 const RecordDecl
*RD
;
9621 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(Next
)) {
9622 HistoryStack
.push_back(Field
);
9624 QualType FieldTy
= Field
->getType();
9625 // Other field types (known to be valid or invalid) are handled while we
9626 // walk around RecordDecl::fields().
9627 assert((FieldTy
->isArrayType() || FieldTy
->isRecordType()) &&
9628 "Unexpected type.");
9629 const Type
*FieldRecTy
= FieldTy
->getPointeeOrArrayElementType();
9631 RD
= FieldRecTy
->castAs
<RecordType
>()->getDecl();
9633 RD
= cast
<RecordDecl
>(Next
);
9636 // Add a null marker so we know when we've gone back up a level
9637 VisitStack
.push_back(nullptr);
9639 for (const auto *FD
: RD
->fields()) {
9640 QualType QT
= FD
->getType();
9642 if (ValidTypes
.count(QT
.getTypePtr()))
9645 OpenCLParamType ParamType
= getOpenCLKernelParameterType(S
, QT
);
9646 if (ParamType
== ValidKernelParam
)
9649 if (ParamType
== RecordKernelParam
) {
9650 VisitStack
.push_back(FD
);
9654 // OpenCL v1.2 s6.9.p:
9655 // Arguments to kernel functions that are declared to be a struct or union
9656 // do not allow OpenCL objects to be passed as elements of the struct or
9657 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9659 if (ParamType
== PtrKernelParam
|| ParamType
== PtrPtrKernelParam
||
9660 ParamType
== InvalidAddrSpacePtrKernelParam
) {
9661 S
.Diag(Param
->getLocation(),
9662 diag::err_record_with_pointers_kernel_param
)
9663 << PT
->isUnionType()
9666 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9669 S
.Diag(OrigRecDecl
->getLocation(), diag::note_within_field_of_type
)
9670 << OrigRecDecl
->getDeclName();
9672 // We have an error, now let's go back up through history and show where
9673 // the offending field came from
9674 for (ArrayRef
<const FieldDecl
*>::const_iterator
9675 I
= HistoryStack
.begin() + 1,
9676 E
= HistoryStack
.end();
9678 const FieldDecl
*OuterField
= *I
;
9679 S
.Diag(OuterField
->getLocation(), diag::note_within_field_of_type
)
9680 << OuterField
->getType();
9683 S
.Diag(FD
->getLocation(), diag::note_illegal_field_declared_here
)
9684 << QT
->isPointerType()
9689 } while (!VisitStack
.empty());
9692 /// Find the DeclContext in which a tag is implicitly declared if we see an
9693 /// elaborated type specifier in the specified context, and lookup finds
9695 static DeclContext
*getTagInjectionContext(DeclContext
*DC
) {
9696 while (!DC
->isFileContext() && !DC
->isFunctionOrMethod())
9697 DC
= DC
->getParent();
9701 /// Find the Scope in which a tag is implicitly declared if we see an
9702 /// elaborated type specifier in the specified context, and lookup finds
9704 static Scope
*getTagInjectionScope(Scope
*S
, const LangOptions
&LangOpts
) {
9705 while (S
->isClassScope() ||
9706 (LangOpts
.CPlusPlus
&&
9707 S
->isFunctionPrototypeScope()) ||
9708 ((S
->getFlags() & Scope::DeclScope
) == 0) ||
9709 (S
->getEntity() && S
->getEntity()->isTransparentContext()))
9714 /// Determine whether a declaration matches a known function in namespace std.
9715 static bool isStdBuiltin(ASTContext
&Ctx
, FunctionDecl
*FD
,
9716 unsigned BuiltinID
) {
9717 switch (BuiltinID
) {
9718 case Builtin::BI__GetExceptionInfo
:
9719 // No type checking whatsoever.
9720 return Ctx
.getTargetInfo().getCXXABI().isMicrosoft();
9722 case Builtin::BIaddressof
:
9723 case Builtin::BI__addressof
:
9724 case Builtin::BIforward
:
9725 case Builtin::BIforward_like
:
9726 case Builtin::BImove
:
9727 case Builtin::BImove_if_noexcept
:
9728 case Builtin::BIas_const
: {
9729 // Ensure that we don't treat the algorithm
9730 // OutputIt std::move(InputIt, InputIt, OutputIt)
9731 // as the builtin std::move.
9732 const auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
9733 return FPT
->getNumParams() == 1 && !FPT
->isVariadic();
9742 Sema::ActOnFunctionDeclarator(Scope
*S
, Declarator
&D
, DeclContext
*DC
,
9743 TypeSourceInfo
*TInfo
, LookupResult
&Previous
,
9744 MultiTemplateParamsArg TemplateParamListsRef
,
9746 QualType R
= TInfo
->getType();
9748 assert(R
->isFunctionType());
9749 if (R
.getCanonicalType()->castAs
<FunctionType
>()->getCmseNSCallAttr())
9750 Diag(D
.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call
);
9752 SmallVector
<TemplateParameterList
*, 4> TemplateParamLists
;
9753 llvm::append_range(TemplateParamLists
, TemplateParamListsRef
);
9754 if (TemplateParameterList
*Invented
= D
.getInventedTemplateParameterList()) {
9755 if (!TemplateParamLists
.empty() &&
9756 Invented
->getDepth() == TemplateParamLists
.back()->getDepth())
9757 TemplateParamLists
.back() = Invented
;
9759 TemplateParamLists
.push_back(Invented
);
9762 // TODO: consider using NameInfo for diagnostic.
9763 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
9764 DeclarationName Name
= NameInfo
.getName();
9765 StorageClass SC
= getFunctionStorageClass(*this, D
);
9767 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
9768 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
9769 diag::err_invalid_thread
)
9770 << DeclSpec::getSpecifierName(TSCS
);
9772 if (D
.isFirstDeclarationOfMember())
9773 adjustMemberFunctionCC(
9774 R
, !(D
.isStaticMember() || D
.isExplicitObjectMemberFunction()),
9775 D
.isCtorOrDtor(), D
.getIdentifierLoc());
9777 bool isFriend
= false;
9778 FunctionTemplateDecl
*FunctionTemplate
= nullptr;
9779 bool isMemberSpecialization
= false;
9780 bool isFunctionTemplateSpecialization
= false;
9782 bool HasExplicitTemplateArgs
= false;
9783 TemplateArgumentListInfo TemplateArgs
;
9785 bool isVirtualOkay
= false;
9787 DeclContext
*OriginalDC
= DC
;
9788 bool IsLocalExternDecl
= adjustContextForLocalExternDecl(DC
);
9790 FunctionDecl
*NewFD
= CreateNewFunctionDecl(*this, D
, DC
, R
, TInfo
, SC
,
9792 if (!NewFD
) return nullptr;
9794 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer())
9795 NewFD
->setTopLevelDeclInObjCContainer();
9797 // Set the lexical context. If this is a function-scope declaration, or has a
9798 // C++ scope specifier, or is the object of a friend declaration, the lexical
9799 // context will be different from the semantic context.
9800 NewFD
->setLexicalDeclContext(CurContext
);
9802 if (IsLocalExternDecl
)
9803 NewFD
->setLocalExternDecl();
9805 if (getLangOpts().CPlusPlus
) {
9806 // The rules for implicit inlines changed in C++20 for methods and friends
9807 // with an in-class definition (when such a definition is not attached to
9808 // the global module). User-specified 'inline' overrides this (set when
9809 // the function decl is created above).
9810 // FIXME: We need a better way to separate C++ standard and clang modules.
9811 bool ImplicitInlineCXX20
= !getLangOpts().CPlusPlusModules
||
9812 !NewFD
->getOwningModule() ||
9813 NewFD
->getOwningModule()->isGlobalModule() ||
9814 NewFD
->getOwningModule()->isHeaderLikeModule();
9815 bool isInline
= D
.getDeclSpec().isInlineSpecified();
9816 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
9817 bool hasExplicit
= D
.getDeclSpec().hasExplicitSpecifier();
9818 isFriend
= D
.getDeclSpec().isFriendSpecified();
9819 if (isFriend
&& !isInline
&& D
.isFunctionDefinition()) {
9820 // Pre-C++20 [class.friend]p5
9821 // A function can be defined in a friend declaration of a
9822 // class . . . . Such a function is implicitly inline.
9823 // Post C++20 [class.friend]p7
9824 // Such a function is implicitly an inline function if it is attached
9825 // to the global module.
9826 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
9829 // If this is a method defined in an __interface, and is not a constructor
9830 // or an overloaded operator, then set the pure flag (isVirtual will already
9832 if (const CXXRecordDecl
*Parent
=
9833 dyn_cast
<CXXRecordDecl
>(NewFD
->getDeclContext())) {
9834 if (Parent
->isInterface() && cast
<CXXMethodDecl
>(NewFD
)->isUserProvided())
9835 NewFD
->setPure(true);
9837 // C++ [class.union]p2
9838 // A union can have member functions, but not virtual functions.
9839 if (isVirtual
&& Parent
->isUnion()) {
9840 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union
);
9841 NewFD
->setInvalidDecl();
9843 if ((Parent
->isClass() || Parent
->isStruct()) &&
9844 Parent
->hasAttr
<SYCLSpecialClassAttr
>() &&
9845 NewFD
->getKind() == Decl::Kind::CXXMethod
&& NewFD
->getIdentifier() &&
9846 NewFD
->getName() == "__init" && D
.isFunctionDefinition()) {
9847 if (auto *Def
= Parent
->getDefinition())
9848 Def
->setInitMethod(true);
9852 SetNestedNameSpecifier(*this, NewFD
, D
);
9853 isMemberSpecialization
= false;
9854 isFunctionTemplateSpecialization
= false;
9855 if (D
.isInvalidType())
9856 NewFD
->setInvalidDecl();
9858 // Match up the template parameter lists with the scope specifier, then
9859 // determine whether we have a template or a template specialization.
9860 bool Invalid
= false;
9861 TemplateParameterList
*TemplateParams
=
9862 MatchTemplateParametersToScopeSpecifier(
9863 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
9864 D
.getCXXScopeSpec(),
9865 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9866 ? D
.getName().TemplateId
9868 TemplateParamLists
, isFriend
, isMemberSpecialization
,
9870 if (TemplateParams
) {
9871 // Check that we can declare a template here.
9872 if (CheckTemplateDeclScope(S
, TemplateParams
))
9873 NewFD
->setInvalidDecl();
9875 if (TemplateParams
->size() > 0) {
9876 // This is a function template
9878 // A destructor cannot be a template.
9879 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
9880 Diag(NewFD
->getLocation(), diag::err_destructor_template
);
9881 NewFD
->setInvalidDecl();
9884 // If we're adding a template to a dependent context, we may need to
9885 // rebuilding some of the types used within the template parameter list,
9886 // now that we know what the current instantiation is.
9887 if (DC
->isDependentContext()) {
9888 ContextRAII
SavedContext(*this, DC
);
9889 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams
))
9893 FunctionTemplate
= FunctionTemplateDecl::Create(Context
, DC
,
9894 NewFD
->getLocation(),
9895 Name
, TemplateParams
,
9897 FunctionTemplate
->setLexicalDeclContext(CurContext
);
9898 NewFD
->setDescribedFunctionTemplate(FunctionTemplate
);
9900 // For source fidelity, store the other template param lists.
9901 if (TemplateParamLists
.size() > 1) {
9902 NewFD
->setTemplateParameterListsInfo(Context
,
9903 ArrayRef
<TemplateParameterList
*>(TemplateParamLists
)
9907 // This is a function template specialization.
9908 isFunctionTemplateSpecialization
= true;
9909 // For source fidelity, store all the template param lists.
9910 if (TemplateParamLists
.size() > 0)
9911 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9913 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9915 // We want to remove the "template<>", found here.
9916 SourceRange RemoveRange
= TemplateParams
->getSourceRange();
9918 // If we remove the template<> and the name is not a
9919 // template-id, we're actually silently creating a problem:
9920 // the friend declaration will refer to an untemplated decl,
9921 // and clearly the user wants a template specialization. So
9922 // we need to insert '<>' after the name.
9923 SourceLocation InsertLoc
;
9924 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
9925 InsertLoc
= D
.getName().getSourceRange().getEnd();
9926 InsertLoc
= getLocForEndOfToken(InsertLoc
);
9929 Diag(D
.getIdentifierLoc(), diag::err_template_spec_decl_friend
)
9930 << Name
<< RemoveRange
9931 << FixItHint::CreateRemoval(RemoveRange
)
9932 << FixItHint::CreateInsertion(InsertLoc
, "<>");
9937 // Check that we can declare a template here.
9938 if (!TemplateParamLists
.empty() && isMemberSpecialization
&&
9939 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
9940 NewFD
->setInvalidDecl();
9942 // All template param lists were matched against the scope specifier:
9943 // this is NOT (an explicit specialization of) a template.
9944 if (TemplateParamLists
.size() > 0)
9945 // For source fidelity, store all the template param lists.
9946 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9950 NewFD
->setInvalidDecl();
9951 if (FunctionTemplate
)
9952 FunctionTemplate
->setInvalidDecl();
9955 // C++ [dcl.fct.spec]p5:
9956 // The virtual specifier shall only be used in declarations of
9957 // nonstatic class member functions that appear within a
9958 // member-specification of a class declaration; see 10.3.
9960 if (isVirtual
&& !NewFD
->isInvalidDecl()) {
9961 if (!isVirtualOkay
) {
9962 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9963 diag::err_virtual_non_function
);
9964 } else if (!CurContext
->isRecord()) {
9965 // 'virtual' was specified outside of the class.
9966 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9967 diag::err_virtual_out_of_class
)
9968 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9969 } else if (NewFD
->getDescribedFunctionTemplate()) {
9970 // C++ [temp.mem]p3:
9971 // A member function template shall not be virtual.
9972 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9973 diag::err_virtual_member_function_template
)
9974 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9976 // Okay: Add virtual to the method.
9977 NewFD
->setVirtualAsWritten(true);
9980 if (getLangOpts().CPlusPlus14
&&
9981 NewFD
->getReturnType()->isUndeducedType())
9982 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual
);
9985 if (getLangOpts().CPlusPlus14
&&
9986 (NewFD
->isDependentContext() ||
9987 (isFriend
&& CurContext
->isDependentContext())) &&
9988 NewFD
->getReturnType()->isUndeducedType()) {
9989 // If the function template is referenced directly (for instance, as a
9990 // member of the current instantiation), pretend it has a dependent type.
9991 // This is not really justified by the standard, but is the only sane
9993 // FIXME: For a friend function, we have not marked the function as being
9994 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9995 const FunctionProtoType
*FPT
=
9996 NewFD
->getType()->castAs
<FunctionProtoType
>();
9997 QualType Result
= SubstAutoTypeDependent(FPT
->getReturnType());
9998 NewFD
->setType(Context
.getFunctionType(Result
, FPT
->getParamTypes(),
9999 FPT
->getExtProtoInfo()));
10002 // C++ [dcl.fct.spec]p3:
10003 // The inline specifier shall not appear on a block scope function
10005 if (isInline
&& !NewFD
->isInvalidDecl()) {
10006 if (CurContext
->isFunctionOrMethod()) {
10007 // 'inline' is not allowed on block scope function declaration.
10008 Diag(D
.getDeclSpec().getInlineSpecLoc(),
10009 diag::err_inline_declaration_block_scope
) << Name
10010 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
10014 // C++ [dcl.fct.spec]p6:
10015 // The explicit specifier shall be used only in the declaration of a
10016 // constructor or conversion function within its class definition;
10017 // see 12.3.1 and 12.3.2.
10018 if (hasExplicit
&& !NewFD
->isInvalidDecl() &&
10019 !isa
<CXXDeductionGuideDecl
>(NewFD
)) {
10020 if (!CurContext
->isRecord()) {
10021 // 'explicit' was specified outside of the class.
10022 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
10023 diag::err_explicit_out_of_class
)
10024 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
10025 } else if (!isa
<CXXConstructorDecl
>(NewFD
) &&
10026 !isa
<CXXConversionDecl
>(NewFD
)) {
10027 // 'explicit' was specified on a function that wasn't a constructor
10028 // or conversion function.
10029 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
10030 diag::err_explicit_non_ctor_or_conv_function
)
10031 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
10035 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
10036 if (ConstexprKind
!= ConstexprSpecKind::Unspecified
) {
10037 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10038 // are implicitly inline.
10039 NewFD
->setImplicitlyInline();
10041 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10042 // be either constructors or to return a literal type. Therefore,
10043 // destructors cannot be declared constexpr.
10044 if (isa
<CXXDestructorDecl
>(NewFD
) &&
10045 (!getLangOpts().CPlusPlus20
||
10046 ConstexprKind
== ConstexprSpecKind::Consteval
)) {
10047 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor
)
10048 << static_cast<int>(ConstexprKind
);
10049 NewFD
->setConstexprKind(getLangOpts().CPlusPlus20
10050 ? ConstexprSpecKind::Unspecified
10051 : ConstexprSpecKind::Constexpr
);
10053 // C++20 [dcl.constexpr]p2: An allocation function, or a
10054 // deallocation function shall not be declared with the consteval
10056 if (ConstexprKind
== ConstexprSpecKind::Consteval
&&
10057 (NewFD
->getOverloadedOperator() == OO_New
||
10058 NewFD
->getOverloadedOperator() == OO_Array_New
||
10059 NewFD
->getOverloadedOperator() == OO_Delete
||
10060 NewFD
->getOverloadedOperator() == OO_Array_Delete
)) {
10061 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
10062 diag::err_invalid_consteval_decl_kind
)
10064 NewFD
->setConstexprKind(ConstexprSpecKind::Constexpr
);
10068 // If __module_private__ was specified, mark the function accordingly.
10069 if (D
.getDeclSpec().isModulePrivateSpecified()) {
10070 if (isFunctionTemplateSpecialization
) {
10071 SourceLocation ModulePrivateLoc
10072 = D
.getDeclSpec().getModulePrivateSpecLoc();
10073 Diag(ModulePrivateLoc
, diag::err_module_private_specialization
)
10075 << FixItHint::CreateRemoval(ModulePrivateLoc
);
10077 NewFD
->setModulePrivate();
10078 if (FunctionTemplate
)
10079 FunctionTemplate
->setModulePrivate();
10084 if (FunctionTemplate
) {
10085 FunctionTemplate
->setObjectOfFriendDecl();
10086 FunctionTemplate
->setAccess(AS_public
);
10088 NewFD
->setObjectOfFriendDecl();
10089 NewFD
->setAccess(AS_public
);
10092 // If a function is defined as defaulted or deleted, mark it as such now.
10093 // We'll do the relevant checks on defaulted / deleted functions later.
10094 switch (D
.getFunctionDefinitionKind()) {
10095 case FunctionDefinitionKind::Declaration
:
10096 case FunctionDefinitionKind::Definition
:
10099 case FunctionDefinitionKind::Defaulted
:
10100 NewFD
->setDefaulted();
10103 case FunctionDefinitionKind::Deleted
:
10104 NewFD
->setDeletedAsWritten();
10108 if (isa
<CXXMethodDecl
>(NewFD
) && DC
== CurContext
&&
10109 D
.isFunctionDefinition() && !isInline
) {
10110 // Pre C++20 [class.mfct]p2:
10111 // A member function may be defined (8.4) in its class definition, in
10112 // which case it is an inline member function (7.1.2)
10113 // Post C++20 [class.mfct]p1:
10114 // If a member function is attached to the global module and is defined
10115 // in its class definition, it is inline.
10116 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
10119 if (SC
== SC_Static
&& isa
<CXXMethodDecl
>(NewFD
) &&
10120 !CurContext
->isRecord()) {
10121 // C++ [class.static]p1:
10122 // A data or function member of a class may be declared static
10123 // in a class definition, in which case it is a static member of
10126 // Complain about the 'static' specifier if it's on an out-of-line
10127 // member function definition.
10129 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10130 // member function template declaration and class member template
10131 // declaration (MSVC versions before 2015), warn about this.
10132 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
10133 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
10134 cast
<CXXRecordDecl
>(DC
)->getDescribedClassTemplate()) ||
10135 (getLangOpts().MSVCCompat
&& NewFD
->getDescribedFunctionTemplate()))
10136 ? diag::ext_static_out_of_line
: diag::err_static_out_of_line
)
10137 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
10140 // C++11 [except.spec]p15:
10141 // A deallocation function with no exception-specification is treated
10142 // as if it were specified with noexcept(true).
10143 const FunctionProtoType
*FPT
= R
->getAs
<FunctionProtoType
>();
10144 if ((Name
.getCXXOverloadedOperator() == OO_Delete
||
10145 Name
.getCXXOverloadedOperator() == OO_Array_Delete
) &&
10146 getLangOpts().CPlusPlus11
&& FPT
&& !FPT
->hasExceptionSpec())
10147 NewFD
->setType(Context
.getFunctionType(
10148 FPT
->getReturnType(), FPT
->getParamTypes(),
10149 FPT
->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept
)));
10151 // C++20 [dcl.inline]/7
10152 // If an inline function or variable that is attached to a named module
10153 // is declared in a definition domain, it shall be defined in that
10155 // So, if the current declaration does not have a definition, we must
10156 // check at the end of the TU (or when the PMF starts) to see that we
10157 // have a definition at that point.
10158 if (isInline
&& !D
.isFunctionDefinition() && getLangOpts().CPlusPlus20
&&
10159 NewFD
->hasOwningModule() &&
10160 NewFD
->getOwningModule()->isModulePurview()) {
10161 PendingInlineFuncDecls
.insert(NewFD
);
10165 // Filter out previous declarations that don't match the scope.
10166 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewFD
),
10167 D
.getCXXScopeSpec().isNotEmpty() ||
10168 isMemberSpecialization
||
10169 isFunctionTemplateSpecialization
);
10171 // Handle GNU asm-label extension (encoded as an attribute).
10172 if (Expr
*E
= (Expr
*) D
.getAsmLabel()) {
10173 // The parser guarantees this is a string.
10174 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
10175 NewFD
->addAttr(AsmLabelAttr::Create(Context
, SE
->getString(),
10176 /*IsLiteralLabel=*/true,
10177 SE
->getStrTokenLoc(0)));
10178 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
10179 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
10180 ExtnameUndeclaredIdentifiers
.find(NewFD
->getIdentifier());
10181 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
10182 if (isDeclExternC(NewFD
)) {
10183 NewFD
->addAttr(I
->second
);
10184 ExtnameUndeclaredIdentifiers
.erase(I
);
10186 Diag(NewFD
->getLocation(), diag::warn_redefine_extname_not_applied
)
10187 << /*Variable*/0 << NewFD
;
10191 // Copy the parameter declarations from the declarator D to the function
10192 // declaration NewFD, if they are available. First scavenge them into Params.
10193 SmallVector
<ParmVarDecl
*, 16> Params
;
10195 if (D
.isFunctionDeclarator(FTIIdx
)) {
10196 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getTypeObject(FTIIdx
).Fun
;
10198 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10199 // function that takes no arguments, not a function that takes a
10200 // single void argument.
10201 // We let through "const void" here because Sema::GetTypeForDeclarator
10202 // already checks for that case.
10203 if (FTIHasNonVoidParameters(FTI
) && FTI
.Params
[0].Param
) {
10204 for (unsigned i
= 0, e
= FTI
.NumParams
; i
!= e
; ++i
) {
10205 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.Params
[i
].Param
);
10206 assert(Param
->getDeclContext() != NewFD
&& "Was set before ?");
10207 Param
->setDeclContext(NewFD
);
10208 Params
.push_back(Param
);
10210 if (Param
->isInvalidDecl())
10211 NewFD
->setInvalidDecl();
10215 if (!getLangOpts().CPlusPlus
) {
10216 // In C, find all the tag declarations from the prototype and move them
10217 // into the function DeclContext. Remove them from the surrounding tag
10218 // injection context of the function, which is typically but not always
10220 DeclContext
*PrototypeTagContext
=
10221 getTagInjectionContext(NewFD
->getLexicalDeclContext());
10222 for (NamedDecl
*NonParmDecl
: FTI
.getDeclsInPrototype()) {
10223 auto *TD
= dyn_cast
<TagDecl
>(NonParmDecl
);
10225 // We don't want to reparent enumerators. Look at their parent enum
10228 if (auto *ECD
= dyn_cast
<EnumConstantDecl
>(NonParmDecl
))
10229 TD
= cast
<EnumDecl
>(ECD
->getDeclContext());
10233 DeclContext
*TagDC
= TD
->getLexicalDeclContext();
10234 if (!TagDC
->containsDecl(TD
))
10236 TagDC
->removeDecl(TD
);
10237 TD
->setDeclContext(NewFD
);
10238 NewFD
->addDecl(TD
);
10240 // Preserve the lexical DeclContext if it is not the surrounding tag
10241 // injection context of the FD. In this example, the semantic context of
10242 // E will be f and the lexical context will be S, while both the
10243 // semantic and lexical contexts of S will be f:
10244 // void f(struct S { enum E { a } f; } s);
10245 if (TagDC
!= PrototypeTagContext
)
10246 TD
->setLexicalDeclContext(TagDC
);
10249 } else if (const FunctionProtoType
*FT
= R
->getAs
<FunctionProtoType
>()) {
10250 // When we're declaring a function with a typedef, typeof, etc as in the
10251 // following example, we'll need to synthesize (unnamed)
10252 // parameters for use in the declaration.
10255 // typedef void fn(int);
10259 // Synthesize a parameter for each argument type.
10260 for (const auto &AI
: FT
->param_types()) {
10261 ParmVarDecl
*Param
=
10262 BuildParmVarDeclForTypedef(NewFD
, D
.getIdentifierLoc(), AI
);
10263 Param
->setScopeInfo(0, Params
.size());
10264 Params
.push_back(Param
);
10267 assert(R
->isFunctionNoProtoType() && NewFD
->getNumParams() == 0 &&
10268 "Should not need args for typedef of non-prototype fn");
10271 // Finally, we know we have the right number of parameters, install them.
10272 NewFD
->setParams(Params
);
10274 if (D
.getDeclSpec().isNoreturnSpecified())
10276 C11NoReturnAttr::Create(Context
, D
.getDeclSpec().getNoreturnSpecLoc()));
10278 // Functions returning a variably modified type violate C99 6.7.5.2p2
10279 // because all functions have linkage.
10280 if (!NewFD
->isInvalidDecl() &&
10281 NewFD
->getReturnType()->isVariablyModifiedType()) {
10282 Diag(NewFD
->getLocation(), diag::err_vm_func_decl
);
10283 NewFD
->setInvalidDecl();
10286 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10287 if (PragmaClangTextSection
.Valid
&& D
.isFunctionDefinition() &&
10288 !NewFD
->hasAttr
<SectionAttr
>())
10289 NewFD
->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10290 Context
, PragmaClangTextSection
.SectionName
,
10291 PragmaClangTextSection
.PragmaLocation
));
10293 // Apply an implicit SectionAttr if #pragma code_seg is active.
10294 if (CodeSegStack
.CurrentValue
&& D
.isFunctionDefinition() &&
10295 !NewFD
->hasAttr
<SectionAttr
>()) {
10296 NewFD
->addAttr(SectionAttr::CreateImplicit(
10297 Context
, CodeSegStack
.CurrentValue
->getString(),
10298 CodeSegStack
.CurrentPragmaLocation
, SectionAttr::Declspec_allocate
));
10299 if (UnifySection(CodeSegStack
.CurrentValue
->getString(),
10300 ASTContext::PSF_Implicit
| ASTContext::PSF_Execute
|
10301 ASTContext::PSF_Read
,
10303 NewFD
->dropAttr
<SectionAttr
>();
10306 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10308 if (StrictGuardStackCheckStack
.CurrentValue
&& D
.isFunctionDefinition() &&
10309 !NewFD
->hasAttr
<StrictGuardStackCheckAttr
>())
10310 NewFD
->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10311 Context
, PragmaClangTextSection
.PragmaLocation
));
10313 // Apply an implicit CodeSegAttr from class declspec or
10314 // apply an implicit SectionAttr from #pragma code_seg if active.
10315 if (!NewFD
->hasAttr
<CodeSegAttr
>()) {
10316 if (Attr
*SAttr
= getImplicitCodeSegOrSectionAttrForFunction(NewFD
,
10317 D
.isFunctionDefinition())) {
10318 NewFD
->addAttr(SAttr
);
10322 // Handle attributes.
10323 ProcessDeclAttributes(S
, NewFD
, D
);
10324 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
10325 if (NewTVA
&& !NewTVA
->isDefaultVersion() &&
10326 !Context
.getTargetInfo().hasFeature("fmv")) {
10327 // Don't add to scope fmv functions declarations if fmv disabled
10328 AddToScope
= false;
10332 if (getLangOpts().OpenCL
|| getLangOpts().HLSL
) {
10333 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10336 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10337 // type declaration will generate a compilation error.
10338 LangAS AddressSpace
= NewFD
->getReturnType().getAddressSpace();
10339 if (AddressSpace
!= LangAS::Default
) {
10340 Diag(NewFD
->getLocation(), diag::err_return_value_with_address_space
);
10341 NewFD
->setInvalidDecl();
10345 if (!getLangOpts().CPlusPlus
) {
10346 // Perform semantic checking on the function declaration.
10347 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10348 CheckMain(NewFD
, D
.getDeclSpec());
10350 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10351 CheckMSVCRTEntryPoint(NewFD
);
10353 if (!NewFD
->isInvalidDecl())
10354 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10355 isMemberSpecialization
,
10356 D
.isFunctionDefinition()));
10357 else if (!Previous
.empty())
10358 // Recover gracefully from an invalid redeclaration.
10359 D
.setRedeclaration(true);
10360 assert((NewFD
->isInvalidDecl() || !D
.isRedeclaration() ||
10361 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10362 "previous declaration set still overloaded");
10364 // Diagnose no-prototype function declarations with calling conventions that
10365 // don't support variadic calls. Only do this in C and do it after merging
10366 // possibly prototyped redeclarations.
10367 const FunctionType
*FT
= NewFD
->getType()->castAs
<FunctionType
>();
10368 if (isa
<FunctionNoProtoType
>(FT
) && !D
.isFunctionDefinition()) {
10369 CallingConv CC
= FT
->getExtInfo().getCC();
10370 if (!supportsVariadicCall(CC
)) {
10371 // Windows system headers sometimes accidentally use stdcall without
10372 // (void) parameters, so we relax this to a warning.
10374 CC
== CC_X86StdCall
? diag::warn_cconv_knr
: diag::err_cconv_knr
;
10375 Diag(NewFD
->getLocation(), DiagID
)
10376 << FunctionType::getNameForCallConv(CC
);
10380 if (NewFD
->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10381 NewFD
->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10382 checkNonTrivialCUnion(NewFD
->getReturnType(),
10383 NewFD
->getReturnTypeSourceRange().getBegin(),
10384 NTCUC_FunctionReturn
, NTCUK_Destruct
|NTCUK_Copy
);
10386 // C++11 [replacement.functions]p3:
10387 // The program's definitions shall not be specified as inline.
10389 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10391 // Suppress the diagnostic if the function is __attribute__((used)), since
10392 // that forces an external definition to be emitted.
10393 if (D
.getDeclSpec().isInlineSpecified() &&
10394 NewFD
->isReplaceableGlobalAllocationFunction() &&
10395 !NewFD
->hasAttr
<UsedAttr
>())
10396 Diag(D
.getDeclSpec().getInlineSpecLoc(),
10397 diag::ext_operator_new_delete_declared_inline
)
10398 << NewFD
->getDeclName();
10400 // If the declarator is a template-id, translate the parser's template
10401 // argument list into our AST format.
10402 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
10403 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
10404 TemplateArgs
.setLAngleLoc(TemplateId
->LAngleLoc
);
10405 TemplateArgs
.setRAngleLoc(TemplateId
->RAngleLoc
);
10406 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
10407 TemplateId
->NumArgs
);
10408 translateTemplateArguments(TemplateArgsPtr
,
10411 HasExplicitTemplateArgs
= true;
10413 if (NewFD
->isInvalidDecl()) {
10414 HasExplicitTemplateArgs
= false;
10415 } else if (FunctionTemplate
) {
10416 // Function template with explicit template arguments.
10417 Diag(D
.getIdentifierLoc(), diag::err_function_template_partial_spec
)
10418 << SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
);
10420 HasExplicitTemplateArgs
= false;
10421 } else if (isFriend
) {
10422 // "friend void foo<>(int);" is an implicit specialization decl.
10423 isFunctionTemplateSpecialization
= true;
10425 assert(isFunctionTemplateSpecialization
&&
10426 "should have a 'template<>' for this decl");
10428 } else if (isFriend
&& isFunctionTemplateSpecialization
) {
10429 // This combination is only possible in a recovery case; the user
10430 // wrote something like:
10431 // template <> friend void foo(int);
10432 // which we're recovering from as if the user had written:
10433 // friend void foo<>(int);
10434 // Go ahead and fake up a template id.
10435 HasExplicitTemplateArgs
= true;
10436 TemplateArgs
.setLAngleLoc(D
.getIdentifierLoc());
10437 TemplateArgs
.setRAngleLoc(D
.getIdentifierLoc());
10440 // We do not add HD attributes to specializations here because
10441 // they may have different constexpr-ness compared to their
10442 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10443 // may end up with different effective targets. Instead, a
10444 // specialization inherits its target attributes from its template
10445 // in the CheckFunctionTemplateSpecialization() call below.
10446 if (getLangOpts().CUDA
&& !isFunctionTemplateSpecialization
)
10447 maybeAddCUDAHostDeviceAttrs(NewFD
, Previous
);
10449 // Handle explict specializations of function templates
10450 // and friend function declarations with an explicit
10451 // template argument list.
10452 if (isFunctionTemplateSpecialization
) {
10453 bool isDependentSpecialization
= false;
10455 // For friend function specializations, this is a dependent
10456 // specialization if its semantic context is dependent, its
10457 // type is dependent, or if its template-id is dependent.
10458 isDependentSpecialization
=
10459 DC
->isDependentContext() || NewFD
->getType()->isDependentType() ||
10460 (HasExplicitTemplateArgs
&&
10461 TemplateSpecializationType::
10462 anyInstantiationDependentTemplateArguments(
10463 TemplateArgs
.arguments()));
10464 assert((!isDependentSpecialization
||
10465 (HasExplicitTemplateArgs
== isDependentSpecialization
)) &&
10466 "dependent friend function specialization without template "
10469 // For class-scope explicit specializations of function templates,
10470 // if the lexical context is dependent, then the specialization
10472 isDependentSpecialization
=
10473 CurContext
->isRecord() && CurContext
->isDependentContext();
10476 TemplateArgumentListInfo
*ExplicitTemplateArgs
=
10477 HasExplicitTemplateArgs
? &TemplateArgs
: nullptr;
10478 if (isDependentSpecialization
) {
10479 // If it's a dependent specialization, it may not be possible
10480 // to determine the primary template (for explicit specializations)
10481 // or befriended declaration (for friends) until the enclosing
10482 // template is instantiated. In such cases, we store the declarations
10483 // found by name lookup and defer resolution until instantiation.
10484 if (CheckDependentFunctionTemplateSpecialization(
10485 NewFD
, ExplicitTemplateArgs
, Previous
))
10486 NewFD
->setInvalidDecl();
10487 } else if (!NewFD
->isInvalidDecl()) {
10488 if (CheckFunctionTemplateSpecialization(NewFD
, ExplicitTemplateArgs
,
10490 NewFD
->setInvalidDecl();
10493 // C++ [dcl.stc]p1:
10494 // A storage-class-specifier shall not be specified in an explicit
10495 // specialization (14.7.3)
10496 // FIXME: We should be checking this for dependent specializations.
10497 FunctionTemplateSpecializationInfo
*Info
=
10498 NewFD
->getTemplateSpecializationInfo();
10499 if (Info
&& SC
!= SC_None
) {
10500 if (SC
!= Info
->getTemplate()->getTemplatedDecl()->getStorageClass())
10501 Diag(NewFD
->getLocation(),
10502 diag::err_explicit_specialization_inconsistent_storage_class
)
10504 << FixItHint::CreateRemoval(
10505 D
.getDeclSpec().getStorageClassSpecLoc());
10508 Diag(NewFD
->getLocation(),
10509 diag::ext_explicit_specialization_storage_class
)
10510 << FixItHint::CreateRemoval(
10511 D
.getDeclSpec().getStorageClassSpecLoc());
10513 } else if (isMemberSpecialization
&& isa
<CXXMethodDecl
>(NewFD
)) {
10514 if (CheckMemberSpecialization(NewFD
, Previous
))
10515 NewFD
->setInvalidDecl();
10518 // Perform semantic checking on the function declaration.
10519 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10520 CheckMain(NewFD
, D
.getDeclSpec());
10522 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10523 CheckMSVCRTEntryPoint(NewFD
);
10525 if (!NewFD
->isInvalidDecl())
10526 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10527 isMemberSpecialization
,
10528 D
.isFunctionDefinition()));
10529 else if (!Previous
.empty())
10530 // Recover gracefully from an invalid redeclaration.
10531 D
.setRedeclaration(true);
10533 assert((NewFD
->isInvalidDecl() || NewFD
->isMultiVersion() ||
10534 !D
.isRedeclaration() ||
10535 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10536 "previous declaration set still overloaded");
10538 NamedDecl
*PrincipalDecl
= (FunctionTemplate
10539 ? cast
<NamedDecl
>(FunctionTemplate
)
10542 if (isFriend
&& NewFD
->getPreviousDecl()) {
10543 AccessSpecifier Access
= AS_public
;
10544 if (!NewFD
->isInvalidDecl())
10545 Access
= NewFD
->getPreviousDecl()->getAccess();
10547 NewFD
->setAccess(Access
);
10548 if (FunctionTemplate
) FunctionTemplate
->setAccess(Access
);
10551 if (NewFD
->isOverloadedOperator() && !DC
->isRecord() &&
10552 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
10553 PrincipalDecl
->setNonMemberOperator();
10555 // If we have a function template, check the template parameter
10556 // list. This will check and merge default template arguments.
10557 if (FunctionTemplate
) {
10558 FunctionTemplateDecl
*PrevTemplate
=
10559 FunctionTemplate
->getPreviousDecl();
10560 CheckTemplateParameterList(FunctionTemplate
->getTemplateParameters(),
10561 PrevTemplate
? PrevTemplate
->getTemplateParameters()
10563 D
.getDeclSpec().isFriendSpecified()
10564 ? (D
.isFunctionDefinition()
10565 ? TPC_FriendFunctionTemplateDefinition
10566 : TPC_FriendFunctionTemplate
)
10567 : (D
.getCXXScopeSpec().isSet() &&
10568 DC
&& DC
->isRecord() &&
10569 DC
->isDependentContext())
10570 ? TPC_ClassTemplateMember
10571 : TPC_FunctionTemplate
);
10574 if (NewFD
->isInvalidDecl()) {
10575 // Ignore all the rest of this.
10576 } else if (!D
.isRedeclaration()) {
10577 struct ActOnFDArgs ExtraArgs
= { S
, D
, TemplateParamLists
,
10579 // Fake up an access specifier if it's supposed to be a class member.
10580 if (isa
<CXXRecordDecl
>(NewFD
->getDeclContext()))
10581 NewFD
->setAccess(AS_public
);
10583 // Qualified decls generally require a previous declaration.
10584 if (D
.getCXXScopeSpec().isSet()) {
10585 // ...with the major exception of templated-scope or
10586 // dependent-scope friend declarations.
10588 // TODO: we currently also suppress this check in dependent
10589 // contexts because (1) the parameter depth will be off when
10590 // matching friend templates and (2) we might actually be
10591 // selecting a friend based on a dependent factor. But there
10592 // are situations where these conditions don't apply and we
10593 // can actually do this check immediately.
10595 // Unless the scope is dependent, it's always an error if qualified
10596 // redeclaration lookup found nothing at all. Diagnose that now;
10597 // nothing will diagnose that error later.
10599 (D
.getCXXScopeSpec().getScopeRep()->isDependent() ||
10600 (!Previous
.empty() && CurContext
->isDependentContext()))) {
10602 } else if (NewFD
->isCPUDispatchMultiVersion() ||
10603 NewFD
->isCPUSpecificMultiVersion()) {
10604 // ignore this, we allow the redeclaration behavior here to create new
10605 // versions of the function.
10607 // The user tried to provide an out-of-line definition for a
10608 // function that is a member of a class or namespace, but there
10609 // was no such member function declared (C++ [class.mfct]p2,
10610 // C++ [namespace.memdef]p2). For example:
10616 // void X::f() { } // ill-formed
10618 // Complain about this problem, and attempt to suggest close
10619 // matches (e.g., those that differ only in cv-qualifiers and
10620 // whether the parameter types are references).
10622 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10623 *this, Previous
, NewFD
, ExtraArgs
, false, nullptr)) {
10624 AddToScope
= ExtraArgs
.AddToScope
;
10629 // Unqualified local friend declarations are required to resolve
10631 } else if (isFriend
&& cast
<CXXRecordDecl
>(CurContext
)->isLocalClass()) {
10632 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10633 *this, Previous
, NewFD
, ExtraArgs
, true, S
)) {
10634 AddToScope
= ExtraArgs
.AddToScope
;
10638 } else if (!D
.isFunctionDefinition() &&
10639 isa
<CXXMethodDecl
>(NewFD
) && NewFD
->isOutOfLine() &&
10640 !isFriend
&& !isFunctionTemplateSpecialization
&&
10641 !isMemberSpecialization
) {
10642 // An out-of-line member function declaration must also be a
10643 // definition (C++ [class.mfct]p2).
10644 // Note that this is not the case for explicit specializations of
10645 // function templates or member functions of class templates, per
10646 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10647 // extension for compatibility with old SWIG code which likes to
10649 Diag(NewFD
->getLocation(), diag::ext_out_of_line_declaration
)
10650 << D
.getCXXScopeSpec().getRange();
10654 if (getLangOpts().HLSL
&& D
.isFunctionDefinition()) {
10655 // Any top level function could potentially be specified as an entry.
10656 if (!NewFD
->isInvalidDecl() && S
->getDepth() == 0 && Name
.isIdentifier())
10657 ActOnHLSLTopLevelFunction(NewFD
);
10659 if (NewFD
->hasAttr
<HLSLShaderAttr
>())
10660 CheckHLSLEntryPoint(NewFD
);
10663 // If this is the first declaration of a library builtin function, add
10664 // attributes as appropriate.
10665 if (!D
.isRedeclaration()) {
10666 if (IdentifierInfo
*II
= Previous
.getLookupName().getAsIdentifierInfo()) {
10667 if (unsigned BuiltinID
= II
->getBuiltinID()) {
10668 bool InStdNamespace
= Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
);
10669 if (!InStdNamespace
&&
10670 NewFD
->getDeclContext()->getRedeclContext()->isFileContext()) {
10671 if (NewFD
->getLanguageLinkage() == CLanguageLinkage
) {
10672 // Validate the type matches unless this builtin is specified as
10673 // matching regardless of its declared type.
10674 if (Context
.BuiltinInfo
.allowTypeMismatch(BuiltinID
)) {
10675 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10677 ASTContext::GetBuiltinTypeError Error
;
10678 LookupNecessaryTypesForBuiltin(S
, BuiltinID
);
10679 QualType BuiltinType
= Context
.GetBuiltinType(BuiltinID
, Error
);
10681 if (!Error
&& !BuiltinType
.isNull() &&
10682 Context
.hasSameFunctionTypeIgnoringExceptionSpec(
10683 NewFD
->getType(), BuiltinType
))
10684 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10687 } else if (InStdNamespace
&& NewFD
->isInStdNamespace() &&
10688 isStdBuiltin(Context
, NewFD
, BuiltinID
)) {
10689 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10695 ProcessPragmaWeak(S
, NewFD
);
10696 checkAttributesAfterMerging(*this, *NewFD
);
10698 AddKnownFunctionAttributes(NewFD
);
10700 if (NewFD
->hasAttr
<OverloadableAttr
>() &&
10701 !NewFD
->getType()->getAs
<FunctionProtoType
>()) {
10702 Diag(NewFD
->getLocation(),
10703 diag::err_attribute_overloadable_no_prototype
)
10705 NewFD
->dropAttr
<OverloadableAttr
>();
10708 // If there's a #pragma GCC visibility in scope, and this isn't a class
10709 // member, set the visibility of this function.
10710 if (!DC
->isRecord() && NewFD
->isExternallyVisible())
10711 AddPushedVisibilityAttribute(NewFD
);
10713 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10714 // marking the function.
10715 AddCFAuditedAttribute(NewFD
);
10717 // If this is a function definition, check if we have to apply any
10718 // attributes (i.e. optnone and no_builtin) due to a pragma.
10719 if (D
.isFunctionDefinition()) {
10720 AddRangeBasedOptnone(NewFD
);
10721 AddImplicitMSFunctionNoBuiltinAttr(NewFD
);
10722 AddSectionMSAllocText(NewFD
);
10723 ModifyFnAttributesMSPragmaOptimize(NewFD
);
10726 // If this is the first declaration of an extern C variable, update
10727 // the map of such variables.
10728 if (NewFD
->isFirstDecl() && !NewFD
->isInvalidDecl() &&
10729 isIncompleteDeclExternC(*this, NewFD
))
10730 RegisterLocallyScopedExternCDecl(NewFD
, S
);
10732 // Set this FunctionDecl's range up to the right paren.
10733 NewFD
->setRangeEnd(D
.getSourceRange().getEnd());
10735 if (D
.isRedeclaration() && !Previous
.empty()) {
10736 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
10737 checkDLLAttributeRedeclaration(*this, Prev
, NewFD
,
10738 isMemberSpecialization
||
10739 isFunctionTemplateSpecialization
,
10740 D
.isFunctionDefinition());
10743 if (getLangOpts().CUDA
) {
10744 IdentifierInfo
*II
= NewFD
->getIdentifier();
10745 if (II
&& II
->isStr(getCudaConfigureFuncName()) &&
10746 !NewFD
->isInvalidDecl() &&
10747 NewFD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10748 if (!R
->castAs
<FunctionType
>()->getReturnType()->isScalarType())
10749 Diag(NewFD
->getLocation(), diag::err_config_scalar_return
)
10750 << getCudaConfigureFuncName();
10751 Context
.setcudaConfigureCallDecl(NewFD
);
10754 // Variadic functions, other than a *declaration* of printf, are not allowed
10755 // in device-side CUDA code, unless someone passed
10756 // -fcuda-allow-variadic-functions.
10757 if (!getLangOpts().CUDAAllowVariadicFunctions
&& NewFD
->isVariadic() &&
10758 (NewFD
->hasAttr
<CUDADeviceAttr
>() ||
10759 NewFD
->hasAttr
<CUDAGlobalAttr
>()) &&
10760 !(II
&& II
->isStr("printf") && NewFD
->isExternC() &&
10761 !D
.isFunctionDefinition())) {
10762 Diag(NewFD
->getLocation(), diag::err_variadic_device_fn
);
10766 MarkUnusedFileScopedDecl(NewFD
);
10770 if (getLangOpts().OpenCL
&& NewFD
->hasAttr
<OpenCLKernelAttr
>()) {
10771 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10772 if (SC
== SC_Static
) {
10773 Diag(D
.getIdentifierLoc(), diag::err_static_kernel
);
10774 D
.setInvalidType();
10777 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10778 if (!NewFD
->getReturnType()->isVoidType()) {
10779 SourceRange RTRange
= NewFD
->getReturnTypeSourceRange();
10780 Diag(D
.getIdentifierLoc(), diag::err_expected_kernel_void_return_type
)
10781 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "void")
10783 D
.setInvalidType();
10786 llvm::SmallPtrSet
<const Type
*, 16> ValidTypes
;
10787 for (auto *Param
: NewFD
->parameters())
10788 checkIsValidOpenCLKernelParameter(*this, D
, Param
, ValidTypes
);
10790 if (getLangOpts().OpenCLCPlusPlus
) {
10791 if (DC
->isRecord()) {
10792 Diag(D
.getIdentifierLoc(), diag::err_method_kernel
);
10793 D
.setInvalidType();
10795 if (FunctionTemplate
) {
10796 Diag(D
.getIdentifierLoc(), diag::err_template_kernel
);
10797 D
.setInvalidType();
10802 if (getLangOpts().CPlusPlus
) {
10803 // Precalculate whether this is a friend function template with a constraint
10804 // that depends on an enclosing template, per [temp.friend]p9.
10805 if (isFriend
&& FunctionTemplate
&&
10806 FriendConstraintsDependOnEnclosingTemplate(NewFD
))
10807 NewFD
->setFriendConstraintRefersToEnclosingTemplate(true);
10809 if (FunctionTemplate
) {
10810 if (NewFD
->isInvalidDecl())
10811 FunctionTemplate
->setInvalidDecl();
10812 return FunctionTemplate
;
10815 if (isMemberSpecialization
&& !NewFD
->isInvalidDecl())
10816 CompleteMemberSpecialization(NewFD
, Previous
);
10819 for (const ParmVarDecl
*Param
: NewFD
->parameters()) {
10820 QualType PT
= Param
->getType();
10822 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10824 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10825 if(const PipeType
*PipeTy
= PT
->getAs
<PipeType
>()) {
10826 QualType ElemTy
= PipeTy
->getElementType();
10827 if (ElemTy
->isReferenceType() || ElemTy
->isPointerType()) {
10828 Diag(Param
->getTypeSpecStartLoc(), diag::err_reference_pipe_type
);
10829 D
.setInvalidType();
10833 // WebAssembly tables can't be used as function parameters.
10834 if (Context
.getTargetInfo().getTriple().isWasm()) {
10835 if (PT
->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10836 Diag(Param
->getTypeSpecStartLoc(),
10837 diag::err_wasm_table_as_function_parameter
);
10838 D
.setInvalidType();
10843 // Diagnose availability attributes. Availability cannot be used on functions
10844 // that are run during load/unload.
10845 if (const auto *attr
= NewFD
->getAttr
<AvailabilityAttr
>()) {
10846 if (NewFD
->hasAttr
<ConstructorAttr
>()) {
10847 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10849 NewFD
->dropAttr
<AvailabilityAttr
>();
10851 if (NewFD
->hasAttr
<DestructorAttr
>()) {
10852 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10854 NewFD
->dropAttr
<AvailabilityAttr
>();
10858 // Diagnose no_builtin attribute on function declaration that are not a
10860 // FIXME: We should really be doing this in
10861 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10862 // the FunctionDecl and at this point of the code
10863 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10864 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10865 if (const auto *NBA
= NewFD
->getAttr
<NoBuiltinAttr
>())
10866 switch (D
.getFunctionDefinitionKind()) {
10867 case FunctionDefinitionKind::Defaulted
:
10868 case FunctionDefinitionKind::Deleted
:
10869 Diag(NBA
->getLocation(),
10870 diag::err_attribute_no_builtin_on_defaulted_deleted_function
)
10871 << NBA
->getSpelling();
10873 case FunctionDefinitionKind::Declaration
:
10874 Diag(NBA
->getLocation(), diag::err_attribute_no_builtin_on_non_definition
)
10875 << NBA
->getSpelling();
10877 case FunctionDefinitionKind::Definition
:
10884 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10885 /// when __declspec(code_seg) "is applied to a class, all member functions of
10886 /// the class and nested classes -- this includes compiler-generated special
10887 /// member functions -- are put in the specified segment."
10888 /// The actual behavior is a little more complicated. The Microsoft compiler
10889 /// won't check outer classes if there is an active value from #pragma code_seg.
10890 /// The CodeSeg is always applied from the direct parent but only from outer
10891 /// classes when the #pragma code_seg stack is empty. See:
10892 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10893 /// available since MS has removed the page.
10894 static Attr
*getImplicitCodeSegAttrFromClass(Sema
&S
, const FunctionDecl
*FD
) {
10895 const auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
);
10898 const CXXRecordDecl
*Parent
= Method
->getParent();
10899 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10900 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10901 NewAttr
->setImplicit(true);
10905 // The Microsoft compiler won't check outer classes for the CodeSeg
10906 // when the #pragma code_seg stack is active.
10907 if (S
.CodeSegStack
.CurrentValue
)
10910 while ((Parent
= dyn_cast
<CXXRecordDecl
>(Parent
->getParent()))) {
10911 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10912 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10913 NewAttr
->setImplicit(true);
10920 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10921 /// containing class. Otherwise it will return implicit SectionAttr if the
10922 /// function is a definition and there is an active value on CodeSegStack
10923 /// (from the current #pragma code-seg value).
10925 /// \param FD Function being declared.
10926 /// \param IsDefinition Whether it is a definition or just a declaration.
10927 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10928 /// nullptr if no attribute should be added.
10929 Attr
*Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl
*FD
,
10930 bool IsDefinition
) {
10931 if (Attr
*A
= getImplicitCodeSegAttrFromClass(*this, FD
))
10933 if (!FD
->hasAttr
<SectionAttr
>() && IsDefinition
&&
10934 CodeSegStack
.CurrentValue
)
10935 return SectionAttr::CreateImplicit(
10936 getASTContext(), CodeSegStack
.CurrentValue
->getString(),
10937 CodeSegStack
.CurrentPragmaLocation
, SectionAttr::Declspec_allocate
);
10941 /// Determines if we can perform a correct type check for \p D as a
10942 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10943 /// best-effort check.
10945 /// \param NewD The new declaration.
10946 /// \param OldD The old declaration.
10947 /// \param NewT The portion of the type of the new declaration to check.
10948 /// \param OldT The portion of the type of the old declaration to check.
10949 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl
*NewD
, ValueDecl
*OldD
,
10950 QualType NewT
, QualType OldT
) {
10951 if (!NewD
->getLexicalDeclContext()->isDependentContext())
10954 // For dependently-typed local extern declarations and friends, we can't
10955 // perform a correct type check in general until instantiation:
10958 // template<typename T> void g() { T f(); }
10960 // (valid if g() is only instantiated with T = int).
10961 if (NewT
->isDependentType() &&
10962 (NewD
->isLocalExternDecl() || NewD
->getFriendObjectKind()))
10965 // Similarly, if the previous declaration was a dependent local extern
10966 // declaration, we don't really know its type yet.
10967 if (OldT
->isDependentType() && OldD
->isLocalExternDecl())
10973 /// Checks if the new declaration declared in dependent context must be
10974 /// put in the same redeclaration chain as the specified declaration.
10976 /// \param D Declaration that is checked.
10977 /// \param PrevDecl Previous declaration found with proper lookup method for the
10978 /// same declaration name.
10979 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10982 bool Sema::shouldLinkDependentDeclWithPrevious(Decl
*D
, Decl
*PrevDecl
) {
10983 if (!D
->getLexicalDeclContext()->isDependentContext())
10986 // Don't chain dependent friend function definitions until instantiation, to
10987 // permit cases like
10990 // template<typename T> class C1 { friend void func() {} };
10991 // template<typename T> class C2 { friend void func() {} };
10993 // ... which is valid if only one of C1 and C2 is ever instantiated.
10995 // FIXME: This need only apply to function definitions. For now, we proxy
10996 // this by checking for a file-scope function. We do not want this to apply
10997 // to friend declarations nominating member functions, because that gets in
10998 // the way of access checks.
10999 if (D
->getFriendObjectKind() && D
->getDeclContext()->isFileContext())
11002 auto *VD
= dyn_cast
<ValueDecl
>(D
);
11003 auto *PrevVD
= dyn_cast
<ValueDecl
>(PrevDecl
);
11004 return !VD
|| !PrevVD
||
11005 canFullyTypeCheckRedeclaration(VD
, PrevVD
, VD
->getType(),
11006 PrevVD
->getType());
11009 /// Check the target or target_version attribute of the function for
11010 /// MultiVersion validity.
11012 /// Returns true if there was an error, false otherwise.
11013 static bool CheckMultiVersionValue(Sema
&S
, const FunctionDecl
*FD
) {
11014 const auto *TA
= FD
->getAttr
<TargetAttr
>();
11015 const auto *TVA
= FD
->getAttr
<TargetVersionAttr
>();
11018 "MultiVersion candidate requires a target or target_version attribute");
11019 const TargetInfo
&TargetInfo
= S
.Context
.getTargetInfo();
11020 enum ErrType
{ Feature
= 0, Architecture
= 1 };
11023 ParsedTargetAttr ParseInfo
=
11024 S
.getASTContext().getTargetInfo().parseTargetAttr(TA
->getFeaturesStr());
11025 if (!ParseInfo
.CPU
.empty() && !TargetInfo
.validateCpuIs(ParseInfo
.CPU
)) {
11026 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
11027 << Architecture
<< ParseInfo
.CPU
;
11030 for (const auto &Feat
: ParseInfo
.Features
) {
11031 auto BareFeat
= StringRef
{Feat
}.substr(1);
11032 if (Feat
[0] == '-') {
11033 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
11034 << Feature
<< ("no-" + BareFeat
).str();
11038 if (!TargetInfo
.validateCpuSupports(BareFeat
) ||
11039 !TargetInfo
.isValidFeatureName(BareFeat
)) {
11040 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
11041 << Feature
<< BareFeat
;
11048 llvm::SmallVector
<StringRef
, 8> Feats
;
11049 TVA
->getFeatures(Feats
);
11050 for (const auto &Feat
: Feats
) {
11051 if (!TargetInfo
.validateCpuSupports(Feat
)) {
11052 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
11053 << Feature
<< Feat
;
11061 // Provide a white-list of attributes that are allowed to be combined with
11062 // multiversion functions.
11063 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind
,
11064 MultiVersionKind MVKind
) {
11065 // Note: this list/diagnosis must match the list in
11066 // checkMultiversionAttributesAllSame.
11071 return MVKind
== MultiVersionKind::Target
;
11072 case attr::NonNull
:
11073 case attr::NoThrow
:
11078 static bool checkNonMultiVersionCompatAttributes(Sema
&S
,
11079 const FunctionDecl
*FD
,
11080 const FunctionDecl
*CausedFD
,
11081 MultiVersionKind MVKind
) {
11082 const auto Diagnose
= [FD
, CausedFD
, MVKind
](Sema
&S
, const Attr
*A
) {
11083 S
.Diag(FD
->getLocation(), diag::err_multiversion_disallowed_other_attr
)
11084 << static_cast<unsigned>(MVKind
) << A
;
11086 S
.Diag(CausedFD
->getLocation(), diag::note_multiversioning_caused_here
);
11090 for (const Attr
*A
: FD
->attrs()) {
11091 switch (A
->getKind()) {
11092 case attr::CPUDispatch
:
11093 case attr::CPUSpecific
:
11094 if (MVKind
!= MultiVersionKind::CPUDispatch
&&
11095 MVKind
!= MultiVersionKind::CPUSpecific
)
11096 return Diagnose(S
, A
);
11099 if (MVKind
!= MultiVersionKind::Target
)
11100 return Diagnose(S
, A
);
11102 case attr::TargetVersion
:
11103 if (MVKind
!= MultiVersionKind::TargetVersion
)
11104 return Diagnose(S
, A
);
11106 case attr::TargetClones
:
11107 if (MVKind
!= MultiVersionKind::TargetClones
)
11108 return Diagnose(S
, A
);
11111 if (!AttrCompatibleWithMultiVersion(A
->getKind(), MVKind
))
11112 return Diagnose(S
, A
);
11119 bool Sema::areMultiversionVariantFunctionsCompatible(
11120 const FunctionDecl
*OldFD
, const FunctionDecl
*NewFD
,
11121 const PartialDiagnostic
&NoProtoDiagID
,
11122 const PartialDiagnosticAt
&NoteCausedDiagIDAt
,
11123 const PartialDiagnosticAt
&NoSupportDiagIDAt
,
11124 const PartialDiagnosticAt
&DiffDiagIDAt
, bool TemplatesSupported
,
11125 bool ConstexprSupported
, bool CLinkageMayDiffer
) {
11126 enum DoesntSupport
{
11133 DefaultedFuncs
= 6,
11134 ConstexprFuncs
= 7,
11135 ConstevalFuncs
= 8,
11144 LanguageLinkage
= 5,
11147 if (NoProtoDiagID
.getDiagID() != 0 && OldFD
&&
11148 !OldFD
->getType()->getAs
<FunctionProtoType
>()) {
11149 Diag(OldFD
->getLocation(), NoProtoDiagID
);
11150 Diag(NoteCausedDiagIDAt
.first
, NoteCausedDiagIDAt
.second
);
11154 if (NoProtoDiagID
.getDiagID() != 0 &&
11155 !NewFD
->getType()->getAs
<FunctionProtoType
>())
11156 return Diag(NewFD
->getLocation(), NoProtoDiagID
);
11158 if (!TemplatesSupported
&&
11159 NewFD
->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate
)
11160 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11163 if (const auto *NewCXXFD
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
11164 if (NewCXXFD
->isVirtual())
11165 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11168 if (isa
<CXXConstructorDecl
>(NewCXXFD
))
11169 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11172 if (isa
<CXXDestructorDecl
>(NewCXXFD
))
11173 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11177 if (NewFD
->isDeleted())
11178 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11181 if (NewFD
->isDefaulted())
11182 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11185 if (!ConstexprSupported
&& NewFD
->isConstexpr())
11186 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11187 << (NewFD
->isConsteval() ? ConstevalFuncs
: ConstexprFuncs
);
11189 QualType NewQType
= Context
.getCanonicalType(NewFD
->getType());
11190 const auto *NewType
= cast
<FunctionType
>(NewQType
);
11191 QualType NewReturnType
= NewType
->getReturnType();
11193 if (NewReturnType
->isUndeducedType())
11194 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11197 // Ensure the return type is identical.
11199 QualType OldQType
= Context
.getCanonicalType(OldFD
->getType());
11200 const auto *OldType
= cast
<FunctionType
>(OldQType
);
11201 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
11202 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
11204 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC())
11205 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << CallingConv
;
11207 QualType OldReturnType
= OldType
->getReturnType();
11209 if (OldReturnType
!= NewReturnType
)
11210 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ReturnType
;
11212 if (OldFD
->getConstexprKind() != NewFD
->getConstexprKind())
11213 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ConstexprSpec
;
11215 if (OldFD
->isInlineSpecified() != NewFD
->isInlineSpecified())
11216 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << InlineSpec
;
11218 if (OldFD
->getFormalLinkage() != NewFD
->getFormalLinkage())
11219 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << Linkage
;
11221 if (!CLinkageMayDiffer
&& OldFD
->isExternC() != NewFD
->isExternC())
11222 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << LanguageLinkage
;
11224 if (CheckEquivalentExceptionSpec(
11225 OldFD
->getType()->getAs
<FunctionProtoType
>(), OldFD
->getLocation(),
11226 NewFD
->getType()->getAs
<FunctionProtoType
>(), NewFD
->getLocation()))
11232 static bool CheckMultiVersionAdditionalRules(Sema
&S
, const FunctionDecl
*OldFD
,
11233 const FunctionDecl
*NewFD
,
11235 MultiVersionKind MVKind
) {
11236 if (!S
.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11237 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_supported
);
11239 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11243 bool IsCPUSpecificCPUDispatchMVKind
=
11244 MVKind
== MultiVersionKind::CPUDispatch
||
11245 MVKind
== MultiVersionKind::CPUSpecific
;
11247 if (CausesMV
&& OldFD
&&
11248 checkNonMultiVersionCompatAttributes(S
, OldFD
, NewFD
, MVKind
))
11251 if (checkNonMultiVersionCompatAttributes(S
, NewFD
, nullptr, MVKind
))
11254 // Only allow transition to MultiVersion if it hasn't been used.
11255 if (OldFD
&& CausesMV
&& OldFD
->isUsed(false))
11256 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
11258 return S
.areMultiversionVariantFunctionsCompatible(
11259 OldFD
, NewFD
, S
.PDiag(diag::err_multiversion_noproto
),
11260 PartialDiagnosticAt(NewFD
->getLocation(),
11261 S
.PDiag(diag::note_multiversioning_caused_here
)),
11262 PartialDiagnosticAt(NewFD
->getLocation(),
11263 S
.PDiag(diag::err_multiversion_doesnt_support
)
11264 << static_cast<unsigned>(MVKind
)),
11265 PartialDiagnosticAt(NewFD
->getLocation(),
11266 S
.PDiag(diag::err_multiversion_diff
)),
11267 /*TemplatesSupported=*/false,
11268 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind
,
11269 /*CLinkageMayDiffer=*/false);
11272 /// Check the validity of a multiversion function declaration that is the
11273 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11275 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11277 /// Returns true if there was an error, false otherwise.
11278 static bool CheckMultiVersionFirstFunction(Sema
&S
, FunctionDecl
*FD
) {
11279 MultiVersionKind MVKind
= FD
->getMultiVersionKind();
11280 assert(MVKind
!= MultiVersionKind::None
&&
11281 "Function lacks multiversion attribute");
11282 const auto *TA
= FD
->getAttr
<TargetAttr
>();
11283 const auto *TVA
= FD
->getAttr
<TargetVersionAttr
>();
11284 // Target and target_version only causes MV if it is default, otherwise this
11285 // is a normal function.
11286 if ((TA
&& !TA
->isDefaultVersion()) || (TVA
&& !TVA
->isDefaultVersion()))
11289 if ((TA
|| TVA
) && CheckMultiVersionValue(S
, FD
)) {
11290 FD
->setInvalidDecl();
11294 if (CheckMultiVersionAdditionalRules(S
, nullptr, FD
, true, MVKind
)) {
11295 FD
->setInvalidDecl();
11299 FD
->setIsMultiVersion();
11303 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl
*FD
) {
11304 for (const Decl
*D
= FD
->getPreviousDecl(); D
; D
= D
->getPreviousDecl()) {
11305 if (D
->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None
)
11312 static bool CheckTargetCausesMultiVersioning(Sema
&S
, FunctionDecl
*OldFD
,
11313 FunctionDecl
*NewFD
,
11314 bool &Redeclaration
,
11315 NamedDecl
*&OldDecl
,
11316 LookupResult
&Previous
) {
11317 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11318 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11319 const auto *OldTA
= OldFD
->getAttr
<TargetAttr
>();
11320 const auto *OldTVA
= OldFD
->getAttr
<TargetVersionAttr
>();
11321 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11322 // to change, this is a simple redeclaration.
11323 if ((NewTA
&& !NewTA
->isDefaultVersion() &&
11324 (!OldTA
|| OldTA
->getFeaturesStr() == NewTA
->getFeaturesStr())) ||
11325 (NewTVA
&& !NewTVA
->isDefaultVersion() &&
11326 (!OldTVA
|| OldTVA
->getName() == NewTVA
->getName())))
11329 // Otherwise, this decl causes MultiVersioning.
11330 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
, true,
11331 NewTVA
? MultiVersionKind::TargetVersion
11332 : MultiVersionKind::Target
)) {
11333 NewFD
->setInvalidDecl();
11337 if (CheckMultiVersionValue(S
, NewFD
)) {
11338 NewFD
->setInvalidDecl();
11342 // If this is 'default', permit the forward declaration.
11343 if (!OldFD
->isMultiVersion() &&
11344 ((NewTA
&& NewTA
->isDefaultVersion() && !OldTA
) ||
11345 (NewTVA
&& NewTVA
->isDefaultVersion() && !OldTVA
))) {
11346 Redeclaration
= true;
11348 OldFD
->setIsMultiVersion();
11349 NewFD
->setIsMultiVersion();
11353 if (CheckMultiVersionValue(S
, OldFD
)) {
11354 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
11355 NewFD
->setInvalidDecl();
11360 ParsedTargetAttr OldParsed
=
11361 S
.getASTContext().getTargetInfo().parseTargetAttr(
11362 OldTA
->getFeaturesStr());
11363 llvm::sort(OldParsed
.Features
);
11364 ParsedTargetAttr NewParsed
=
11365 S
.getASTContext().getTargetInfo().parseTargetAttr(
11366 NewTA
->getFeaturesStr());
11367 // Sort order doesn't matter, it just needs to be consistent.
11368 llvm::sort(NewParsed
.Features
);
11369 if (OldParsed
== NewParsed
) {
11370 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11371 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11372 NewFD
->setInvalidDecl();
11378 llvm::SmallVector
<StringRef
, 8> Feats
;
11379 OldTVA
->getFeatures(Feats
);
11381 llvm::SmallVector
<StringRef
, 8> NewFeats
;
11382 NewTVA
->getFeatures(NewFeats
);
11383 llvm::sort(NewFeats
);
11385 if (Feats
== NewFeats
) {
11386 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11387 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11388 NewFD
->setInvalidDecl();
11393 for (const auto *FD
: OldFD
->redecls()) {
11394 const auto *CurTA
= FD
->getAttr
<TargetAttr
>();
11395 const auto *CurTVA
= FD
->getAttr
<TargetVersionAttr
>();
11396 // We allow forward declarations before ANY multiversioning attributes, but
11397 // nothing after the fact.
11398 if (PreviousDeclsHaveMultiVersionAttribute(FD
) &&
11399 ((NewTA
&& (!CurTA
|| CurTA
->isInherited())) ||
11400 (NewTVA
&& (!CurTVA
|| CurTVA
->isInherited())))) {
11401 S
.Diag(FD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11402 << (NewTA
? 0 : 2);
11403 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
11404 NewFD
->setInvalidDecl();
11409 OldFD
->setIsMultiVersion();
11410 NewFD
->setIsMultiVersion();
11411 Redeclaration
= false;
11417 static bool MultiVersionTypesCompatible(MultiVersionKind Old
,
11418 MultiVersionKind New
) {
11419 if (Old
== New
|| Old
== MultiVersionKind::None
||
11420 New
== MultiVersionKind::None
)
11423 return (Old
== MultiVersionKind::CPUDispatch
&&
11424 New
== MultiVersionKind::CPUSpecific
) ||
11425 (Old
== MultiVersionKind::CPUSpecific
&&
11426 New
== MultiVersionKind::CPUDispatch
);
11429 /// Check the validity of a new function declaration being added to an existing
11430 /// multiversioned declaration collection.
11431 static bool CheckMultiVersionAdditionalDecl(
11432 Sema
&S
, FunctionDecl
*OldFD
, FunctionDecl
*NewFD
,
11433 MultiVersionKind NewMVKind
, const CPUDispatchAttr
*NewCPUDisp
,
11434 const CPUSpecificAttr
*NewCPUSpec
, const TargetClonesAttr
*NewClones
,
11435 bool &Redeclaration
, NamedDecl
*&OldDecl
, LookupResult
&Previous
) {
11436 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11437 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11438 MultiVersionKind OldMVKind
= OldFD
->getMultiVersionKind();
11439 // Disallow mixing of multiversioning types.
11440 if (!MultiVersionTypesCompatible(OldMVKind
, NewMVKind
)) {
11441 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_types_mixed
);
11442 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11443 NewFD
->setInvalidDecl();
11447 ParsedTargetAttr NewParsed
;
11449 NewParsed
= S
.getASTContext().getTargetInfo().parseTargetAttr(
11450 NewTA
->getFeaturesStr());
11451 llvm::sort(NewParsed
.Features
);
11453 llvm::SmallVector
<StringRef
, 8> NewFeats
;
11455 NewTVA
->getFeatures(NewFeats
);
11456 llvm::sort(NewFeats
);
11459 bool UseMemberUsingDeclRules
=
11460 S
.CurContext
->isRecord() && !NewFD
->getFriendObjectKind();
11462 bool MayNeedOverloadableChecks
=
11463 AllowOverloadingOfFunction(Previous
, S
.Context
, NewFD
);
11465 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11466 // of a previous member of the MultiVersion set.
11467 for (NamedDecl
*ND
: Previous
) {
11468 FunctionDecl
*CurFD
= ND
->getAsFunction();
11469 if (!CurFD
|| CurFD
->isInvalidDecl())
11471 if (MayNeedOverloadableChecks
&&
11472 S
.IsOverload(NewFD
, CurFD
, UseMemberUsingDeclRules
))
11475 if (NewMVKind
== MultiVersionKind::None
&&
11476 OldMVKind
== MultiVersionKind::TargetVersion
) {
11477 NewFD
->addAttr(TargetVersionAttr::CreateImplicit(
11478 S
.Context
, "default", NewFD
->getSourceRange()));
11479 NewFD
->setIsMultiVersion();
11480 NewMVKind
= MultiVersionKind::TargetVersion
;
11482 NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11483 NewTVA
->getFeatures(NewFeats
);
11484 llvm::sort(NewFeats
);
11488 switch (NewMVKind
) {
11489 case MultiVersionKind::None
:
11490 assert(OldMVKind
== MultiVersionKind::TargetClones
&&
11491 "Only target_clones can be omitted in subsequent declarations");
11493 case MultiVersionKind::Target
: {
11494 const auto *CurTA
= CurFD
->getAttr
<TargetAttr
>();
11495 if (CurTA
->getFeaturesStr() == NewTA
->getFeaturesStr()) {
11496 NewFD
->setIsMultiVersion();
11497 Redeclaration
= true;
11502 ParsedTargetAttr CurParsed
=
11503 S
.getASTContext().getTargetInfo().parseTargetAttr(
11504 CurTA
->getFeaturesStr());
11505 llvm::sort(CurParsed
.Features
);
11506 if (CurParsed
== NewParsed
) {
11507 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11508 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11509 NewFD
->setInvalidDecl();
11514 case MultiVersionKind::TargetVersion
: {
11515 const auto *CurTVA
= CurFD
->getAttr
<TargetVersionAttr
>();
11516 if (CurTVA
->getName() == NewTVA
->getName()) {
11517 NewFD
->setIsMultiVersion();
11518 Redeclaration
= true;
11522 llvm::SmallVector
<StringRef
, 8> CurFeats
;
11524 CurTVA
->getFeatures(CurFeats
);
11525 llvm::sort(CurFeats
);
11527 if (CurFeats
== NewFeats
) {
11528 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11529 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11530 NewFD
->setInvalidDecl();
11535 case MultiVersionKind::TargetClones
: {
11536 const auto *CurClones
= CurFD
->getAttr
<TargetClonesAttr
>();
11537 Redeclaration
= true;
11539 NewFD
->setIsMultiVersion();
11541 if (CurClones
&& NewClones
&&
11542 (CurClones
->featuresStrs_size() != NewClones
->featuresStrs_size() ||
11543 !std::equal(CurClones
->featuresStrs_begin(),
11544 CurClones
->featuresStrs_end(),
11545 NewClones
->featuresStrs_begin()))) {
11546 S
.Diag(NewFD
->getLocation(), diag::err_target_clone_doesnt_match
);
11547 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11548 NewFD
->setInvalidDecl();
11554 case MultiVersionKind::CPUSpecific
:
11555 case MultiVersionKind::CPUDispatch
: {
11556 const auto *CurCPUSpec
= CurFD
->getAttr
<CPUSpecificAttr
>();
11557 const auto *CurCPUDisp
= CurFD
->getAttr
<CPUDispatchAttr
>();
11558 // Handle CPUDispatch/CPUSpecific versions.
11559 // Only 1 CPUDispatch function is allowed, this will make it go through
11560 // the redeclaration errors.
11561 if (NewMVKind
== MultiVersionKind::CPUDispatch
&&
11562 CurFD
->hasAttr
<CPUDispatchAttr
>()) {
11563 if (CurCPUDisp
->cpus_size() == NewCPUDisp
->cpus_size() &&
11565 CurCPUDisp
->cpus_begin(), CurCPUDisp
->cpus_end(),
11566 NewCPUDisp
->cpus_begin(),
11567 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11568 return Cur
->getName() == New
->getName();
11570 NewFD
->setIsMultiVersion();
11571 Redeclaration
= true;
11576 // If the declarations don't match, this is an error condition.
11577 S
.Diag(NewFD
->getLocation(), diag::err_cpu_dispatch_mismatch
);
11578 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11579 NewFD
->setInvalidDecl();
11582 if (NewMVKind
== MultiVersionKind::CPUSpecific
&& CurCPUSpec
) {
11583 if (CurCPUSpec
->cpus_size() == NewCPUSpec
->cpus_size() &&
11585 CurCPUSpec
->cpus_begin(), CurCPUSpec
->cpus_end(),
11586 NewCPUSpec
->cpus_begin(),
11587 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11588 return Cur
->getName() == New
->getName();
11590 NewFD
->setIsMultiVersion();
11591 Redeclaration
= true;
11596 // Only 1 version of CPUSpecific is allowed for each CPU.
11597 for (const IdentifierInfo
*CurII
: CurCPUSpec
->cpus()) {
11598 for (const IdentifierInfo
*NewII
: NewCPUSpec
->cpus()) {
11599 if (CurII
== NewII
) {
11600 S
.Diag(NewFD
->getLocation(), diag::err_cpu_specific_multiple_defs
)
11602 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11603 NewFD
->setInvalidDecl();
11614 // Else, this is simply a non-redecl case. Checking the 'value' is only
11615 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11616 // handled in the attribute adding step.
11617 if ((NewMVKind
== MultiVersionKind::TargetVersion
||
11618 NewMVKind
== MultiVersionKind::Target
) &&
11619 CheckMultiVersionValue(S
, NewFD
)) {
11620 NewFD
->setInvalidDecl();
11624 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
,
11625 !OldFD
->isMultiVersion(), NewMVKind
)) {
11626 NewFD
->setInvalidDecl();
11630 // Permit forward declarations in the case where these two are compatible.
11631 if (!OldFD
->isMultiVersion()) {
11632 OldFD
->setIsMultiVersion();
11633 NewFD
->setIsMultiVersion();
11634 Redeclaration
= true;
11639 NewFD
->setIsMultiVersion();
11640 Redeclaration
= false;
11646 /// Check the validity of a mulitversion function declaration.
11647 /// Also sets the multiversion'ness' of the function itself.
11649 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11651 /// Returns true if there was an error, false otherwise.
11652 static bool CheckMultiVersionFunction(Sema
&S
, FunctionDecl
*NewFD
,
11653 bool &Redeclaration
, NamedDecl
*&OldDecl
,
11654 LookupResult
&Previous
) {
11655 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11656 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11657 const auto *NewCPUDisp
= NewFD
->getAttr
<CPUDispatchAttr
>();
11658 const auto *NewCPUSpec
= NewFD
->getAttr
<CPUSpecificAttr
>();
11659 const auto *NewClones
= NewFD
->getAttr
<TargetClonesAttr
>();
11660 MultiVersionKind MVKind
= NewFD
->getMultiVersionKind();
11662 // Main isn't allowed to become a multiversion function, however it IS
11663 // permitted to have 'main' be marked with the 'target' optimization hint,
11664 // for 'target_version' only default is allowed.
11665 if (NewFD
->isMain()) {
11666 if (MVKind
!= MultiVersionKind::None
&&
11667 !(MVKind
== MultiVersionKind::Target
&& !NewTA
->isDefaultVersion()) &&
11668 !(MVKind
== MultiVersionKind::TargetVersion
&&
11669 NewTVA
->isDefaultVersion())) {
11670 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_allowed_on_main
);
11671 NewFD
->setInvalidDecl();
11677 // Target attribute on AArch64 is not used for multiversioning
11678 if (NewTA
&& S
.getASTContext().getTargetInfo().getTriple().isAArch64())
11681 if (!OldDecl
|| !OldDecl
->getAsFunction() ||
11682 OldDecl
->getDeclContext()->getRedeclContext() !=
11683 NewFD
->getDeclContext()->getRedeclContext()) {
11684 // If there's no previous declaration, AND this isn't attempting to cause
11685 // multiversioning, this isn't an error condition.
11686 if (MVKind
== MultiVersionKind::None
)
11688 return CheckMultiVersionFirstFunction(S
, NewFD
);
11691 FunctionDecl
*OldFD
= OldDecl
->getAsFunction();
11693 if (!OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
) {
11694 if (NewTVA
|| !OldFD
->getAttr
<TargetVersionAttr
>())
11696 if (!NewFD
->getType()->getAs
<FunctionProtoType
>()) {
11697 // Multiversion declaration doesn't have prototype.
11698 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_noproto
);
11699 NewFD
->setInvalidDecl();
11701 // No "target_version" attribute is equivalent to "default" attribute.
11702 NewFD
->addAttr(TargetVersionAttr::CreateImplicit(
11703 S
.Context
, "default", NewFD
->getSourceRange()));
11704 NewFD
->setIsMultiVersion();
11705 OldFD
->setIsMultiVersion();
11707 Redeclaration
= true;
11712 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11713 // for target_clones and target_version.
11714 if (OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
&&
11715 OldFD
->getMultiVersionKind() != MultiVersionKind::TargetClones
&&
11716 OldFD
->getMultiVersionKind() != MultiVersionKind::TargetVersion
) {
11717 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11718 << (OldFD
->getMultiVersionKind() != MultiVersionKind::Target
);
11719 NewFD
->setInvalidDecl();
11723 if (!OldFD
->isMultiVersion()) {
11725 case MultiVersionKind::Target
:
11726 case MultiVersionKind::TargetVersion
:
11727 return CheckTargetCausesMultiVersioning(S
, OldFD
, NewFD
, Redeclaration
,
11728 OldDecl
, Previous
);
11729 case MultiVersionKind::TargetClones
:
11730 if (OldFD
->isUsed(false)) {
11731 NewFD
->setInvalidDecl();
11732 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
11734 OldFD
->setIsMultiVersion();
11737 case MultiVersionKind::CPUDispatch
:
11738 case MultiVersionKind::CPUSpecific
:
11739 case MultiVersionKind::None
:
11744 // At this point, we have a multiversion function decl (in OldFD) AND an
11745 // appropriate attribute in the current function decl. Resolve that these are
11746 // still compatible with previous declarations.
11747 return CheckMultiVersionAdditionalDecl(S
, OldFD
, NewFD
, MVKind
, NewCPUDisp
,
11748 NewCPUSpec
, NewClones
, Redeclaration
,
11749 OldDecl
, Previous
);
11752 /// Perform semantic checking of a new function declaration.
11754 /// Performs semantic analysis of the new function declaration
11755 /// NewFD. This routine performs all semantic checking that does not
11756 /// require the actual declarator involved in the declaration, and is
11757 /// used both for the declaration of functions as they are parsed
11758 /// (called via ActOnDeclarator) and for the declaration of functions
11759 /// that have been instantiated via C++ template instantiation (called
11760 /// via InstantiateDecl).
11762 /// \param IsMemberSpecialization whether this new function declaration is
11763 /// a member specialization (that replaces any definition provided by the
11764 /// previous declaration).
11766 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11768 /// \returns true if the function declaration is a redeclaration.
11769 bool Sema::CheckFunctionDeclaration(Scope
*S
, FunctionDecl
*NewFD
,
11770 LookupResult
&Previous
,
11771 bool IsMemberSpecialization
,
11773 assert(!NewFD
->getReturnType()->isVariablyModifiedType() &&
11774 "Variably modified return types are not handled here");
11776 // Determine whether the type of this function should be merged with
11777 // a previous visible declaration. This never happens for functions in C++,
11778 // and always happens in C if the previous declaration was visible.
11779 bool MergeTypeWithPrevious
= !getLangOpts().CPlusPlus
&&
11780 !Previous
.isShadowed();
11782 bool Redeclaration
= false;
11783 NamedDecl
*OldDecl
= nullptr;
11784 bool MayNeedOverloadableChecks
= false;
11786 // Merge or overload the declaration with an existing declaration of
11787 // the same name, if appropriate.
11788 if (!Previous
.empty()) {
11789 // Determine whether NewFD is an overload of PrevDecl or
11790 // a declaration that requires merging. If it's an overload,
11791 // there's no more work to do here; we'll just add the new
11792 // function to the scope.
11793 if (!AllowOverloadingOfFunction(Previous
, Context
, NewFD
)) {
11794 NamedDecl
*Candidate
= Previous
.getRepresentativeDecl();
11795 if (shouldLinkPossiblyHiddenDecl(Candidate
, NewFD
)) {
11796 Redeclaration
= true;
11797 OldDecl
= Candidate
;
11800 MayNeedOverloadableChecks
= true;
11801 switch (CheckOverload(S
, NewFD
, Previous
, OldDecl
,
11802 /*NewIsUsingDecl*/ false)) {
11804 Redeclaration
= true;
11807 case Ovl_NonFunction
:
11808 Redeclaration
= true;
11812 Redeclaration
= false;
11818 // Check for a previous extern "C" declaration with this name.
11819 if (!Redeclaration
&&
11820 checkForConflictWithNonVisibleExternC(*this, NewFD
, Previous
)) {
11821 if (!Previous
.empty()) {
11822 // This is an extern "C" declaration with the same name as a previous
11823 // declaration, and thus redeclares that entity...
11824 Redeclaration
= true;
11825 OldDecl
= Previous
.getFoundDecl();
11826 MergeTypeWithPrevious
= false;
11828 // ... except in the presence of __attribute__((overloadable)).
11829 if (OldDecl
->hasAttr
<OverloadableAttr
>() ||
11830 NewFD
->hasAttr
<OverloadableAttr
>()) {
11831 if (IsOverload(NewFD
, cast
<FunctionDecl
>(OldDecl
), false)) {
11832 MayNeedOverloadableChecks
= true;
11833 Redeclaration
= false;
11840 if (CheckMultiVersionFunction(*this, NewFD
, Redeclaration
, OldDecl
, Previous
))
11841 return Redeclaration
;
11843 // PPC MMA non-pointer types are not allowed as function return types.
11844 if (Context
.getTargetInfo().getTriple().isPPC64() &&
11845 CheckPPCMMAType(NewFD
->getReturnType(), NewFD
->getLocation())) {
11846 NewFD
->setInvalidDecl();
11849 // C++11 [dcl.constexpr]p8:
11850 // A constexpr specifier for a non-static member function that is not
11851 // a constructor declares that member function to be const.
11853 // This needs to be delayed until we know whether this is an out-of-line
11854 // definition of a static member function.
11856 // This rule is not present in C++1y, so we produce a backwards
11857 // compatibility warning whenever it happens in C++11.
11858 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
11859 if (!getLangOpts().CPlusPlus14
&& MD
&& MD
->isConstexpr() &&
11860 !MD
->isStatic() && !isa
<CXXConstructorDecl
>(MD
) &&
11861 !isa
<CXXDestructorDecl
>(MD
) && !MD
->getMethodQualifiers().hasConst()) {
11862 CXXMethodDecl
*OldMD
= nullptr;
11864 OldMD
= dyn_cast_or_null
<CXXMethodDecl
>(OldDecl
->getAsFunction());
11865 if (!OldMD
|| !OldMD
->isStatic()) {
11866 const FunctionProtoType
*FPT
=
11867 MD
->getType()->castAs
<FunctionProtoType
>();
11868 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
11869 EPI
.TypeQuals
.addConst();
11870 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
11871 FPT
->getParamTypes(), EPI
));
11873 // Warn that we did this, if we're not performing template instantiation.
11874 // In that case, we'll have warned already when the template was defined.
11875 if (!inTemplateInstantiation()) {
11876 SourceLocation AddConstLoc
;
11877 if (FunctionTypeLoc FTL
= MD
->getTypeSourceInfo()->getTypeLoc()
11878 .IgnoreParens().getAs
<FunctionTypeLoc
>())
11879 AddConstLoc
= getLocForEndOfToken(FTL
.getRParenLoc());
11881 Diag(MD
->getLocation(), diag::warn_cxx14_compat_constexpr_not_const
)
11882 << FixItHint::CreateInsertion(AddConstLoc
, " const");
11887 if (Redeclaration
) {
11888 // NewFD and OldDecl represent declarations that need to be
11890 if (MergeFunctionDecl(NewFD
, OldDecl
, S
, MergeTypeWithPrevious
,
11892 NewFD
->setInvalidDecl();
11893 return Redeclaration
;
11897 Previous
.addDecl(OldDecl
);
11899 if (FunctionTemplateDecl
*OldTemplateDecl
=
11900 dyn_cast
<FunctionTemplateDecl
>(OldDecl
)) {
11901 auto *OldFD
= OldTemplateDecl
->getTemplatedDecl();
11902 FunctionTemplateDecl
*NewTemplateDecl
11903 = NewFD
->getDescribedFunctionTemplate();
11904 assert(NewTemplateDecl
&& "Template/non-template mismatch");
11906 // The call to MergeFunctionDecl above may have created some state in
11907 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11908 // can add it as a redeclaration.
11909 NewTemplateDecl
->mergePrevDecl(OldTemplateDecl
);
11911 NewFD
->setPreviousDeclaration(OldFD
);
11912 if (NewFD
->isCXXClassMember()) {
11913 NewFD
->setAccess(OldTemplateDecl
->getAccess());
11914 NewTemplateDecl
->setAccess(OldTemplateDecl
->getAccess());
11917 // If this is an explicit specialization of a member that is a function
11918 // template, mark it as a member specialization.
11919 if (IsMemberSpecialization
&&
11920 NewTemplateDecl
->getInstantiatedFromMemberTemplate()) {
11921 NewTemplateDecl
->setMemberSpecialization();
11922 assert(OldTemplateDecl
->isMemberSpecialization());
11923 // Explicit specializations of a member template do not inherit deleted
11924 // status from the parent member template that they are specializing.
11925 if (OldFD
->isDeleted()) {
11926 // FIXME: This assert will not hold in the presence of modules.
11927 assert(OldFD
->getCanonicalDecl() == OldFD
);
11928 // FIXME: We need an update record for this AST mutation.
11929 OldFD
->setDeletedAsWritten(false);
11934 if (shouldLinkDependentDeclWithPrevious(NewFD
, OldDecl
)) {
11935 auto *OldFD
= cast
<FunctionDecl
>(OldDecl
);
11936 // This needs to happen first so that 'inline' propagates.
11937 NewFD
->setPreviousDeclaration(OldFD
);
11938 if (NewFD
->isCXXClassMember())
11939 NewFD
->setAccess(OldFD
->getAccess());
11942 } else if (!getLangOpts().CPlusPlus
&& MayNeedOverloadableChecks
&&
11943 !NewFD
->getAttr
<OverloadableAttr
>()) {
11944 assert((Previous
.empty() ||
11945 llvm::any_of(Previous
,
11946 [](const NamedDecl
*ND
) {
11947 return ND
->hasAttr
<OverloadableAttr
>();
11949 "Non-redecls shouldn't happen without overloadable present");
11951 auto OtherUnmarkedIter
= llvm::find_if(Previous
, [](const NamedDecl
*ND
) {
11952 const auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
11953 return FD
&& !FD
->hasAttr
<OverloadableAttr
>();
11956 if (OtherUnmarkedIter
!= Previous
.end()) {
11957 Diag(NewFD
->getLocation(),
11958 diag::err_attribute_overloadable_multiple_unmarked_overloads
);
11959 Diag((*OtherUnmarkedIter
)->getLocation(),
11960 diag::note_attribute_overloadable_prev_overload
)
11963 NewFD
->addAttr(OverloadableAttr::CreateImplicit(Context
));
11967 if (LangOpts
.OpenMP
)
11968 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD
);
11970 // Semantic checking for this function declaration (in isolation).
11972 if (getLangOpts().CPlusPlus
) {
11973 // C++-specific checks.
11974 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(NewFD
)) {
11975 CheckConstructor(Constructor
);
11976 } else if (CXXDestructorDecl
*Destructor
=
11977 dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
11978 // We check here for invalid destructor names.
11979 // If we have a friend destructor declaration that is dependent, we can't
11980 // diagnose right away because cases like this are still valid:
11981 // template <class T> struct A { friend T::X::~Y(); };
11982 // struct B { struct Y { ~Y(); }; using X = Y; };
11983 // template struct A<B>;
11984 if (NewFD
->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None
||
11985 !Destructor
->getFunctionObjectParameterType()->isDependentType()) {
11986 CXXRecordDecl
*Record
= Destructor
->getParent();
11987 QualType ClassType
= Context
.getTypeDeclType(Record
);
11989 DeclarationName Name
= Context
.DeclarationNames
.getCXXDestructorName(
11990 Context
.getCanonicalType(ClassType
));
11991 if (NewFD
->getDeclName() != Name
) {
11992 Diag(NewFD
->getLocation(), diag::err_destructor_name
);
11993 NewFD
->setInvalidDecl();
11994 return Redeclaration
;
11997 } else if (auto *Guide
= dyn_cast
<CXXDeductionGuideDecl
>(NewFD
)) {
11998 if (auto *TD
= Guide
->getDescribedFunctionTemplate())
11999 CheckDeductionGuideTemplate(TD
);
12001 // A deduction guide is not on the list of entities that can be
12002 // explicitly specialized.
12003 if (Guide
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
12004 Diag(Guide
->getBeginLoc(), diag::err_deduction_guide_specialized
)
12005 << /*explicit specialization*/ 1;
12008 // Find any virtual functions that this function overrides.
12009 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
12010 if (!Method
->isFunctionTemplateSpecialization() &&
12011 !Method
->getDescribedFunctionTemplate() &&
12012 Method
->isCanonicalDecl()) {
12013 AddOverriddenMethods(Method
->getParent(), Method
);
12015 if (Method
->isVirtual() && NewFD
->getTrailingRequiresClause())
12016 // C++2a [class.virtual]p6
12017 // A virtual method shall not have a requires-clause.
12018 Diag(NewFD
->getTrailingRequiresClause()->getBeginLoc(),
12019 diag::err_constrained_virtual_method
);
12021 if (Method
->isStatic())
12022 checkThisInStaticMemberFunctionType(Method
);
12025 // C++20: dcl.decl.general p4:
12026 // The optional requires-clause ([temp.pre]) in an init-declarator or
12027 // member-declarator shall be present only if the declarator declares a
12028 // templated function ([dcl.fct]).
12029 if (Expr
*TRC
= NewFD
->getTrailingRequiresClause()) {
12031 // An entity is templated if it is
12033 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12034 // templated entity,
12035 // - a member of a templated entity,
12036 // - an enumerator for an enumeration that is a templated entity, or
12037 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12038 // appearing in the declaration of a templated entity. [Note 6: A local
12039 // class, a local or block variable, or a friend function defined in a
12040 // templated entity is a templated entity. — end note]
12042 // A templated function is a function template or a function that is
12043 // templated. A templated class is a class template or a class that is
12044 // templated. A templated variable is a variable template or a variable
12045 // that is templated.
12047 if (!NewFD
->getDescribedFunctionTemplate() && // -a template
12048 // defined... in a templated entity
12049 !(DeclIsDefn
&& NewFD
->isTemplated()) &&
12050 // a member of a templated entity
12051 !(isa
<CXXMethodDecl
>(NewFD
) && NewFD
->isTemplated()) &&
12052 // Don't complain about instantiations, they've already had these
12053 // rules + others enforced.
12054 !NewFD
->isTemplateInstantiation()) {
12055 Diag(TRC
->getBeginLoc(), diag::err_constrained_non_templated_function
);
12059 if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(NewFD
))
12060 ActOnConversionDeclarator(Conversion
);
12062 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12063 if (NewFD
->isOverloadedOperator() &&
12064 CheckOverloadedOperatorDeclaration(NewFD
)) {
12065 NewFD
->setInvalidDecl();
12066 return Redeclaration
;
12069 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12070 if (NewFD
->getLiteralIdentifier() &&
12071 CheckLiteralOperatorDeclaration(NewFD
)) {
12072 NewFD
->setInvalidDecl();
12073 return Redeclaration
;
12076 // In C++, check default arguments now that we have merged decls. Unless
12077 // the lexical context is the class, because in this case this is done
12078 // during delayed parsing anyway.
12079 if (!CurContext
->isRecord())
12080 CheckCXXDefaultArguments(NewFD
);
12082 // If this function is declared as being extern "C", then check to see if
12083 // the function returns a UDT (class, struct, or union type) that is not C
12084 // compatible, and if it does, warn the user.
12085 // But, issue any diagnostic on the first declaration only.
12086 if (Previous
.empty() && NewFD
->isExternC()) {
12087 QualType R
= NewFD
->getReturnType();
12088 if (R
->isIncompleteType() && !R
->isVoidType())
12089 Diag(NewFD
->getLocation(), diag::warn_return_value_udt_incomplete
)
12091 else if (!R
.isPODType(Context
) && !R
->isVoidType() &&
12092 !R
->isObjCObjectPointerType())
12093 Diag(NewFD
->getLocation(), diag::warn_return_value_udt
) << NewFD
<< R
;
12096 // C++1z [dcl.fct]p6:
12097 // [...] whether the function has a non-throwing exception-specification
12098 // [is] part of the function type
12100 // This results in an ABI break between C++14 and C++17 for functions whose
12101 // declared type includes an exception-specification in a parameter or
12102 // return type. (Exception specifications on the function itself are OK in
12103 // most cases, and exception specifications are not permitted in most other
12104 // contexts where they could make it into a mangling.)
12105 if (!getLangOpts().CPlusPlus17
&& !NewFD
->getPrimaryTemplate()) {
12106 auto HasNoexcept
= [&](QualType T
) -> bool {
12107 // Strip off declarator chunks that could be between us and a function
12108 // type. We don't need to look far, exception specifications are very
12109 // restricted prior to C++17.
12110 if (auto *RT
= T
->getAs
<ReferenceType
>())
12111 T
= RT
->getPointeeType();
12112 else if (T
->isAnyPointerType())
12113 T
= T
->getPointeeType();
12114 else if (auto *MPT
= T
->getAs
<MemberPointerType
>())
12115 T
= MPT
->getPointeeType();
12116 if (auto *FPT
= T
->getAs
<FunctionProtoType
>())
12117 if (FPT
->isNothrow())
12122 auto *FPT
= NewFD
->getType()->castAs
<FunctionProtoType
>();
12123 bool AnyNoexcept
= HasNoexcept(FPT
->getReturnType());
12124 for (QualType T
: FPT
->param_types())
12125 AnyNoexcept
|= HasNoexcept(T
);
12127 Diag(NewFD
->getLocation(),
12128 diag::warn_cxx17_compat_exception_spec_in_signature
)
12132 if (!Redeclaration
&& LangOpts
.CUDA
)
12133 checkCUDATargetOverload(NewFD
, Previous
);
12136 // Check if the function definition uses any AArch64 SME features without
12137 // having the '+sme' feature enabled.
12139 bool UsesSM
= NewFD
->hasAttr
<ArmLocallyStreamingAttr
>();
12140 bool UsesZA
= NewFD
->hasAttr
<ArmNewZAAttr
>();
12141 if (const auto *FPT
= NewFD
->getType()->getAs
<FunctionProtoType
>()) {
12142 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
12144 EPI
.AArch64SMEAttributes
& FunctionType::SME_PStateSMEnabledMask
;
12145 UsesZA
|= EPI
.AArch64SMEAttributes
& FunctionType::SME_PStateZASharedMask
;
12148 if (UsesSM
|| UsesZA
) {
12149 llvm::StringMap
<bool> FeatureMap
;
12150 Context
.getFunctionFeatureMap(FeatureMap
, NewFD
);
12151 if (!FeatureMap
.contains("sme")) {
12153 Diag(NewFD
->getLocation(),
12154 diag::err_sme_definition_using_sm_in_non_sme_target
);
12156 Diag(NewFD
->getLocation(),
12157 diag::err_sme_definition_using_za_in_non_sme_target
);
12162 return Redeclaration
;
12165 void Sema::CheckMain(FunctionDecl
* FD
, const DeclSpec
& DS
) {
12166 // C++11 [basic.start.main]p3:
12167 // A program that [...] declares main to be inline, static or
12168 // constexpr is ill-formed.
12169 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12170 // appear in a declaration of main.
12171 // static main is not an error under C99, but we should warn about it.
12172 // We accept _Noreturn main as an extension.
12173 if (FD
->getStorageClass() == SC_Static
)
12174 Diag(DS
.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12175 ? diag::err_static_main
: diag::warn_static_main
)
12176 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
12177 if (FD
->isInlineSpecified())
12178 Diag(DS
.getInlineSpecLoc(), diag::err_inline_main
)
12179 << FixItHint::CreateRemoval(DS
.getInlineSpecLoc());
12180 if (DS
.isNoreturnSpecified()) {
12181 SourceLocation NoreturnLoc
= DS
.getNoreturnSpecLoc();
12182 SourceRange
NoreturnRange(NoreturnLoc
, getLocForEndOfToken(NoreturnLoc
));
12183 Diag(NoreturnLoc
, diag::ext_noreturn_main
);
12184 Diag(NoreturnLoc
, diag::note_main_remove_noreturn
)
12185 << FixItHint::CreateRemoval(NoreturnRange
);
12187 if (FD
->isConstexpr()) {
12188 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_main
)
12189 << FD
->isConsteval()
12190 << FixItHint::CreateRemoval(DS
.getConstexprSpecLoc());
12191 FD
->setConstexprKind(ConstexprSpecKind::Unspecified
);
12194 if (getLangOpts().OpenCL
) {
12195 Diag(FD
->getLocation(), diag::err_opencl_no_main
)
12196 << FD
->hasAttr
<OpenCLKernelAttr
>();
12197 FD
->setInvalidDecl();
12201 // Functions named main in hlsl are default entries, but don't have specific
12202 // signatures they are required to conform to.
12203 if (getLangOpts().HLSL
)
12206 QualType T
= FD
->getType();
12207 assert(T
->isFunctionType() && "function decl is not of function type");
12208 const FunctionType
* FT
= T
->castAs
<FunctionType
>();
12210 // Set default calling convention for main()
12211 if (FT
->getCallConv() != CC_C
) {
12212 FT
= Context
.adjustFunctionType(FT
, FT
->getExtInfo().withCallingConv(CC_C
));
12213 FD
->setType(QualType(FT
, 0));
12214 T
= Context
.getCanonicalType(FD
->getType());
12217 if (getLangOpts().GNUMode
&& !getLangOpts().CPlusPlus
) {
12218 // In C with GNU extensions we allow main() to have non-integer return
12219 // type, but we should warn about the extension, and we disable the
12220 // implicit-return-zero rule.
12222 // GCC in C mode accepts qualified 'int'.
12223 if (Context
.hasSameUnqualifiedType(FT
->getReturnType(), Context
.IntTy
))
12224 FD
->setHasImplicitReturnZero(true);
12226 Diag(FD
->getTypeSpecStartLoc(), diag::ext_main_returns_nonint
);
12227 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
12228 if (RTRange
.isValid())
12229 Diag(RTRange
.getBegin(), diag::note_main_change_return_type
)
12230 << FixItHint::CreateReplacement(RTRange
, "int");
12233 // In C and C++, main magically returns 0 if you fall off the end;
12234 // set the flag which tells us that.
12235 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12237 // All the standards say that main() should return 'int'.
12238 if (Context
.hasSameType(FT
->getReturnType(), Context
.IntTy
))
12239 FD
->setHasImplicitReturnZero(true);
12241 // Otherwise, this is just a flat-out error.
12242 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
12243 Diag(FD
->getTypeSpecStartLoc(), diag::err_main_returns_nonint
)
12244 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "int")
12246 FD
->setInvalidDecl(true);
12250 // Treat protoless main() as nullary.
12251 if (isa
<FunctionNoProtoType
>(FT
)) return;
12253 const FunctionProtoType
* FTP
= cast
<const FunctionProtoType
>(FT
);
12254 unsigned nparams
= FTP
->getNumParams();
12255 assert(FD
->getNumParams() == nparams
);
12257 bool HasExtraParameters
= (nparams
> 3);
12259 if (FTP
->isVariadic()) {
12260 Diag(FD
->getLocation(), diag::ext_variadic_main
);
12261 // FIXME: if we had information about the location of the ellipsis, we
12262 // could add a FixIt hint to remove it as a parameter.
12265 // Darwin passes an undocumented fourth argument of type char**. If
12266 // other platforms start sprouting these, the logic below will start
12268 if (nparams
== 4 && Context
.getTargetInfo().getTriple().isOSDarwin())
12269 HasExtraParameters
= false;
12271 if (HasExtraParameters
) {
12272 Diag(FD
->getLocation(), diag::err_main_surplus_args
) << nparams
;
12273 FD
->setInvalidDecl(true);
12277 // FIXME: a lot of the following diagnostics would be improved
12278 // if we had some location information about types.
12281 Context
.getPointerType(Context
.getPointerType(Context
.CharTy
));
12282 QualType Expected
[] = { Context
.IntTy
, CharPP
, CharPP
, CharPP
};
12284 for (unsigned i
= 0; i
< nparams
; ++i
) {
12285 QualType AT
= FTP
->getParamType(i
);
12287 bool mismatch
= true;
12289 if (Context
.hasSameUnqualifiedType(AT
, Expected
[i
]))
12291 else if (Expected
[i
] == CharPP
) {
12292 // As an extension, the following forms are okay:
12294 // char const * const *
12297 QualifierCollector qs
;
12298 const PointerType
* PT
;
12299 if ((PT
= qs
.strip(AT
)->getAs
<PointerType
>()) &&
12300 (PT
= qs
.strip(PT
->getPointeeType())->getAs
<PointerType
>()) &&
12301 Context
.hasSameType(QualType(qs
.strip(PT
->getPointeeType()), 0),
12304 mismatch
= !qs
.empty();
12309 Diag(FD
->getLocation(), diag::err_main_arg_wrong
) << i
<< Expected
[i
];
12310 // TODO: suggest replacing given type with expected type
12311 FD
->setInvalidDecl(true);
12315 if (nparams
== 1 && !FD
->isInvalidDecl()) {
12316 Diag(FD
->getLocation(), diag::warn_main_one_arg
);
12319 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
12320 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
12321 FD
->setInvalidDecl();
12325 static bool isDefaultStdCall(FunctionDecl
*FD
, Sema
&S
) {
12327 // Default calling convention for main and wmain is __cdecl
12328 if (FD
->getName() == "main" || FD
->getName() == "wmain")
12331 // Default calling convention for MinGW is __cdecl
12332 const llvm::Triple
&T
= S
.Context
.getTargetInfo().getTriple();
12333 if (T
.isWindowsGNUEnvironment())
12336 // Default calling convention for WinMain, wWinMain and DllMain
12337 // is __stdcall on 32 bit Windows
12338 if (T
.isOSWindows() && T
.getArch() == llvm::Triple::x86
)
12344 void Sema::CheckMSVCRTEntryPoint(FunctionDecl
*FD
) {
12345 QualType T
= FD
->getType();
12346 assert(T
->isFunctionType() && "function decl is not of function type");
12347 const FunctionType
*FT
= T
->castAs
<FunctionType
>();
12349 // Set an implicit return of 'zero' if the function can return some integral,
12350 // enumeration, pointer or nullptr type.
12351 if (FT
->getReturnType()->isIntegralOrEnumerationType() ||
12352 FT
->getReturnType()->isAnyPointerType() ||
12353 FT
->getReturnType()->isNullPtrType())
12354 // DllMain is exempt because a return value of zero means it failed.
12355 if (FD
->getName() != "DllMain")
12356 FD
->setHasImplicitReturnZero(true);
12358 // Explicity specified calling conventions are applied to MSVC entry points
12359 if (!hasExplicitCallingConv(T
)) {
12360 if (isDefaultStdCall(FD
, *this)) {
12361 if (FT
->getCallConv() != CC_X86StdCall
) {
12362 FT
= Context
.adjustFunctionType(
12363 FT
, FT
->getExtInfo().withCallingConv(CC_X86StdCall
));
12364 FD
->setType(QualType(FT
, 0));
12366 } else if (FT
->getCallConv() != CC_C
) {
12367 FT
= Context
.adjustFunctionType(FT
,
12368 FT
->getExtInfo().withCallingConv(CC_C
));
12369 FD
->setType(QualType(FT
, 0));
12373 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
12374 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
12375 FD
->setInvalidDecl();
12379 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl
*FD
) {
12380 auto &TargetInfo
= getASTContext().getTargetInfo();
12382 if (FD
->getName() != TargetInfo
.getTargetOpts().HLSLEntry
)
12385 StringRef Env
= TargetInfo
.getTriple().getEnvironmentName();
12386 HLSLShaderAttr::ShaderType ShaderType
;
12387 if (HLSLShaderAttr::ConvertStrToShaderType(Env
, ShaderType
)) {
12388 if (const auto *Shader
= FD
->getAttr
<HLSLShaderAttr
>()) {
12389 // The entry point is already annotated - check that it matches the
12391 if (Shader
->getType() != ShaderType
) {
12392 Diag(Shader
->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch
)
12394 FD
->setInvalidDecl();
12397 // Implicitly add the shader attribute if the entry function isn't
12398 // explicitly annotated.
12399 FD
->addAttr(HLSLShaderAttr::CreateImplicit(Context
, ShaderType
,
12400 FD
->getBeginLoc()));
12403 switch (TargetInfo
.getTriple().getEnvironment()) {
12404 case llvm::Triple::UnknownEnvironment
:
12405 case llvm::Triple::Library
:
12408 llvm_unreachable("Unhandled environment in triple");
12413 void Sema::CheckHLSLEntryPoint(FunctionDecl
*FD
) {
12414 const auto *ShaderAttr
= FD
->getAttr
<HLSLShaderAttr
>();
12415 assert(ShaderAttr
&& "Entry point has no shader attribute");
12416 HLSLShaderAttr::ShaderType ST
= ShaderAttr
->getType();
12419 case HLSLShaderAttr::Pixel
:
12420 case HLSLShaderAttr::Vertex
:
12421 case HLSLShaderAttr::Geometry
:
12422 case HLSLShaderAttr::Hull
:
12423 case HLSLShaderAttr::Domain
:
12424 case HLSLShaderAttr::RayGeneration
:
12425 case HLSLShaderAttr::Intersection
:
12426 case HLSLShaderAttr::AnyHit
:
12427 case HLSLShaderAttr::ClosestHit
:
12428 case HLSLShaderAttr::Miss
:
12429 case HLSLShaderAttr::Callable
:
12430 if (const auto *NT
= FD
->getAttr
<HLSLNumThreadsAttr
>()) {
12431 DiagnoseHLSLAttrStageMismatch(NT
, ST
,
12432 {HLSLShaderAttr::Compute
,
12433 HLSLShaderAttr::Amplification
,
12434 HLSLShaderAttr::Mesh
});
12435 FD
->setInvalidDecl();
12439 case HLSLShaderAttr::Compute
:
12440 case HLSLShaderAttr::Amplification
:
12441 case HLSLShaderAttr::Mesh
:
12442 if (!FD
->hasAttr
<HLSLNumThreadsAttr
>()) {
12443 Diag(FD
->getLocation(), diag::err_hlsl_missing_numthreads
)
12444 << HLSLShaderAttr::ConvertShaderTypeToStr(ST
);
12445 FD
->setInvalidDecl();
12450 for (ParmVarDecl
*Param
: FD
->parameters()) {
12451 if (const auto *AnnotationAttr
= Param
->getAttr
<HLSLAnnotationAttr
>()) {
12452 CheckHLSLSemanticAnnotation(FD
, Param
, AnnotationAttr
);
12454 // FIXME: Handle struct parameters where annotations are on struct fields.
12455 // See: https://github.com/llvm/llvm-project/issues/57875
12456 Diag(FD
->getLocation(), diag::err_hlsl_missing_semantic_annotation
);
12457 Diag(Param
->getLocation(), diag::note_previous_decl
) << Param
;
12458 FD
->setInvalidDecl();
12461 // FIXME: Verify return type semantic annotation.
12464 void Sema::CheckHLSLSemanticAnnotation(
12465 FunctionDecl
*EntryPoint
, const Decl
*Param
,
12466 const HLSLAnnotationAttr
*AnnotationAttr
) {
12467 auto *ShaderAttr
= EntryPoint
->getAttr
<HLSLShaderAttr
>();
12468 assert(ShaderAttr
&& "Entry point has no shader attribute");
12469 HLSLShaderAttr::ShaderType ST
= ShaderAttr
->getType();
12471 switch (AnnotationAttr
->getKind()) {
12472 case attr::HLSLSV_DispatchThreadID
:
12473 case attr::HLSLSV_GroupIndex
:
12474 if (ST
== HLSLShaderAttr::Compute
)
12476 DiagnoseHLSLAttrStageMismatch(AnnotationAttr
, ST
,
12477 {HLSLShaderAttr::Compute
});
12480 llvm_unreachable("Unknown HLSLAnnotationAttr");
12484 void Sema::DiagnoseHLSLAttrStageMismatch(
12485 const Attr
*A
, HLSLShaderAttr::ShaderType Stage
,
12486 std::initializer_list
<HLSLShaderAttr::ShaderType
> AllowedStages
) {
12487 SmallVector
<StringRef
, 8> StageStrings
;
12488 llvm::transform(AllowedStages
, std::back_inserter(StageStrings
),
12489 [](HLSLShaderAttr::ShaderType ST
) {
12491 HLSLShaderAttr::ConvertShaderTypeToStr(ST
));
12493 Diag(A
->getLoc(), diag::err_hlsl_attr_unsupported_in_stage
)
12494 << A
<< HLSLShaderAttr::ConvertShaderTypeToStr(Stage
)
12495 << (AllowedStages
.size() != 1) << join(StageStrings
, ", ");
12498 bool Sema::CheckForConstantInitializer(Expr
*Init
, QualType DclT
) {
12499 // FIXME: Need strict checking. In C89, we need to check for
12500 // any assignment, increment, decrement, function-calls, or
12501 // commas outside of a sizeof. In C99, it's the same list,
12502 // except that the aforementioned are allowed in unevaluated
12503 // expressions. Everything else falls under the
12504 // "may accept other forms of constant expressions" exception.
12506 // Regular C++ code will not end up here (exceptions: language extensions,
12507 // OpenCL C++ etc), so the constant expression rules there don't matter.
12508 if (Init
->isValueDependent()) {
12509 assert(Init
->containsErrors() &&
12510 "Dependent code should only occur in error-recovery path.");
12513 const Expr
*Culprit
;
12514 if (Init
->isConstantInitializer(Context
, false, &Culprit
))
12516 Diag(Culprit
->getExprLoc(), diag::err_init_element_not_constant
)
12517 << Culprit
->getSourceRange();
12522 // Visits an initialization expression to see if OrigDecl is evaluated in
12523 // its own initialization and throws a warning if it does.
12524 class SelfReferenceChecker
12525 : public EvaluatedExprVisitor
<SelfReferenceChecker
> {
12530 bool isReferenceType
;
12533 llvm::SmallVector
<unsigned, 4> InitFieldIndex
;
12536 typedef EvaluatedExprVisitor
<SelfReferenceChecker
> Inherited
;
12538 SelfReferenceChecker(Sema
&S
, Decl
*OrigDecl
) : Inherited(S
.Context
),
12539 S(S
), OrigDecl(OrigDecl
) {
12541 isRecordType
= false;
12542 isReferenceType
= false;
12543 isInitList
= false;
12544 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(OrigDecl
)) {
12545 isPODType
= VD
->getType().isPODType(S
.Context
);
12546 isRecordType
= VD
->getType()->isRecordType();
12547 isReferenceType
= VD
->getType()->isReferenceType();
12551 // For most expressions, just call the visitor. For initializer lists,
12552 // track the index of the field being initialized since fields are
12553 // initialized in order allowing use of previously initialized fields.
12554 void CheckExpr(Expr
*E
) {
12555 InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(E
);
12561 // Track and increment the index here.
12563 InitFieldIndex
.push_back(0);
12564 for (auto *Child
: InitList
->children()) {
12565 CheckExpr(cast
<Expr
>(Child
));
12566 ++InitFieldIndex
.back();
12568 InitFieldIndex
.pop_back();
12571 // Returns true if MemberExpr is checked and no further checking is needed.
12572 // Returns false if additional checking is required.
12573 bool CheckInitListMemberExpr(MemberExpr
*E
, bool CheckReference
) {
12574 llvm::SmallVector
<FieldDecl
*, 4> Fields
;
12576 bool ReferenceField
= false;
12578 // Get the field members used.
12579 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12580 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
12583 Fields
.push_back(FD
);
12584 if (FD
->getType()->isReferenceType())
12585 ReferenceField
= true;
12586 Base
= ME
->getBase()->IgnoreParenImpCasts();
12589 // Keep checking only if the base Decl is the same.
12590 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
);
12591 if (!DRE
|| DRE
->getDecl() != OrigDecl
)
12594 // A reference field can be bound to an unininitialized field.
12595 if (CheckReference
&& !ReferenceField
)
12598 // Convert FieldDecls to their index number.
12599 llvm::SmallVector
<unsigned, 4> UsedFieldIndex
;
12600 for (const FieldDecl
*I
: llvm::reverse(Fields
))
12601 UsedFieldIndex
.push_back(I
->getFieldIndex());
12603 // See if a warning is needed by checking the first difference in index
12604 // numbers. If field being used has index less than the field being
12605 // initialized, then the use is safe.
12606 for (auto UsedIter
= UsedFieldIndex
.begin(),
12607 UsedEnd
= UsedFieldIndex
.end(),
12608 OrigIter
= InitFieldIndex
.begin(),
12609 OrigEnd
= InitFieldIndex
.end();
12610 UsedIter
!= UsedEnd
&& OrigIter
!= OrigEnd
; ++UsedIter
, ++OrigIter
) {
12611 if (*UsedIter
< *OrigIter
)
12613 if (*UsedIter
> *OrigIter
)
12617 // TODO: Add a different warning which will print the field names.
12618 HandleDeclRefExpr(DRE
);
12622 // For most expressions, the cast is directly above the DeclRefExpr.
12623 // For conditional operators, the cast can be outside the conditional
12624 // operator if both expressions are DeclRefExpr's.
12625 void HandleValue(Expr
*E
) {
12626 E
= E
->IgnoreParens();
12627 if (DeclRefExpr
* DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
12628 HandleDeclRefExpr(DRE
);
12632 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
12633 Visit(CO
->getCond());
12634 HandleValue(CO
->getTrueExpr());
12635 HandleValue(CO
->getFalseExpr());
12639 if (BinaryConditionalOperator
*BCO
=
12640 dyn_cast
<BinaryConditionalOperator
>(E
)) {
12641 Visit(BCO
->getCond());
12642 HandleValue(BCO
->getFalseExpr());
12646 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
12647 HandleValue(OVE
->getSourceExpr());
12651 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
12652 if (BO
->getOpcode() == BO_Comma
) {
12653 Visit(BO
->getLHS());
12654 HandleValue(BO
->getRHS());
12659 if (isa
<MemberExpr
>(E
)) {
12661 if (CheckInitListMemberExpr(cast
<MemberExpr
>(E
),
12662 false /*CheckReference*/))
12666 Expr
*Base
= E
->IgnoreParenImpCasts();
12667 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12668 // Check for static member variables and don't warn on them.
12669 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12671 Base
= ME
->getBase()->IgnoreParenImpCasts();
12673 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
))
12674 HandleDeclRefExpr(DRE
);
12681 // Reference types not handled in HandleValue are handled here since all
12682 // uses of references are bad, not just r-value uses.
12683 void VisitDeclRefExpr(DeclRefExpr
*E
) {
12684 if (isReferenceType
)
12685 HandleDeclRefExpr(E
);
12688 void VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
12689 if (E
->getCastKind() == CK_LValueToRValue
) {
12690 HandleValue(E
->getSubExpr());
12694 Inherited::VisitImplicitCastExpr(E
);
12697 void VisitMemberExpr(MemberExpr
*E
) {
12699 if (CheckInitListMemberExpr(E
, true /*CheckReference*/))
12703 // Don't warn on arrays since they can be treated as pointers.
12704 if (E
->getType()->canDecayToPointerType()) return;
12706 // Warn when a non-static method call is followed by non-static member
12707 // field accesses, which is followed by a DeclRefExpr.
12708 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl());
12709 bool Warn
= (MD
&& !MD
->isStatic());
12710 Expr
*Base
= E
->getBase()->IgnoreParenImpCasts();
12711 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12712 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12714 Base
= ME
->getBase()->IgnoreParenImpCasts();
12717 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
)) {
12719 HandleDeclRefExpr(DRE
);
12723 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12724 // Visit that expression.
12728 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
12729 Expr
*Callee
= E
->getCallee();
12731 if (isa
<UnresolvedLookupExpr
>(Callee
))
12732 return Inherited::VisitCXXOperatorCallExpr(E
);
12735 for (auto Arg
: E
->arguments())
12736 HandleValue(Arg
->IgnoreParenImpCasts());
12739 void VisitUnaryOperator(UnaryOperator
*E
) {
12740 // For POD record types, addresses of its own members are well-defined.
12741 if (E
->getOpcode() == UO_AddrOf
&& isRecordType
&&
12742 isa
<MemberExpr
>(E
->getSubExpr()->IgnoreParens())) {
12744 HandleValue(E
->getSubExpr());
12748 if (E
->isIncrementDecrementOp()) {
12749 HandleValue(E
->getSubExpr());
12753 Inherited::VisitUnaryOperator(E
);
12756 void VisitObjCMessageExpr(ObjCMessageExpr
*E
) {}
12758 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
12759 if (E
->getConstructor()->isCopyConstructor()) {
12760 Expr
*ArgExpr
= E
->getArg(0);
12761 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(ArgExpr
))
12762 if (ILE
->getNumInits() == 1)
12763 ArgExpr
= ILE
->getInit(0);
12764 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
12765 if (ICE
->getCastKind() == CK_NoOp
)
12766 ArgExpr
= ICE
->getSubExpr();
12767 HandleValue(ArgExpr
);
12770 Inherited::VisitCXXConstructExpr(E
);
12773 void VisitCallExpr(CallExpr
*E
) {
12774 // Treat std::move as a use.
12775 if (E
->isCallToStdMove()) {
12776 HandleValue(E
->getArg(0));
12780 Inherited::VisitCallExpr(E
);
12783 void VisitBinaryOperator(BinaryOperator
*E
) {
12784 if (E
->isCompoundAssignmentOp()) {
12785 HandleValue(E
->getLHS());
12786 Visit(E
->getRHS());
12790 Inherited::VisitBinaryOperator(E
);
12793 // A custom visitor for BinaryConditionalOperator is needed because the
12794 // regular visitor would check the condition and true expression separately
12795 // but both point to the same place giving duplicate diagnostics.
12796 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
12797 Visit(E
->getCond());
12798 Visit(E
->getFalseExpr());
12801 void HandleDeclRefExpr(DeclRefExpr
*DRE
) {
12802 Decl
* ReferenceDecl
= DRE
->getDecl();
12803 if (OrigDecl
!= ReferenceDecl
) return;
12805 if (isReferenceType
) {
12806 diag
= diag::warn_uninit_self_reference_in_reference_init
;
12807 } else if (cast
<VarDecl
>(OrigDecl
)->isStaticLocal()) {
12808 diag
= diag::warn_static_self_reference_in_init
;
12809 } else if (isa
<TranslationUnitDecl
>(OrigDecl
->getDeclContext()) ||
12810 isa
<NamespaceDecl
>(OrigDecl
->getDeclContext()) ||
12811 DRE
->getDecl()->getType()->isRecordType()) {
12812 diag
= diag::warn_uninit_self_reference_in_init
;
12814 // Local variables will be handled by the CFG analysis.
12818 S
.DiagRuntimeBehavior(DRE
->getBeginLoc(), DRE
,
12820 << DRE
->getDecl() << OrigDecl
->getLocation()
12821 << DRE
->getSourceRange());
12825 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12826 static void CheckSelfReference(Sema
&S
, Decl
* OrigDecl
, Expr
*E
,
12828 // Parameters arguments are occassionially constructed with itself,
12829 // for instance, in recursive functions. Skip them.
12830 if (isa
<ParmVarDecl
>(OrigDecl
))
12833 E
= E
->IgnoreParens();
12835 // Skip checking T a = a where T is not a record or reference type.
12836 // Doing so is a way to silence uninitialized warnings.
12837 if (!DirectInit
&& !cast
<VarDecl
>(OrigDecl
)->getType()->isRecordType())
12838 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
12839 if (ICE
->getCastKind() == CK_LValueToRValue
)
12840 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ICE
->getSubExpr()))
12841 if (DRE
->getDecl() == OrigDecl
)
12844 SelfReferenceChecker(S
, OrigDecl
).CheckExpr(E
);
12846 } // end anonymous namespace
12849 // Simple wrapper to add the name of a variable or (if no variable is
12850 // available) a DeclarationName into a diagnostic.
12851 struct VarDeclOrName
{
12853 DeclarationName Name
;
12855 friend const Sema::SemaDiagnosticBuilder
&
12856 operator<<(const Sema::SemaDiagnosticBuilder
&Diag
, VarDeclOrName VN
) {
12857 return VN
.VDecl
? Diag
<< VN
.VDecl
: Diag
<< VN
.Name
;
12860 } // end anonymous namespace
12862 QualType
Sema::deduceVarTypeFromInitializer(VarDecl
*VDecl
,
12863 DeclarationName Name
, QualType Type
,
12864 TypeSourceInfo
*TSI
,
12865 SourceRange Range
, bool DirectInit
,
12867 bool IsInitCapture
= !VDecl
;
12868 assert((!VDecl
|| !VDecl
->isInitCapture()) &&
12869 "init captures are expected to be deduced prior to initialization");
12871 VarDeclOrName VN
{VDecl
, Name
};
12873 DeducedType
*Deduced
= Type
->getContainedDeducedType();
12874 assert(Deduced
&& "deduceVarTypeFromInitializer for non-deduced type");
12876 // Diagnose auto array declarations in C23, unless it's a supported extension.
12877 if (getLangOpts().C23
&& Type
->isArrayType() &&
12878 !isa_and_present
<StringLiteral
, InitListExpr
>(Init
)) {
12879 Diag(Range
.getBegin(), diag::err_auto_not_allowed
)
12880 << (int)Deduced
->getContainedAutoType()->getKeyword()
12881 << /*in array decl*/ 23 << Range
;
12885 // C++11 [dcl.spec.auto]p3
12887 assert(VDecl
&& "no init for init capture deduction?");
12889 // Except for class argument deduction, and then for an initializing
12890 // declaration only, i.e. no static at class scope or extern.
12891 if (!isa
<DeducedTemplateSpecializationType
>(Deduced
) ||
12892 VDecl
->hasExternalStorage() ||
12893 VDecl
->isStaticDataMember()) {
12894 Diag(VDecl
->getLocation(), diag::err_auto_var_requires_init
)
12895 << VDecl
->getDeclName() << Type
;
12900 ArrayRef
<Expr
*> DeduceInits
;
12902 DeduceInits
= Init
;
12904 auto *PL
= dyn_cast_if_present
<ParenListExpr
>(Init
);
12905 if (DirectInit
&& PL
)
12906 DeduceInits
= PL
->exprs();
12908 if (isa
<DeducedTemplateSpecializationType
>(Deduced
)) {
12909 assert(VDecl
&& "non-auto type for init capture deduction?");
12910 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
12911 InitializationKind Kind
= InitializationKind::CreateForInit(
12912 VDecl
->getLocation(), DirectInit
, Init
);
12913 // FIXME: Initialization should not be taking a mutable list of inits.
12914 SmallVector
<Expr
*, 8> InitsCopy(DeduceInits
.begin(), DeduceInits
.end());
12915 return DeduceTemplateSpecializationFromInitializer(TSI
, Entity
, Kind
,
12920 if (auto *IL
= dyn_cast
<InitListExpr
>(Init
))
12921 DeduceInits
= IL
->inits();
12924 // Deduction only works if we have exactly one source expression.
12925 if (DeduceInits
.empty()) {
12926 // It isn't possible to write this directly, but it is possible to
12927 // end up in this situation with "auto x(some_pack...);"
12928 Diag(Init
->getBeginLoc(), IsInitCapture
12929 ? diag::err_init_capture_no_expression
12930 : diag::err_auto_var_init_no_expression
)
12931 << VN
<< Type
<< Range
;
12935 if (DeduceInits
.size() > 1) {
12936 Diag(DeduceInits
[1]->getBeginLoc(),
12937 IsInitCapture
? diag::err_init_capture_multiple_expressions
12938 : diag::err_auto_var_init_multiple_expressions
)
12939 << VN
<< Type
<< Range
;
12943 Expr
*DeduceInit
= DeduceInits
[0];
12944 if (DirectInit
&& isa
<InitListExpr
>(DeduceInit
)) {
12945 Diag(Init
->getBeginLoc(), IsInitCapture
12946 ? diag::err_init_capture_paren_braces
12947 : diag::err_auto_var_init_paren_braces
)
12948 << isa
<InitListExpr
>(Init
) << VN
<< Type
<< Range
;
12952 // Expressions default to 'id' when we're in a debugger.
12953 bool DefaultedAnyToId
= false;
12954 if (getLangOpts().DebuggerCastResultToId
&&
12955 Init
->getType() == Context
.UnknownAnyTy
&& !IsInitCapture
) {
12956 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
12957 if (Result
.isInvalid()) {
12960 Init
= Result
.get();
12961 DefaultedAnyToId
= true;
12964 // C++ [dcl.decomp]p1:
12965 // If the assignment-expression [...] has array type A and no ref-qualifier
12966 // is present, e has type cv A
12967 if (VDecl
&& isa
<DecompositionDecl
>(VDecl
) &&
12968 Context
.hasSameUnqualifiedType(Type
, Context
.getAutoDeductType()) &&
12969 DeduceInit
->getType()->isConstantArrayType())
12970 return Context
.getQualifiedType(DeduceInit
->getType(),
12971 Type
.getQualifiers());
12973 QualType DeducedType
;
12974 TemplateDeductionInfo
Info(DeduceInit
->getExprLoc());
12975 TemplateDeductionResult Result
=
12976 DeduceAutoType(TSI
->getTypeLoc(), DeduceInit
, DeducedType
, Info
);
12977 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
) {
12978 if (!IsInitCapture
)
12979 DiagnoseAutoDeductionFailure(VDecl
, DeduceInit
);
12980 else if (isa
<InitListExpr
>(Init
))
12981 Diag(Range
.getBegin(),
12982 diag::err_init_capture_deduction_failure_from_init_list
)
12984 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12985 : DeduceInit
->getType())
12986 << DeduceInit
->getSourceRange();
12988 Diag(Range
.getBegin(), diag::err_init_capture_deduction_failure
)
12989 << VN
<< TSI
->getType()
12990 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12991 : DeduceInit
->getType())
12992 << DeduceInit
->getSourceRange();
12995 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12996 // 'id' instead of a specific object type prevents most of our usual
12998 // We only want to warn outside of template instantiations, though:
12999 // inside a template, the 'id' could have come from a parameter.
13000 if (!inTemplateInstantiation() && !DefaultedAnyToId
&& !IsInitCapture
&&
13001 !DeducedType
.isNull() && DeducedType
->isObjCIdType()) {
13002 SourceLocation Loc
= TSI
->getTypeLoc().getBeginLoc();
13003 Diag(Loc
, diag::warn_auto_var_is_id
) << VN
<< Range
;
13006 return DeducedType
;
13009 bool Sema::DeduceVariableDeclarationType(VarDecl
*VDecl
, bool DirectInit
,
13011 assert(!Init
|| !Init
->containsErrors());
13012 QualType DeducedType
= deduceVarTypeFromInitializer(
13013 VDecl
, VDecl
->getDeclName(), VDecl
->getType(), VDecl
->getTypeSourceInfo(),
13014 VDecl
->getSourceRange(), DirectInit
, Init
);
13015 if (DeducedType
.isNull()) {
13016 VDecl
->setInvalidDecl();
13020 VDecl
->setType(DeducedType
);
13021 assert(VDecl
->isLinkageValid());
13023 // In ARC, infer lifetime.
13024 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(VDecl
))
13025 VDecl
->setInvalidDecl();
13027 if (getLangOpts().OpenCL
)
13028 deduceOpenCLAddressSpace(VDecl
);
13030 // If this is a redeclaration, check that the type we just deduced matches
13031 // the previously declared type.
13032 if (VarDecl
*Old
= VDecl
->getPreviousDecl()) {
13033 // We never need to merge the type, because we cannot form an incomplete
13034 // array of auto, nor deduce such a type.
13035 MergeVarDeclTypes(VDecl
, Old
, /*MergeTypeWithPrevious*/ false);
13038 // Check the deduced type is valid for a variable declaration.
13039 CheckVariableDeclarationType(VDecl
);
13040 return VDecl
->isInvalidDecl();
13043 void Sema::checkNonTrivialCUnionInInitializer(const Expr
*Init
,
13044 SourceLocation Loc
) {
13045 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(Init
))
13046 Init
= EWC
->getSubExpr();
13048 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
))
13049 Init
= CE
->getSubExpr();
13051 QualType InitType
= Init
->getType();
13052 assert((InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13053 InitType
.hasNonTrivialToPrimitiveCopyCUnion()) &&
13054 "shouldn't be called if type doesn't have a non-trivial C struct");
13055 if (auto *ILE
= dyn_cast
<InitListExpr
>(Init
)) {
13056 for (auto *I
: ILE
->inits()) {
13057 if (!I
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13058 !I
->getType().hasNonTrivialToPrimitiveCopyCUnion())
13060 SourceLocation SL
= I
->getExprLoc();
13061 checkNonTrivialCUnionInInitializer(I
, SL
.isValid() ? SL
: Loc
);
13066 if (isa
<ImplicitValueInitExpr
>(Init
)) {
13067 if (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13068 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_DefaultInitializedObject
,
13071 // Assume all other explicit initializers involving copying some existing
13073 // TODO: ignore any explicit initializers where we can guarantee
13075 if (InitType
.hasNonTrivialToPrimitiveCopyCUnion())
13076 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_CopyInit
, NTCUK_Copy
);
13082 bool shouldIgnoreForRecordTriviality(const FieldDecl
*FD
) {
13083 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13084 // in the source code or implicitly by the compiler if it is in a union
13085 // defined in a system header and has non-trivial ObjC ownership
13086 // qualifications. We don't want those fields to participate in determining
13087 // whether the containing union is non-trivial.
13088 return FD
->hasAttr
<UnavailableAttr
>();
13091 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13092 : DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
13095 DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
13098 DiagNonTrivalCUnionDefaultInitializeVisitor(
13099 QualType OrigTy
, SourceLocation OrigLoc
,
13100 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
13101 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
13103 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK
, QualType QT
,
13104 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13105 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
13106 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
13107 InNonTrivialUnion
);
13108 return Super::visitWithKind(PDIK
, QT
, FD
, InNonTrivialUnion
);
13111 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
13112 bool InNonTrivialUnion
) {
13113 if (InNonTrivialUnion
)
13114 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13115 << 1 << 0 << QT
<< FD
->getName();
13118 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13119 if (InNonTrivialUnion
)
13120 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13121 << 1 << 0 << QT
<< FD
->getName();
13124 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13125 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
13126 if (RD
->isUnion()) {
13127 if (OrigLoc
.isValid()) {
13128 bool IsUnion
= false;
13129 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
13130 IsUnion
= OrigRD
->isUnion();
13131 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
13132 << 0 << OrigTy
<< IsUnion
<< UseContext
;
13133 // Reset OrigLoc so that this diagnostic is emitted only once.
13134 OrigLoc
= SourceLocation();
13136 InNonTrivialUnion
= true;
13139 if (InNonTrivialUnion
)
13140 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
13141 << 0 << 0 << QT
.getUnqualifiedType() << "";
13143 for (const FieldDecl
*FD
: RD
->fields())
13144 if (!shouldIgnoreForRecordTriviality(FD
))
13145 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
13148 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
13150 // The non-trivial C union type or the struct/union type that contains a
13151 // non-trivial C union.
13153 SourceLocation OrigLoc
;
13154 Sema::NonTrivialCUnionContext UseContext
;
13158 struct DiagNonTrivalCUnionDestructedTypeVisitor
13159 : DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void> {
13161 DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void>;
13163 DiagNonTrivalCUnionDestructedTypeVisitor(
13164 QualType OrigTy
, SourceLocation OrigLoc
,
13165 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
13166 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
13168 void visitWithKind(QualType::DestructionKind DK
, QualType QT
,
13169 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13170 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
13171 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
13172 InNonTrivialUnion
);
13173 return Super::visitWithKind(DK
, QT
, FD
, InNonTrivialUnion
);
13176 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
13177 bool InNonTrivialUnion
) {
13178 if (InNonTrivialUnion
)
13179 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13180 << 1 << 1 << QT
<< FD
->getName();
13183 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13184 if (InNonTrivialUnion
)
13185 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13186 << 1 << 1 << QT
<< FD
->getName();
13189 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13190 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
13191 if (RD
->isUnion()) {
13192 if (OrigLoc
.isValid()) {
13193 bool IsUnion
= false;
13194 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
13195 IsUnion
= OrigRD
->isUnion();
13196 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
13197 << 1 << OrigTy
<< IsUnion
<< UseContext
;
13198 // Reset OrigLoc so that this diagnostic is emitted only once.
13199 OrigLoc
= SourceLocation();
13201 InNonTrivialUnion
= true;
13204 if (InNonTrivialUnion
)
13205 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
13206 << 0 << 1 << QT
.getUnqualifiedType() << "";
13208 for (const FieldDecl
*FD
: RD
->fields())
13209 if (!shouldIgnoreForRecordTriviality(FD
))
13210 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
13213 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
13214 void visitCXXDestructor(QualType QT
, const FieldDecl
*FD
,
13215 bool InNonTrivialUnion
) {}
13217 // The non-trivial C union type or the struct/union type that contains a
13218 // non-trivial C union.
13220 SourceLocation OrigLoc
;
13221 Sema::NonTrivialCUnionContext UseContext
;
13225 struct DiagNonTrivalCUnionCopyVisitor
13226 : CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void> {
13227 using Super
= CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void>;
13229 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy
, SourceLocation OrigLoc
,
13230 Sema::NonTrivialCUnionContext UseContext
,
13232 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
13234 void visitWithKind(QualType::PrimitiveCopyKind PCK
, QualType QT
,
13235 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13236 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
13237 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
13238 InNonTrivialUnion
);
13239 return Super::visitWithKind(PCK
, QT
, FD
, InNonTrivialUnion
);
13242 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
13243 bool InNonTrivialUnion
) {
13244 if (InNonTrivialUnion
)
13245 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13246 << 1 << 2 << QT
<< FD
->getName();
13249 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13250 if (InNonTrivialUnion
)
13251 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
13252 << 1 << 2 << QT
<< FD
->getName();
13255 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
13256 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
13257 if (RD
->isUnion()) {
13258 if (OrigLoc
.isValid()) {
13259 bool IsUnion
= false;
13260 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
13261 IsUnion
= OrigRD
->isUnion();
13262 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
13263 << 2 << OrigTy
<< IsUnion
<< UseContext
;
13264 // Reset OrigLoc so that this diagnostic is emitted only once.
13265 OrigLoc
= SourceLocation();
13267 InNonTrivialUnion
= true;
13270 if (InNonTrivialUnion
)
13271 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
13272 << 0 << 2 << QT
.getUnqualifiedType() << "";
13274 for (const FieldDecl
*FD
: RD
->fields())
13275 if (!shouldIgnoreForRecordTriviality(FD
))
13276 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
13279 void preVisit(QualType::PrimitiveCopyKind PCK
, QualType QT
,
13280 const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
13281 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
13282 void visitVolatileTrivial(QualType QT
, const FieldDecl
*FD
,
13283 bool InNonTrivialUnion
) {}
13285 // The non-trivial C union type or the struct/union type that contains a
13286 // non-trivial C union.
13288 SourceLocation OrigLoc
;
13289 Sema::NonTrivialCUnionContext UseContext
;
13295 void Sema::checkNonTrivialCUnion(QualType QT
, SourceLocation Loc
,
13296 NonTrivialCUnionContext UseContext
,
13297 unsigned NonTrivialKind
) {
13298 assert((QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13299 QT
.hasNonTrivialToPrimitiveDestructCUnion() ||
13300 QT
.hasNonTrivialToPrimitiveCopyCUnion()) &&
13301 "shouldn't be called if type doesn't have a non-trivial C union");
13303 if ((NonTrivialKind
& NTCUK_Init
) &&
13304 QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13305 DiagNonTrivalCUnionDefaultInitializeVisitor(QT
, Loc
, UseContext
, *this)
13306 .visit(QT
, nullptr, false);
13307 if ((NonTrivialKind
& NTCUK_Destruct
) &&
13308 QT
.hasNonTrivialToPrimitiveDestructCUnion())
13309 DiagNonTrivalCUnionDestructedTypeVisitor(QT
, Loc
, UseContext
, *this)
13310 .visit(QT
, nullptr, false);
13311 if ((NonTrivialKind
& NTCUK_Copy
) && QT
.hasNonTrivialToPrimitiveCopyCUnion())
13312 DiagNonTrivalCUnionCopyVisitor(QT
, Loc
, UseContext
, *this)
13313 .visit(QT
, nullptr, false);
13316 /// AddInitializerToDecl - Adds the initializer Init to the
13317 /// declaration dcl. If DirectInit is true, this is C++ direct
13318 /// initialization rather than copy initialization.
13319 void Sema::AddInitializerToDecl(Decl
*RealDecl
, Expr
*Init
, bool DirectInit
) {
13320 // If there is no declaration, there was an error parsing it. Just ignore
13321 // the initializer.
13322 if (!RealDecl
|| RealDecl
->isInvalidDecl()) {
13323 CorrectDelayedTyposInExpr(Init
, dyn_cast_or_null
<VarDecl
>(RealDecl
));
13327 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(RealDecl
)) {
13328 // Pure-specifiers are handled in ActOnPureSpecifier.
13329 Diag(Method
->getLocation(), diag::err_member_function_initialization
)
13330 << Method
->getDeclName() << Init
->getSourceRange();
13331 Method
->setInvalidDecl();
13335 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
13337 assert(!isa
<FieldDecl
>(RealDecl
) && "field init shouldn't get here");
13338 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
13339 RealDecl
->setInvalidDecl();
13343 // WebAssembly tables can't be used to initialise a variable.
13344 if (Init
&& !Init
->getType().isNull() &&
13345 Init
->getType()->isWebAssemblyTableType()) {
13346 Diag(Init
->getExprLoc(), diag::err_wasm_table_art
) << 0;
13347 VDecl
->setInvalidDecl();
13351 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13352 if (VDecl
->getType()->isUndeducedType()) {
13353 // Attempt typo correction early so that the type of the init expression can
13354 // be deduced based on the chosen correction if the original init contains a
13356 ExprResult Res
= CorrectDelayedTyposInExpr(Init
, VDecl
);
13357 if (!Res
.isUsable()) {
13358 // There are unresolved typos in Init, just drop them.
13359 // FIXME: improve the recovery strategy to preserve the Init.
13360 RealDecl
->setInvalidDecl();
13363 if (Res
.get()->containsErrors()) {
13364 // Invalidate the decl as we don't know the type for recovery-expr yet.
13365 RealDecl
->setInvalidDecl();
13366 VDecl
->setInit(Res
.get());
13371 if (DeduceVariableDeclarationType(VDecl
, DirectInit
, Init
))
13375 // dllimport cannot be used on variable definitions.
13376 if (VDecl
->hasAttr
<DLLImportAttr
>() && !VDecl
->isStaticDataMember()) {
13377 Diag(VDecl
->getLocation(), diag::err_attribute_dllimport_data_definition
);
13378 VDecl
->setInvalidDecl();
13382 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13383 // the identifier has external or internal linkage, the declaration shall
13384 // have no initializer for the identifier.
13385 // C++14 [dcl.init]p5 is the same restriction for C++.
13386 if (VDecl
->isLocalVarDecl() && VDecl
->hasExternalStorage()) {
13387 Diag(VDecl
->getLocation(), diag::err_block_extern_cant_init
);
13388 VDecl
->setInvalidDecl();
13392 if (!VDecl
->getType()->isDependentType()) {
13393 // A definition must end up with a complete type, which means it must be
13394 // complete with the restriction that an array type might be completed by
13395 // the initializer; note that later code assumes this restriction.
13396 QualType BaseDeclType
= VDecl
->getType();
13397 if (const ArrayType
*Array
= Context
.getAsIncompleteArrayType(BaseDeclType
))
13398 BaseDeclType
= Array
->getElementType();
13399 if (RequireCompleteType(VDecl
->getLocation(), BaseDeclType
,
13400 diag::err_typecheck_decl_incomplete_type
)) {
13401 RealDecl
->setInvalidDecl();
13405 // The variable can not have an abstract class type.
13406 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
13407 diag::err_abstract_type_in_decl
,
13408 AbstractVariableType
))
13409 VDecl
->setInvalidDecl();
13412 // C++ [module.import/6] external definitions are not permitted in header
13414 if (getLangOpts().CPlusPlusModules
&& currentModuleIsHeaderUnit() &&
13415 !VDecl
->isInvalidDecl() && VDecl
->isThisDeclarationADefinition() &&
13416 VDecl
->getFormalLinkage() == Linkage::ExternalLinkage
&&
13417 !VDecl
->isInline() && !VDecl
->isTemplated() &&
13418 !isa
<VarTemplateSpecializationDecl
>(VDecl
)) {
13419 Diag(VDecl
->getLocation(), diag::err_extern_def_in_header_unit
);
13420 VDecl
->setInvalidDecl();
13423 // If adding the initializer will turn this declaration into a definition,
13424 // and we already have a definition for this variable, diagnose or otherwise
13425 // handle the situation.
13426 if (VarDecl
*Def
= VDecl
->getDefinition())
13427 if (Def
!= VDecl
&&
13428 (!VDecl
->isStaticDataMember() || VDecl
->isOutOfLine()) &&
13429 !VDecl
->isThisDeclarationADemotedDefinition() &&
13430 checkVarDeclRedefinition(Def
, VDecl
))
13433 if (getLangOpts().CPlusPlus
) {
13434 // C++ [class.static.data]p4
13435 // If a static data member is of const integral or const
13436 // enumeration type, its declaration in the class definition can
13437 // specify a constant-initializer which shall be an integral
13438 // constant expression (5.19). In that case, the member can appear
13439 // in integral constant expressions. The member shall still be
13440 // defined in a namespace scope if it is used in the program and the
13441 // namespace scope definition shall not contain an initializer.
13443 // We already performed a redefinition check above, but for static
13444 // data members we also need to check whether there was an in-class
13445 // declaration with an initializer.
13446 if (VDecl
->isStaticDataMember() && VDecl
->getCanonicalDecl()->hasInit()) {
13447 Diag(Init
->getExprLoc(), diag::err_static_data_member_reinitialization
)
13448 << VDecl
->getDeclName();
13449 Diag(VDecl
->getCanonicalDecl()->getInit()->getExprLoc(),
13450 diag::note_previous_initializer
)
13455 if (VDecl
->hasLocalStorage())
13456 setFunctionHasBranchProtectedScope();
13458 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
)) {
13459 VDecl
->setInvalidDecl();
13464 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13465 // a kernel function cannot be initialized."
13466 if (VDecl
->getType().getAddressSpace() == LangAS::opencl_local
) {
13467 Diag(VDecl
->getLocation(), diag::err_local_cant_init
);
13468 VDecl
->setInvalidDecl();
13472 // The LoaderUninitialized attribute acts as a definition (of undef).
13473 if (VDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
13474 Diag(VDecl
->getLocation(), diag::err_loader_uninitialized_cant_init
);
13475 VDecl
->setInvalidDecl();
13479 // Get the decls type and save a reference for later, since
13480 // CheckInitializerTypes may change it.
13481 QualType DclT
= VDecl
->getType(), SavT
= DclT
;
13483 // Expressions default to 'id' when we're in a debugger
13484 // and we are assigning it to a variable of Objective-C pointer type.
13485 if (getLangOpts().DebuggerCastResultToId
&& DclT
->isObjCObjectPointerType() &&
13486 Init
->getType() == Context
.UnknownAnyTy
) {
13487 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
13488 if (Result
.isInvalid()) {
13489 VDecl
->setInvalidDecl();
13492 Init
= Result
.get();
13495 // Perform the initialization.
13496 ParenListExpr
*CXXDirectInit
= dyn_cast
<ParenListExpr
>(Init
);
13497 bool IsParenListInit
= false;
13498 if (!VDecl
->isInvalidDecl()) {
13499 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
13500 InitializationKind Kind
= InitializationKind::CreateForInit(
13501 VDecl
->getLocation(), DirectInit
, Init
);
13503 MultiExprArg Args
= Init
;
13505 Args
= MultiExprArg(CXXDirectInit
->getExprs(),
13506 CXXDirectInit
->getNumExprs());
13508 // Try to correct any TypoExprs in the initialization arguments.
13509 for (size_t Idx
= 0; Idx
< Args
.size(); ++Idx
) {
13510 ExprResult Res
= CorrectDelayedTyposInExpr(
13511 Args
[Idx
], VDecl
, /*RecoverUncorrectedTypos=*/true,
13512 [this, Entity
, Kind
](Expr
*E
) {
13513 InitializationSequence
Init(*this, Entity
, Kind
, MultiExprArg(E
));
13514 return Init
.Failed() ? ExprError() : E
;
13516 if (Res
.isInvalid()) {
13517 VDecl
->setInvalidDecl();
13518 } else if (Res
.get() != Args
[Idx
]) {
13519 Args
[Idx
] = Res
.get();
13522 if (VDecl
->isInvalidDecl())
13525 InitializationSequence
InitSeq(*this, Entity
, Kind
, Args
,
13526 /*TopLevelOfInitList=*/false,
13527 /*TreatUnavailableAsInvalid=*/false);
13528 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Args
, &DclT
);
13529 if (Result
.isInvalid()) {
13530 // If the provided initializer fails to initialize the var decl,
13531 // we attach a recovery expr for better recovery.
13532 auto RecoveryExpr
=
13533 CreateRecoveryExpr(Init
->getBeginLoc(), Init
->getEndLoc(), Args
);
13534 if (RecoveryExpr
.get())
13535 VDecl
->setInit(RecoveryExpr
.get());
13539 Init
= Result
.getAs
<Expr
>();
13540 IsParenListInit
= !InitSeq
.steps().empty() &&
13541 InitSeq
.step_begin()->Kind
==
13542 InitializationSequence::SK_ParenthesizedListInit
;
13543 QualType VDeclType
= VDecl
->getType();
13544 if (Init
&& !Init
->getType().isNull() &&
13545 !Init
->getType()->isDependentType() && !VDeclType
->isDependentType() &&
13546 Context
.getAsIncompleteArrayType(VDeclType
) &&
13547 Context
.getAsIncompleteArrayType(Init
->getType())) {
13548 // Bail out if it is not possible to deduce array size from the
13550 Diag(VDecl
->getLocation(), diag::err_typecheck_decl_incomplete_type
)
13552 VDecl
->setInvalidDecl();
13557 // Check for self-references within variable initializers.
13558 // Variables declared within a function/method body (except for references)
13559 // are handled by a dataflow analysis.
13560 // This is undefined behavior in C++, but valid in C.
13561 if (getLangOpts().CPlusPlus
)
13562 if (!VDecl
->hasLocalStorage() || VDecl
->getType()->isRecordType() ||
13563 VDecl
->getType()->isReferenceType())
13564 CheckSelfReference(*this, RealDecl
, Init
, DirectInit
);
13566 // If the type changed, it means we had an incomplete type that was
13567 // completed by the initializer. For example:
13568 // int ary[] = { 1, 3, 5 };
13569 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13570 if (!VDecl
->isInvalidDecl() && (DclT
!= SavT
))
13571 VDecl
->setType(DclT
);
13573 if (!VDecl
->isInvalidDecl()) {
13574 checkUnsafeAssigns(VDecl
->getLocation(), VDecl
->getType(), Init
);
13576 if (VDecl
->hasAttr
<BlocksAttr
>())
13577 checkRetainCycles(VDecl
, Init
);
13579 // It is safe to assign a weak reference into a strong variable.
13580 // Although this code can still have problems:
13581 // id x = self.weakProp;
13582 // id y = self.weakProp;
13583 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13584 // paths through the function. This should be revisited if
13585 // -Wrepeated-use-of-weak is made flow-sensitive.
13586 if (FunctionScopeInfo
*FSI
= getCurFunction())
13587 if ((VDecl
->getType().getObjCLifetime() == Qualifiers::OCL_Strong
||
13588 VDecl
->getType().isNonWeakInMRRWithObjCWeak(Context
)) &&
13589 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
13590 Init
->getBeginLoc()))
13591 FSI
->markSafeWeakUse(Init
);
13594 // The initialization is usually a full-expression.
13596 // FIXME: If this is a braced initialization of an aggregate, it is not
13597 // an expression, and each individual field initializer is a separate
13598 // full-expression. For instance, in:
13600 // struct Temp { ~Temp(); };
13601 // struct S { S(Temp); };
13602 // struct T { S a, b; } t = { Temp(), Temp() }
13604 // we should destroy the first Temp before constructing the second.
13605 ExprResult Result
=
13606 ActOnFinishFullExpr(Init
, VDecl
->getLocation(),
13607 /*DiscardedValue*/ false, VDecl
->isConstexpr());
13608 if (Result
.isInvalid()) {
13609 VDecl
->setInvalidDecl();
13612 Init
= Result
.get();
13614 // Attach the initializer to the decl.
13615 VDecl
->setInit(Init
);
13617 if (VDecl
->isLocalVarDecl()) {
13618 // Don't check the initializer if the declaration is malformed.
13619 if (VDecl
->isInvalidDecl()) {
13622 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13623 // This is true even in C++ for OpenCL.
13624 } else if (VDecl
->getType().getAddressSpace() == LangAS::opencl_constant
) {
13625 CheckForConstantInitializer(Init
, DclT
);
13627 // Otherwise, C++ does not restrict the initializer.
13628 } else if (getLangOpts().CPlusPlus
) {
13631 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13632 // static storage duration shall be constant expressions or string literals.
13633 } else if (VDecl
->getStorageClass() == SC_Static
) {
13634 CheckForConstantInitializer(Init
, DclT
);
13636 // C89 is stricter than C99 for aggregate initializers.
13637 // C89 6.5.7p3: All the expressions [...] in an initializer list
13638 // for an object that has aggregate or union type shall be
13639 // constant expressions.
13640 } else if (!getLangOpts().C99
&& VDecl
->getType()->isAggregateType() &&
13641 isa
<InitListExpr
>(Init
)) {
13642 const Expr
*Culprit
;
13643 if (!Init
->isConstantInitializer(Context
, false, &Culprit
)) {
13644 Diag(Culprit
->getExprLoc(),
13645 diag::ext_aggregate_init_not_constant
)
13646 << Culprit
->getSourceRange();
13650 if (auto *E
= dyn_cast
<ExprWithCleanups
>(Init
))
13651 if (auto *BE
= dyn_cast
<BlockExpr
>(E
->getSubExpr()->IgnoreParens()))
13652 if (VDecl
->hasLocalStorage())
13653 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
13654 } else if (VDecl
->isStaticDataMember() && !VDecl
->isInline() &&
13655 VDecl
->getLexicalDeclContext()->isRecord()) {
13656 // This is an in-class initialization for a static data member, e.g.,
13659 // static const int value = 17;
13662 // C++ [class.mem]p4:
13663 // A member-declarator can contain a constant-initializer only
13664 // if it declares a static member (9.4) of const integral or
13665 // const enumeration type, see 9.4.2.
13667 // C++11 [class.static.data]p3:
13668 // If a non-volatile non-inline const static data member is of integral
13669 // or enumeration type, its declaration in the class definition can
13670 // specify a brace-or-equal-initializer in which every initializer-clause
13671 // that is an assignment-expression is a constant expression. A static
13672 // data member of literal type can be declared in the class definition
13673 // with the constexpr specifier; if so, its declaration shall specify a
13674 // brace-or-equal-initializer in which every initializer-clause that is
13675 // an assignment-expression is a constant expression.
13677 // Do nothing on dependent types.
13678 if (DclT
->isDependentType()) {
13680 // Allow any 'static constexpr' members, whether or not they are of literal
13681 // type. We separately check that every constexpr variable is of literal
13683 } else if (VDecl
->isConstexpr()) {
13685 // Require constness.
13686 } else if (!DclT
.isConstQualified()) {
13687 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_non_const
)
13688 << Init
->getSourceRange();
13689 VDecl
->setInvalidDecl();
13691 // We allow integer constant expressions in all cases.
13692 } else if (DclT
->isIntegralOrEnumerationType()) {
13693 // Check whether the expression is a constant expression.
13694 SourceLocation Loc
;
13695 if (getLangOpts().CPlusPlus11
&& DclT
.isVolatileQualified())
13696 // In C++11, a non-constexpr const static data member with an
13697 // in-class initializer cannot be volatile.
13698 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_volatile
);
13699 else if (Init
->isValueDependent())
13700 ; // Nothing to check.
13701 else if (Init
->isIntegerConstantExpr(Context
, &Loc
))
13702 ; // Ok, it's an ICE!
13703 else if (Init
->getType()->isScopedEnumeralType() &&
13704 Init
->isCXX11ConstantExpr(Context
))
13705 ; // Ok, it is a scoped-enum constant expression.
13706 else if (Init
->isEvaluatable(Context
)) {
13707 // If we can constant fold the initializer through heroics, accept it,
13708 // but report this as a use of an extension for -pedantic.
13709 Diag(Loc
, diag::ext_in_class_initializer_non_constant
)
13710 << Init
->getSourceRange();
13712 // Otherwise, this is some crazy unknown case. Report the issue at the
13713 // location provided by the isIntegerConstantExpr failed check.
13714 Diag(Loc
, diag::err_in_class_initializer_non_constant
)
13715 << Init
->getSourceRange();
13716 VDecl
->setInvalidDecl();
13719 // We allow foldable floating-point constants as an extension.
13720 } else if (DclT
->isFloatingType()) { // also permits complex, which is ok
13721 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13722 // it anyway and provide a fixit to add the 'constexpr'.
13723 if (getLangOpts().CPlusPlus11
) {
13724 Diag(VDecl
->getLocation(),
13725 diag::ext_in_class_initializer_float_type_cxx11
)
13726 << DclT
<< Init
->getSourceRange();
13727 Diag(VDecl
->getBeginLoc(),
13728 diag::note_in_class_initializer_float_type_cxx11
)
13729 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13731 Diag(VDecl
->getLocation(), diag::ext_in_class_initializer_float_type
)
13732 << DclT
<< Init
->getSourceRange();
13734 if (!Init
->isValueDependent() && !Init
->isEvaluatable(Context
)) {
13735 Diag(Init
->getExprLoc(), diag::err_in_class_initializer_non_constant
)
13736 << Init
->getSourceRange();
13737 VDecl
->setInvalidDecl();
13741 // Suggest adding 'constexpr' in C++11 for literal types.
13742 } else if (getLangOpts().CPlusPlus11
&& DclT
->isLiteralType(Context
)) {
13743 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_literal_type
)
13744 << DclT
<< Init
->getSourceRange()
13745 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13746 VDecl
->setConstexpr(true);
13749 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_bad_type
)
13750 << DclT
<< Init
->getSourceRange();
13751 VDecl
->setInvalidDecl();
13753 } else if (VDecl
->isFileVarDecl()) {
13754 // In C, extern is typically used to avoid tentative definitions when
13755 // declaring variables in headers, but adding an intializer makes it a
13756 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13757 // In C++, extern is often used to give implictly static const variables
13758 // external linkage, so don't warn in that case. If selectany is present,
13759 // this might be header code intended for C and C++ inclusion, so apply the
13761 if (VDecl
->getStorageClass() == SC_Extern
&&
13762 ((!getLangOpts().CPlusPlus
&& !VDecl
->hasAttr
<SelectAnyAttr
>()) ||
13763 !Context
.getBaseElementType(VDecl
->getType()).isConstQualified()) &&
13764 !(getLangOpts().CPlusPlus
&& VDecl
->isExternC()) &&
13765 !isTemplateInstantiation(VDecl
->getTemplateSpecializationKind()))
13766 Diag(VDecl
->getLocation(), diag::warn_extern_init
);
13768 // In Microsoft C++ mode, a const variable defined in namespace scope has
13769 // external linkage by default if the variable is declared with
13770 // __declspec(dllexport).
13771 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
13772 getLangOpts().CPlusPlus
&& VDecl
->getType().isConstQualified() &&
13773 VDecl
->hasAttr
<DLLExportAttr
>() && VDecl
->getDefinition())
13774 VDecl
->setStorageClass(SC_Extern
);
13776 // C99 6.7.8p4. All file scoped initializers need to be constant.
13777 if (!getLangOpts().CPlusPlus
&& !VDecl
->isInvalidDecl())
13778 CheckForConstantInitializer(Init
, DclT
);
13781 QualType InitType
= Init
->getType();
13782 if (!InitType
.isNull() &&
13783 (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13784 InitType
.hasNonTrivialToPrimitiveCopyCUnion()))
13785 checkNonTrivialCUnionInInitializer(Init
, Init
->getExprLoc());
13787 // We will represent direct-initialization similarly to copy-initialization:
13788 // int x(1); -as-> int x = 1;
13789 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13791 // Clients that want to distinguish between the two forms, can check for
13792 // direct initializer using VarDecl::getInitStyle().
13793 // A major benefit is that clients that don't particularly care about which
13794 // exactly form was it (like the CodeGen) can handle both cases without
13795 // special case code.
13798 // The form of initialization (using parentheses or '=') is generally
13799 // insignificant, but does matter when the entity being initialized has a
13801 if (CXXDirectInit
) {
13802 assert(DirectInit
&& "Call-style initializer must be direct init.");
13803 VDecl
->setInitStyle(IsParenListInit
? VarDecl::ParenListInit
13804 : VarDecl::CallInit
);
13805 } else if (DirectInit
) {
13806 // This must be list-initialization. No other way is direct-initialization.
13807 VDecl
->setInitStyle(VarDecl::ListInit
);
13810 if (LangOpts
.OpenMP
&&
13811 (LangOpts
.OpenMPIsTargetDevice
|| !LangOpts
.OMPTargetTriples
.empty()) &&
13812 VDecl
->isFileVarDecl())
13813 DeclsToCheckForDeferredDiags
.insert(VDecl
);
13814 CheckCompleteVariableDeclaration(VDecl
);
13817 /// ActOnInitializerError - Given that there was an error parsing an
13818 /// initializer for the given declaration, try to at least re-establish
13819 /// invariants such as whether a variable's type is either dependent or
13821 void Sema::ActOnInitializerError(Decl
*D
) {
13822 // Our main concern here is re-establishing invariants like "a
13823 // variable's type is either dependent or complete".
13824 if (!D
|| D
->isInvalidDecl()) return;
13826 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
13829 // Bindings are not usable if we can't make sense of the initializer.
13830 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
))
13831 for (auto *BD
: DD
->bindings())
13832 BD
->setInvalidDecl();
13834 // Auto types are meaningless if we can't make sense of the initializer.
13835 if (VD
->getType()->isUndeducedType()) {
13836 D
->setInvalidDecl();
13840 QualType Ty
= VD
->getType();
13841 if (Ty
->isDependentType()) return;
13843 // Require a complete type.
13844 if (RequireCompleteType(VD
->getLocation(),
13845 Context
.getBaseElementType(Ty
),
13846 diag::err_typecheck_decl_incomplete_type
)) {
13847 VD
->setInvalidDecl();
13851 // Require a non-abstract type.
13852 if (RequireNonAbstractType(VD
->getLocation(), Ty
,
13853 diag::err_abstract_type_in_decl
,
13854 AbstractVariableType
)) {
13855 VD
->setInvalidDecl();
13859 // Don't bother complaining about constructors or destructors,
13863 void Sema::ActOnUninitializedDecl(Decl
*RealDecl
) {
13864 // If there is no declaration, there was an error parsing it. Just ignore it.
13868 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(RealDecl
)) {
13869 QualType Type
= Var
->getType();
13871 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13872 if (isa
<DecompositionDecl
>(RealDecl
)) {
13873 Diag(Var
->getLocation(), diag::err_decomp_decl_requires_init
) << Var
;
13874 Var
->setInvalidDecl();
13878 if (Type
->isUndeducedType() &&
13879 DeduceVariableDeclarationType(Var
, false, nullptr))
13882 // C++11 [class.static.data]p3: A static data member can be declared with
13883 // the constexpr specifier; if so, its declaration shall specify
13884 // a brace-or-equal-initializer.
13885 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13886 // the definition of a variable [...] or the declaration of a static data
13888 if (Var
->isConstexpr() && !Var
->isThisDeclarationADefinition() &&
13889 !Var
->isThisDeclarationADemotedDefinition()) {
13890 if (Var
->isStaticDataMember()) {
13891 // C++1z removes the relevant rule; the in-class declaration is always
13892 // a definition there.
13893 if (!getLangOpts().CPlusPlus17
&&
13894 !Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
13895 Diag(Var
->getLocation(),
13896 diag::err_constexpr_static_mem_var_requires_init
)
13898 Var
->setInvalidDecl();
13902 Diag(Var
->getLocation(), diag::err_invalid_constexpr_var_decl
);
13903 Var
->setInvalidDecl();
13908 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13910 if (!Var
->isInvalidDecl() &&
13911 Var
->getType().getAddressSpace() == LangAS::opencl_constant
&&
13912 Var
->getStorageClass() != SC_Extern
&& !Var
->getInit()) {
13913 bool HasConstExprDefaultConstructor
= false;
13914 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13915 for (auto *Ctor
: RD
->ctors()) {
13916 if (Ctor
->isConstexpr() && Ctor
->getNumParams() == 0 &&
13917 Ctor
->getMethodQualifiers().getAddressSpace() ==
13918 LangAS::opencl_constant
) {
13919 HasConstExprDefaultConstructor
= true;
13923 if (!HasConstExprDefaultConstructor
) {
13924 Diag(Var
->getLocation(), diag::err_opencl_constant_no_init
);
13925 Var
->setInvalidDecl();
13930 if (!Var
->isInvalidDecl() && RealDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
13931 if (Var
->getStorageClass() == SC_Extern
) {
13932 Diag(Var
->getLocation(), diag::err_loader_uninitialized_extern_decl
)
13934 Var
->setInvalidDecl();
13937 if (RequireCompleteType(Var
->getLocation(), Var
->getType(),
13938 diag::err_typecheck_decl_incomplete_type
)) {
13939 Var
->setInvalidDecl();
13942 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13943 if (!RD
->hasTrivialDefaultConstructor()) {
13944 Diag(Var
->getLocation(), diag::err_loader_uninitialized_trivial_ctor
);
13945 Var
->setInvalidDecl();
13949 // The declaration is unitialized, no need for further checks.
13953 VarDecl::DefinitionKind DefKind
= Var
->isThisDeclarationADefinition();
13954 if (!Var
->isInvalidDecl() && DefKind
!= VarDecl::DeclarationOnly
&&
13955 Var
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13956 checkNonTrivialCUnion(Var
->getType(), Var
->getLocation(),
13957 NTCUC_DefaultInitializedObject
, NTCUK_Init
);
13961 case VarDecl::Definition
:
13962 if (!Var
->isStaticDataMember() || !Var
->getAnyInitializer())
13965 // We have an out-of-line definition of a static data member
13966 // that has an in-class initializer, so we type-check this like
13971 case VarDecl::DeclarationOnly
:
13972 // It's only a declaration.
13974 // Block scope. C99 6.7p7: If an identifier for an object is
13975 // declared with no linkage (C99 6.2.2p6), the type for the
13976 // object shall be complete.
13977 if (!Type
->isDependentType() && Var
->isLocalVarDecl() &&
13978 !Var
->hasLinkage() && !Var
->isInvalidDecl() &&
13979 RequireCompleteType(Var
->getLocation(), Type
,
13980 diag::err_typecheck_decl_incomplete_type
))
13981 Var
->setInvalidDecl();
13983 // Make sure that the type is not abstract.
13984 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13985 RequireNonAbstractType(Var
->getLocation(), Type
,
13986 diag::err_abstract_type_in_decl
,
13987 AbstractVariableType
))
13988 Var
->setInvalidDecl();
13989 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13990 Var
->getStorageClass() == SC_PrivateExtern
) {
13991 Diag(Var
->getLocation(), diag::warn_private_extern
);
13992 Diag(Var
->getLocation(), diag::note_private_extern
);
13995 if (Context
.getTargetInfo().allowDebugInfoForExternalRef() &&
13996 !Var
->isInvalidDecl())
13997 ExternalDeclarations
.push_back(Var
);
14001 case VarDecl::TentativeDefinition
:
14002 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14003 // object that has file scope without an initializer, and without a
14004 // storage-class specifier or with the storage-class specifier "static",
14005 // constitutes a tentative definition. Note: A tentative definition with
14006 // external linkage is valid (C99 6.2.2p5).
14007 if (!Var
->isInvalidDecl()) {
14008 if (const IncompleteArrayType
*ArrayT
14009 = Context
.getAsIncompleteArrayType(Type
)) {
14010 if (RequireCompleteSizedType(
14011 Var
->getLocation(), ArrayT
->getElementType(),
14012 diag::err_array_incomplete_or_sizeless_type
))
14013 Var
->setInvalidDecl();
14014 } else if (Var
->getStorageClass() == SC_Static
) {
14015 // C99 6.9.2p3: If the declaration of an identifier for an object is
14016 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14017 // declared type shall not be an incomplete type.
14018 // NOTE: code such as the following
14019 // static struct s;
14020 // struct s { int a; };
14021 // is accepted by gcc. Hence here we issue a warning instead of
14022 // an error and we do not invalidate the static declaration.
14023 // NOTE: to avoid multiple warnings, only check the first declaration.
14024 if (Var
->isFirstDecl())
14025 RequireCompleteType(Var
->getLocation(), Type
,
14026 diag::ext_typecheck_decl_incomplete_type
);
14030 // Record the tentative definition; we're done.
14031 if (!Var
->isInvalidDecl())
14032 TentativeDefinitions
.push_back(Var
);
14036 // Provide a specific diagnostic for uninitialized variable
14037 // definitions with incomplete array type.
14038 if (Type
->isIncompleteArrayType()) {
14039 if (Var
->isConstexpr())
14040 Diag(Var
->getLocation(), diag::err_constexpr_var_requires_const_init
)
14043 Diag(Var
->getLocation(),
14044 diag::err_typecheck_incomplete_array_needs_initializer
);
14045 Var
->setInvalidDecl();
14049 // Provide a specific diagnostic for uninitialized variable
14050 // definitions with reference type.
14051 if (Type
->isReferenceType()) {
14052 Diag(Var
->getLocation(), diag::err_reference_var_requires_init
)
14053 << Var
<< SourceRange(Var
->getLocation(), Var
->getLocation());
14057 // Do not attempt to type-check the default initializer for a
14058 // variable with dependent type.
14059 if (Type
->isDependentType())
14062 if (Var
->isInvalidDecl())
14065 if (!Var
->hasAttr
<AliasAttr
>()) {
14066 if (RequireCompleteType(Var
->getLocation(),
14067 Context
.getBaseElementType(Type
),
14068 diag::err_typecheck_decl_incomplete_type
)) {
14069 Var
->setInvalidDecl();
14076 // The variable can not have an abstract class type.
14077 if (RequireNonAbstractType(Var
->getLocation(), Type
,
14078 diag::err_abstract_type_in_decl
,
14079 AbstractVariableType
)) {
14080 Var
->setInvalidDecl();
14084 // Check for jumps past the implicit initializer. C++0x
14085 // clarifies that this applies to a "variable with automatic
14086 // storage duration", not a "local variable".
14087 // C++11 [stmt.dcl]p3
14088 // A program that jumps from a point where a variable with automatic
14089 // storage duration is not in scope to a point where it is in scope is
14090 // ill-formed unless the variable has scalar type, class type with a
14091 // trivial default constructor and a trivial destructor, a cv-qualified
14092 // version of one of these types, or an array of one of the preceding
14093 // types and is declared without an initializer.
14094 if (getLangOpts().CPlusPlus
&& Var
->hasLocalStorage()) {
14095 if (const RecordType
*Record
14096 = Context
.getBaseElementType(Type
)->getAs
<RecordType
>()) {
14097 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
->getDecl());
14098 // Mark the function (if we're in one) for further checking even if the
14099 // looser rules of C++11 do not require such checks, so that we can
14100 // diagnose incompatibilities with C++98.
14101 if (!CXXRecord
->isPOD())
14102 setFunctionHasBranchProtectedScope();
14105 // In OpenCL, we can't initialize objects in the __local address space,
14106 // even implicitly, so don't synthesize an implicit initializer.
14107 if (getLangOpts().OpenCL
&&
14108 Var
->getType().getAddressSpace() == LangAS::opencl_local
)
14110 // C++03 [dcl.init]p9:
14111 // If no initializer is specified for an object, and the
14112 // object is of (possibly cv-qualified) non-POD class type (or
14113 // array thereof), the object shall be default-initialized; if
14114 // the object is of const-qualified type, the underlying class
14115 // type shall have a user-declared default
14116 // constructor. Otherwise, if no initializer is specified for
14117 // a non- static object, the object and its subobjects, if
14118 // any, have an indeterminate initial value); if the object
14119 // or any of its subobjects are of const-qualified type, the
14120 // program is ill-formed.
14121 // C++0x [dcl.init]p11:
14122 // If no initializer is specified for an object, the object is
14123 // default-initialized; [...].
14124 InitializedEntity Entity
= InitializedEntity::InitializeVariable(Var
);
14125 InitializationKind Kind
14126 = InitializationKind::CreateDefault(Var
->getLocation());
14128 InitializationSequence
InitSeq(*this, Entity
, Kind
, std::nullopt
);
14129 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, std::nullopt
);
14132 Var
->setInit(MaybeCreateExprWithCleanups(Init
.get()));
14133 // This is important for template substitution.
14134 Var
->setInitStyle(VarDecl::CallInit
);
14135 } else if (Init
.isInvalid()) {
14136 // If default-init fails, attach a recovery-expr initializer to track
14137 // that initialization was attempted and failed.
14138 auto RecoveryExpr
=
14139 CreateRecoveryExpr(Var
->getLocation(), Var
->getLocation(), {});
14140 if (RecoveryExpr
.get())
14141 Var
->setInit(RecoveryExpr
.get());
14144 CheckCompleteVariableDeclaration(Var
);
14148 void Sema::ActOnCXXForRangeDecl(Decl
*D
) {
14149 // If there is no declaration, there was an error parsing it. Ignore it.
14153 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
14155 Diag(D
->getLocation(), diag::err_for_range_decl_must_be_var
);
14156 D
->setInvalidDecl();
14160 VD
->setCXXForRangeDecl(true);
14162 // for-range-declaration cannot be given a storage class specifier.
14164 switch (VD
->getStorageClass()) {
14173 case SC_PrivateExtern
:
14184 // for-range-declaration cannot be given a storage class specifier con't.
14185 switch (VD
->getTSCSpec()) {
14186 case TSCS_thread_local
:
14189 case TSCS___thread
:
14190 case TSCS__Thread_local
:
14191 case TSCS_unspecified
:
14196 Diag(VD
->getOuterLocStart(), diag::err_for_range_storage_class
)
14198 D
->setInvalidDecl();
14202 StmtResult
Sema::ActOnCXXForRangeIdentifier(Scope
*S
, SourceLocation IdentLoc
,
14203 IdentifierInfo
*Ident
,
14204 ParsedAttributes
&Attrs
) {
14205 // C++1y [stmt.iter]p1:
14206 // A range-based for statement of the form
14207 // for ( for-range-identifier : for-range-initializer ) statement
14208 // is equivalent to
14209 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14210 DeclSpec
DS(Attrs
.getPool().getFactory());
14212 const char *PrevSpec
;
14214 DS
.SetTypeSpecType(DeclSpec::TST_auto
, IdentLoc
, PrevSpec
, DiagID
,
14215 getPrintingPolicy());
14217 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::ForInit
);
14218 D
.SetIdentifier(Ident
, IdentLoc
);
14219 D
.takeAttributes(Attrs
);
14221 D
.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc
, /*lvalue*/ false),
14223 Decl
*Var
= ActOnDeclarator(S
, D
);
14224 cast
<VarDecl
>(Var
)->setCXXForRangeDecl(true);
14225 FinalizeDeclaration(Var
);
14226 return ActOnDeclStmt(FinalizeDeclaratorGroup(S
, DS
, Var
), IdentLoc
,
14227 Attrs
.Range
.getEnd().isValid() ? Attrs
.Range
.getEnd()
14231 void Sema::CheckCompleteVariableDeclaration(VarDecl
*var
) {
14232 if (var
->isInvalidDecl()) return;
14234 MaybeAddCUDAConstantAttr(var
);
14236 if (getLangOpts().OpenCL
) {
14237 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14239 if (var
->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14241 Diag(var
->getLocation(), diag::err_opencl_invalid_block_declaration
)
14243 var
->setInvalidDecl();
14248 // In Objective-C, don't allow jumps past the implicit initialization of a
14249 // local retaining variable.
14250 if (getLangOpts().ObjC
&&
14251 var
->hasLocalStorage()) {
14252 switch (var
->getType().getObjCLifetime()) {
14253 case Qualifiers::OCL_None
:
14254 case Qualifiers::OCL_ExplicitNone
:
14255 case Qualifiers::OCL_Autoreleasing
:
14258 case Qualifiers::OCL_Weak
:
14259 case Qualifiers::OCL_Strong
:
14260 setFunctionHasBranchProtectedScope();
14265 if (var
->hasLocalStorage() &&
14266 var
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
14267 setFunctionHasBranchProtectedScope();
14269 // Warn about externally-visible variables being defined without a
14270 // prior declaration. We only want to do this for global
14271 // declarations, but we also specifically need to avoid doing it for
14272 // class members because the linkage of an anonymous class can
14273 // change if it's later given a typedef name.
14274 if (var
->isThisDeclarationADefinition() &&
14275 var
->getDeclContext()->getRedeclContext()->isFileContext() &&
14276 var
->isExternallyVisible() && var
->hasLinkage() &&
14277 !var
->isInline() && !var
->getDescribedVarTemplate() &&
14278 var
->getStorageClass() != SC_Register
&&
14279 !isa
<VarTemplatePartialSpecializationDecl
>(var
) &&
14280 !isTemplateInstantiation(var
->getTemplateSpecializationKind()) &&
14281 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations
,
14282 var
->getLocation())) {
14283 // Find a previous declaration that's not a definition.
14284 VarDecl
*prev
= var
->getPreviousDecl();
14285 while (prev
&& prev
->isThisDeclarationADefinition())
14286 prev
= prev
->getPreviousDecl();
14289 Diag(var
->getLocation(), diag::warn_missing_variable_declarations
) << var
;
14290 Diag(var
->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage
)
14291 << /* variable */ 0;
14295 // Cache the result of checking for constant initialization.
14296 std::optional
<bool> CacheHasConstInit
;
14297 const Expr
*CacheCulprit
= nullptr;
14298 auto checkConstInit
= [&]() mutable {
14299 if (!CacheHasConstInit
)
14300 CacheHasConstInit
= var
->getInit()->isConstantInitializer(
14301 Context
, var
->getType()->isReferenceType(), &CacheCulprit
);
14302 return *CacheHasConstInit
;
14305 if (var
->getTLSKind() == VarDecl::TLS_Static
) {
14306 if (var
->getType().isDestructedType()) {
14307 // GNU C++98 edits for __thread, [basic.start.term]p3:
14308 // The type of an object with thread storage duration shall not
14309 // have a non-trivial destructor.
14310 Diag(var
->getLocation(), diag::err_thread_nontrivial_dtor
);
14311 if (getLangOpts().CPlusPlus11
)
14312 Diag(var
->getLocation(), diag::note_use_thread_local
);
14313 } else if (getLangOpts().CPlusPlus
&& var
->hasInit()) {
14314 if (!checkConstInit()) {
14315 // GNU C++98 edits for __thread, [basic.start.init]p4:
14316 // An object of thread storage duration shall not require dynamic
14318 // FIXME: Need strict checking here.
14319 Diag(CacheCulprit
->getExprLoc(), diag::err_thread_dynamic_init
)
14320 << CacheCulprit
->getSourceRange();
14321 if (getLangOpts().CPlusPlus11
)
14322 Diag(var
->getLocation(), diag::note_use_thread_local
);
14328 if (!var
->getType()->isStructureType() && var
->hasInit() &&
14329 isa
<InitListExpr
>(var
->getInit())) {
14330 const auto *ILE
= cast
<InitListExpr
>(var
->getInit());
14331 unsigned NumInits
= ILE
->getNumInits();
14333 for (unsigned I
= 0; I
< NumInits
; ++I
) {
14334 const auto *Init
= ILE
->getInit(I
);
14337 const auto *SL
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
14341 unsigned NumConcat
= SL
->getNumConcatenated();
14342 // Diagnose missing comma in string array initialization.
14343 // Do not warn when all the elements in the initializer are concatenated
14344 // together. Do not warn for macros too.
14345 if (NumConcat
== 2 && !SL
->getBeginLoc().isMacroID()) {
14346 bool OnlyOneMissingComma
= true;
14347 for (unsigned J
= I
+ 1; J
< NumInits
; ++J
) {
14348 const auto *Init
= ILE
->getInit(J
);
14351 const auto *SLJ
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
14352 if (!SLJ
|| SLJ
->getNumConcatenated() > 1) {
14353 OnlyOneMissingComma
= false;
14358 if (OnlyOneMissingComma
) {
14359 SmallVector
<FixItHint
, 1> Hints
;
14360 for (unsigned i
= 0; i
< NumConcat
- 1; ++i
)
14361 Hints
.push_back(FixItHint::CreateInsertion(
14362 PP
.getLocForEndOfToken(SL
->getStrTokenLoc(i
)), ","));
14364 Diag(SL
->getStrTokenLoc(1),
14365 diag::warn_concatenated_literal_array_init
)
14367 Diag(SL
->getBeginLoc(),
14368 diag::note_concatenated_string_literal_silence
);
14370 // In any case, stop now.
14377 QualType type
= var
->getType();
14379 if (var
->hasAttr
<BlocksAttr
>())
14380 getCurFunction()->addByrefBlockVar(var
);
14382 Expr
*Init
= var
->getInit();
14383 bool GlobalStorage
= var
->hasGlobalStorage();
14384 bool IsGlobal
= GlobalStorage
&& !var
->isStaticLocal();
14385 QualType baseType
= Context
.getBaseElementType(type
);
14386 bool HasConstInit
= true;
14388 // Check whether the initializer is sufficiently constant.
14389 if (getLangOpts().CPlusPlus
&& !type
->isDependentType() && Init
&&
14390 !Init
->isValueDependent() &&
14391 (GlobalStorage
|| var
->isConstexpr() ||
14392 var
->mightBeUsableInConstantExpressions(Context
))) {
14393 // If this variable might have a constant initializer or might be usable in
14394 // constant expressions, check whether or not it actually is now. We can't
14395 // do this lazily, because the result might depend on things that change
14396 // later, such as which constexpr functions happen to be defined.
14397 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
14398 if (!getLangOpts().CPlusPlus11
) {
14399 // Prior to C++11, in contexts where a constant initializer is required,
14400 // the set of valid constant initializers is described by syntactic rules
14401 // in [expr.const]p2-6.
14402 // FIXME: Stricter checking for these rules would be useful for constinit /
14403 // -Wglobal-constructors.
14404 HasConstInit
= checkConstInit();
14406 // Compute and cache the constant value, and remember that we have a
14407 // constant initializer.
14408 if (HasConstInit
) {
14409 (void)var
->checkForConstantInitialization(Notes
);
14411 } else if (CacheCulprit
) {
14412 Notes
.emplace_back(CacheCulprit
->getExprLoc(),
14413 PDiag(diag::note_invalid_subexpr_in_const_expr
));
14414 Notes
.back().second
<< CacheCulprit
->getSourceRange();
14417 // Evaluate the initializer to see if it's a constant initializer.
14418 HasConstInit
= var
->checkForConstantInitialization(Notes
);
14421 if (HasConstInit
) {
14422 // FIXME: Consider replacing the initializer with a ConstantExpr.
14423 } else if (var
->isConstexpr()) {
14424 SourceLocation DiagLoc
= var
->getLocation();
14425 // If the note doesn't add any useful information other than a source
14426 // location, fold it into the primary diagnostic.
14427 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
14428 diag::note_invalid_subexpr_in_const_expr
) {
14429 DiagLoc
= Notes
[0].first
;
14432 Diag(DiagLoc
, diag::err_constexpr_var_requires_const_init
)
14433 << var
<< Init
->getSourceRange();
14434 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
14435 Diag(Notes
[I
].first
, Notes
[I
].second
);
14436 } else if (GlobalStorage
&& var
->hasAttr
<ConstInitAttr
>()) {
14437 auto *Attr
= var
->getAttr
<ConstInitAttr
>();
14438 Diag(var
->getLocation(), diag::err_require_constant_init_failed
)
14439 << Init
->getSourceRange();
14440 Diag(Attr
->getLocation(), diag::note_declared_required_constant_init_here
)
14441 << Attr
->getRange() << Attr
->isConstinit();
14442 for (auto &it
: Notes
)
14443 Diag(it
.first
, it
.second
);
14444 } else if (IsGlobal
&&
14445 !getDiagnostics().isIgnored(diag::warn_global_constructor
,
14446 var
->getLocation())) {
14447 // Warn about globals which don't have a constant initializer. Don't
14448 // warn about globals with a non-trivial destructor because we already
14449 // warned about them.
14450 CXXRecordDecl
*RD
= baseType
->getAsCXXRecordDecl();
14451 if (!(RD
&& !RD
->hasTrivialDestructor())) {
14452 // checkConstInit() here permits trivial default initialization even in
14453 // C++11 onwards, where such an initializer is not a constant initializer
14454 // but nonetheless doesn't require a global constructor.
14455 if (!checkConstInit())
14456 Diag(var
->getLocation(), diag::warn_global_constructor
)
14457 << Init
->getSourceRange();
14462 // Apply section attributes and pragmas to global variables.
14463 if (GlobalStorage
&& var
->isThisDeclarationADefinition() &&
14464 !inTemplateInstantiation()) {
14465 PragmaStack
<StringLiteral
*> *Stack
= nullptr;
14466 int SectionFlags
= ASTContext::PSF_Read
;
14468 Context
.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14469 std::optional
<QualType::NonConstantStorageReason
> Reason
;
14470 if (HasConstInit
&&
14471 !(Reason
= var
->getType().isNonConstantStorage(Context
, true, false))) {
14472 Stack
= &ConstSegStack
;
14474 SectionFlags
|= ASTContext::PSF_Write
;
14475 Stack
= var
->hasInit() && HasConstInit
? &DataSegStack
: &BSSSegStack
;
14477 if (const SectionAttr
*SA
= var
->getAttr
<SectionAttr
>()) {
14478 if (SA
->getSyntax() == AttributeCommonInfo::AS_Declspec
)
14479 SectionFlags
|= ASTContext::PSF_Implicit
;
14480 UnifySection(SA
->getName(), SectionFlags
, var
);
14481 } else if (Stack
->CurrentValue
) {
14482 if (Stack
!= &ConstSegStack
&& MSVCEnv
&&
14483 ConstSegStack
.CurrentValue
!= ConstSegStack
.DefaultValue
&&
14484 var
->getType().isConstQualified()) {
14485 assert((!Reason
|| Reason
!= QualType::NonConstantStorageReason::
14486 NonConstNonReferenceType
) &&
14487 "This case should've already been handled elsewhere");
14488 Diag(var
->getLocation(), diag::warn_section_msvc_compat
)
14489 << var
<< ConstSegStack
.CurrentValue
<< (int)(!HasConstInit
14490 ? QualType::NonConstantStorageReason::NonTrivialCtor
14493 SectionFlags
|= ASTContext::PSF_Implicit
;
14494 auto SectionName
= Stack
->CurrentValue
->getString();
14495 var
->addAttr(SectionAttr::CreateImplicit(Context
, SectionName
,
14496 Stack
->CurrentPragmaLocation
,
14497 SectionAttr::Declspec_allocate
));
14498 if (UnifySection(SectionName
, SectionFlags
, var
))
14499 var
->dropAttr
<SectionAttr
>();
14502 // Apply the init_seg attribute if this has an initializer. If the
14503 // initializer turns out to not be dynamic, we'll end up ignoring this
14505 if (CurInitSeg
&& var
->getInit())
14506 var
->addAttr(InitSegAttr::CreateImplicit(Context
, CurInitSeg
->getString(),
14510 // All the following checks are C++ only.
14511 if (!getLangOpts().CPlusPlus
) {
14512 // If this variable must be emitted, add it as an initializer for the
14514 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
14515 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
14519 // Require the destructor.
14520 if (!type
->isDependentType())
14521 if (const RecordType
*recordType
= baseType
->getAs
<RecordType
>())
14522 FinalizeVarWithDestructor(var
, recordType
);
14524 // If this variable must be emitted, add it as an initializer for the current
14526 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
14527 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
14529 // Build the bindings if this is a structured binding declaration.
14530 if (auto *DD
= dyn_cast
<DecompositionDecl
>(var
))
14531 CheckCompleteDecompositionDeclaration(DD
);
14534 /// Check if VD needs to be dllexport/dllimport due to being in a
14535 /// dllexport/import function.
14536 void Sema::CheckStaticLocalForDllExport(VarDecl
*VD
) {
14537 assert(VD
->isStaticLocal());
14539 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
14541 // Find outermost function when VD is in lambda function.
14542 while (FD
&& !getDLLAttr(FD
) &&
14543 !FD
->hasAttr
<DLLExportStaticLocalAttr
>() &&
14544 !FD
->hasAttr
<DLLImportStaticLocalAttr
>()) {
14545 FD
= dyn_cast_or_null
<FunctionDecl
>(FD
->getParentFunctionOrMethod());
14551 // Static locals inherit dll attributes from their function.
14552 if (Attr
*A
= getDLLAttr(FD
)) {
14553 auto *NewAttr
= cast
<InheritableAttr
>(A
->clone(getASTContext()));
14554 NewAttr
->setInherited(true);
14555 VD
->addAttr(NewAttr
);
14556 } else if (Attr
*A
= FD
->getAttr
<DLLExportStaticLocalAttr
>()) {
14557 auto *NewAttr
= DLLExportAttr::CreateImplicit(getASTContext(), *A
);
14558 NewAttr
->setInherited(true);
14559 VD
->addAttr(NewAttr
);
14561 // Export this function to enforce exporting this static variable even
14562 // if it is not used in this compilation unit.
14563 if (!FD
->hasAttr
<DLLExportAttr
>())
14564 FD
->addAttr(NewAttr
);
14566 } else if (Attr
*A
= FD
->getAttr
<DLLImportStaticLocalAttr
>()) {
14567 auto *NewAttr
= DLLImportAttr::CreateImplicit(getASTContext(), *A
);
14568 NewAttr
->setInherited(true);
14569 VD
->addAttr(NewAttr
);
14573 void Sema::CheckThreadLocalForLargeAlignment(VarDecl
*VD
) {
14574 assert(VD
->getTLSKind());
14576 // Perform TLS alignment check here after attributes attached to the variable
14577 // which may affect the alignment have been processed. Only perform the check
14578 // if the target has a maximum TLS alignment (zero means no constraints).
14579 if (unsigned MaxAlign
= Context
.getTargetInfo().getMaxTLSAlign()) {
14580 // Protect the check so that it's not performed on dependent types and
14581 // dependent alignments (we can't determine the alignment in that case).
14582 if (!VD
->hasDependentAlignment()) {
14583 CharUnits MaxAlignChars
= Context
.toCharUnitsFromBits(MaxAlign
);
14584 if (Context
.getDeclAlign(VD
) > MaxAlignChars
) {
14585 Diag(VD
->getLocation(), diag::err_tls_var_aligned_over_maximum
)
14586 << (unsigned)Context
.getDeclAlign(VD
).getQuantity() << VD
14587 << (unsigned)MaxAlignChars
.getQuantity();
14593 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14594 /// any semantic actions necessary after any initializer has been attached.
14595 void Sema::FinalizeDeclaration(Decl
*ThisDecl
) {
14596 // Note that we are no longer parsing the initializer for this declaration.
14597 ParsingInitForAutoVars
.erase(ThisDecl
);
14599 VarDecl
*VD
= dyn_cast_or_null
<VarDecl
>(ThisDecl
);
14603 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14604 if (VD
->hasGlobalStorage() && VD
->isThisDeclarationADefinition() &&
14605 !inTemplateInstantiation() && !VD
->hasAttr
<SectionAttr
>()) {
14606 if (PragmaClangBSSSection
.Valid
)
14607 VD
->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14608 Context
, PragmaClangBSSSection
.SectionName
,
14609 PragmaClangBSSSection
.PragmaLocation
));
14610 if (PragmaClangDataSection
.Valid
)
14611 VD
->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14612 Context
, PragmaClangDataSection
.SectionName
,
14613 PragmaClangDataSection
.PragmaLocation
));
14614 if (PragmaClangRodataSection
.Valid
)
14615 VD
->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14616 Context
, PragmaClangRodataSection
.SectionName
,
14617 PragmaClangRodataSection
.PragmaLocation
));
14618 if (PragmaClangRelroSection
.Valid
)
14619 VD
->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14620 Context
, PragmaClangRelroSection
.SectionName
,
14621 PragmaClangRelroSection
.PragmaLocation
));
14624 if (auto *DD
= dyn_cast
<DecompositionDecl
>(ThisDecl
)) {
14625 for (auto *BD
: DD
->bindings()) {
14626 FinalizeDeclaration(BD
);
14630 checkAttributesAfterMerging(*this, *VD
);
14632 if (VD
->isStaticLocal())
14633 CheckStaticLocalForDllExport(VD
);
14635 if (VD
->getTLSKind())
14636 CheckThreadLocalForLargeAlignment(VD
);
14638 // Perform check for initializers of device-side global variables.
14639 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14640 // 7.5). We must also apply the same checks to all __shared__
14641 // variables whether they are local or not. CUDA also allows
14642 // constant initializers for __constant__ and __device__ variables.
14643 if (getLangOpts().CUDA
)
14644 checkAllowedCUDAInitializer(VD
);
14646 // Grab the dllimport or dllexport attribute off of the VarDecl.
14647 const InheritableAttr
*DLLAttr
= getDLLAttr(VD
);
14649 // Imported static data members cannot be defined out-of-line.
14650 if (const auto *IA
= dyn_cast_or_null
<DLLImportAttr
>(DLLAttr
)) {
14651 if (VD
->isStaticDataMember() && VD
->isOutOfLine() &&
14652 VD
->isThisDeclarationADefinition()) {
14653 // We allow definitions of dllimport class template static data members
14655 CXXRecordDecl
*Context
=
14656 cast
<CXXRecordDecl
>(VD
->getFirstDecl()->getDeclContext());
14657 bool IsClassTemplateMember
=
14658 isa
<ClassTemplatePartialSpecializationDecl
>(Context
) ||
14659 Context
->getDescribedClassTemplate();
14661 Diag(VD
->getLocation(),
14662 IsClassTemplateMember
14663 ? diag::warn_attribute_dllimport_static_field_definition
14664 : diag::err_attribute_dllimport_static_field_definition
);
14665 Diag(IA
->getLocation(), diag::note_attribute
);
14666 if (!IsClassTemplateMember
)
14667 VD
->setInvalidDecl();
14671 // dllimport/dllexport variables cannot be thread local, their TLS index
14672 // isn't exported with the variable.
14673 if (DLLAttr
&& VD
->getTLSKind()) {
14674 auto *F
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
14675 if (F
&& getDLLAttr(F
)) {
14676 assert(VD
->isStaticLocal());
14677 // But if this is a static local in a dlimport/dllexport function, the
14678 // function will never be inlined, which means the var would never be
14679 // imported, so having it marked import/export is safe.
14681 Diag(VD
->getLocation(), diag::err_attribute_dll_thread_local
) << VD
14683 VD
->setInvalidDecl();
14687 if (UsedAttr
*Attr
= VD
->getAttr
<UsedAttr
>()) {
14688 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14689 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14691 VD
->dropAttr
<UsedAttr
>();
14694 if (RetainAttr
*Attr
= VD
->getAttr
<RetainAttr
>()) {
14695 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14696 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14698 VD
->dropAttr
<RetainAttr
>();
14702 const DeclContext
*DC
= VD
->getDeclContext();
14703 // If there's a #pragma GCC visibility in scope, and this isn't a class
14704 // member, set the visibility of this variable.
14705 if (DC
->getRedeclContext()->isFileContext() && VD
->isExternallyVisible())
14706 AddPushedVisibilityAttribute(VD
);
14708 // FIXME: Warn on unused var template partial specializations.
14709 if (VD
->isFileVarDecl() && !isa
<VarTemplatePartialSpecializationDecl
>(VD
))
14710 MarkUnusedFileScopedDecl(VD
);
14712 // Now we have parsed the initializer and can update the table of magic
14714 if (!VD
->hasAttr
<TypeTagForDatatypeAttr
>() ||
14715 !VD
->getType()->isIntegralOrEnumerationType())
14718 for (const auto *I
: ThisDecl
->specific_attrs
<TypeTagForDatatypeAttr
>()) {
14719 const Expr
*MagicValueExpr
= VD
->getInit();
14720 if (!MagicValueExpr
) {
14723 std::optional
<llvm::APSInt
> MagicValueInt
;
14724 if (!(MagicValueInt
= MagicValueExpr
->getIntegerConstantExpr(Context
))) {
14725 Diag(I
->getRange().getBegin(),
14726 diag::err_type_tag_for_datatype_not_ice
)
14727 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14730 if (MagicValueInt
->getActiveBits() > 64) {
14731 Diag(I
->getRange().getBegin(),
14732 diag::err_type_tag_for_datatype_too_large
)
14733 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14736 uint64_t MagicValue
= MagicValueInt
->getZExtValue();
14737 RegisterTypeTagForDatatype(I
->getArgumentKind(),
14739 I
->getMatchingCType(),
14740 I
->getLayoutCompatible(),
14741 I
->getMustBeNull());
14745 static bool hasDeducedAuto(DeclaratorDecl
*DD
) {
14746 auto *VD
= dyn_cast
<VarDecl
>(DD
);
14747 return VD
&& !VD
->getType()->hasAutoForTrailingReturnType();
14750 Sema::DeclGroupPtrTy
Sema::FinalizeDeclaratorGroup(Scope
*S
, const DeclSpec
&DS
,
14751 ArrayRef
<Decl
*> Group
) {
14752 SmallVector
<Decl
*, 8> Decls
;
14754 if (DS
.isTypeSpecOwned())
14755 Decls
.push_back(DS
.getRepAsDecl());
14757 DeclaratorDecl
*FirstDeclaratorInGroup
= nullptr;
14758 DecompositionDecl
*FirstDecompDeclaratorInGroup
= nullptr;
14759 bool DiagnosedMultipleDecomps
= false;
14760 DeclaratorDecl
*FirstNonDeducedAutoInGroup
= nullptr;
14761 bool DiagnosedNonDeducedAuto
= false;
14763 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14764 if (Decl
*D
= Group
[i
]) {
14765 // Check if the Decl has been declared in '#pragma omp declare target'
14766 // directive and has static storage duration.
14767 if (auto *VD
= dyn_cast
<VarDecl
>(D
);
14768 LangOpts
.OpenMP
&& VD
&& VD
->hasAttr
<OMPDeclareTargetDeclAttr
>() &&
14769 VD
->hasGlobalStorage())
14770 ActOnOpenMPDeclareTargetInitializer(D
);
14771 // For declarators, there are some additional syntactic-ish checks we need
14773 if (auto *DD
= dyn_cast
<DeclaratorDecl
>(D
)) {
14774 if (!FirstDeclaratorInGroup
)
14775 FirstDeclaratorInGroup
= DD
;
14776 if (!FirstDecompDeclaratorInGroup
)
14777 FirstDecompDeclaratorInGroup
= dyn_cast
<DecompositionDecl
>(D
);
14778 if (!FirstNonDeducedAutoInGroup
&& DS
.hasAutoTypeSpec() &&
14779 !hasDeducedAuto(DD
))
14780 FirstNonDeducedAutoInGroup
= DD
;
14782 if (FirstDeclaratorInGroup
!= DD
) {
14783 // A decomposition declaration cannot be combined with any other
14784 // declaration in the same group.
14785 if (FirstDecompDeclaratorInGroup
&& !DiagnosedMultipleDecomps
) {
14786 Diag(FirstDecompDeclaratorInGroup
->getLocation(),
14787 diag::err_decomp_decl_not_alone
)
14788 << FirstDeclaratorInGroup
->getSourceRange()
14789 << DD
->getSourceRange();
14790 DiagnosedMultipleDecomps
= true;
14793 // A declarator that uses 'auto' in any way other than to declare a
14794 // variable with a deduced type cannot be combined with any other
14795 // declarator in the same group.
14796 if (FirstNonDeducedAutoInGroup
&& !DiagnosedNonDeducedAuto
) {
14797 Diag(FirstNonDeducedAutoInGroup
->getLocation(),
14798 diag::err_auto_non_deduced_not_alone
)
14799 << FirstNonDeducedAutoInGroup
->getType()
14800 ->hasAutoForTrailingReturnType()
14801 << FirstDeclaratorInGroup
->getSourceRange()
14802 << DD
->getSourceRange();
14803 DiagnosedNonDeducedAuto
= true;
14808 Decls
.push_back(D
);
14812 if (DeclSpec::isDeclRep(DS
.getTypeSpecType())) {
14813 if (TagDecl
*Tag
= dyn_cast_or_null
<TagDecl
>(DS
.getRepAsDecl())) {
14814 handleTagNumbering(Tag
, S
);
14815 if (FirstDeclaratorInGroup
&& !Tag
->hasNameForLinkage() &&
14816 getLangOpts().CPlusPlus
)
14817 Context
.addDeclaratorForUnnamedTagDecl(Tag
, FirstDeclaratorInGroup
);
14821 return BuildDeclaratorGroup(Decls
);
14824 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14825 /// group, performing any necessary semantic checking.
14826 Sema::DeclGroupPtrTy
14827 Sema::BuildDeclaratorGroup(MutableArrayRef
<Decl
*> Group
) {
14828 // C++14 [dcl.spec.auto]p7: (DR1347)
14829 // If the type that replaces the placeholder type is not the same in each
14830 // deduction, the program is ill-formed.
14831 if (Group
.size() > 1) {
14833 VarDecl
*DeducedDecl
= nullptr;
14834 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14835 VarDecl
*D
= dyn_cast
<VarDecl
>(Group
[i
]);
14836 if (!D
|| D
->isInvalidDecl())
14838 DeducedType
*DT
= D
->getType()->getContainedDeducedType();
14839 if (!DT
|| DT
->getDeducedType().isNull())
14841 if (Deduced
.isNull()) {
14842 Deduced
= DT
->getDeducedType();
14844 } else if (!Context
.hasSameType(DT
->getDeducedType(), Deduced
)) {
14845 auto *AT
= dyn_cast
<AutoType
>(DT
);
14846 auto Dia
= Diag(D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14847 diag::err_auto_different_deductions
)
14848 << (AT
? (unsigned)AT
->getKeyword() : 3) << Deduced
14849 << DeducedDecl
->getDeclName() << DT
->getDeducedType()
14850 << D
->getDeclName();
14851 if (DeducedDecl
->hasInit())
14852 Dia
<< DeducedDecl
->getInit()->getSourceRange();
14854 Dia
<< D
->getInit()->getSourceRange();
14855 D
->setInvalidDecl();
14861 ActOnDocumentableDecls(Group
);
14863 return DeclGroupPtrTy::make(
14864 DeclGroupRef::Create(Context
, Group
.data(), Group
.size()));
14867 void Sema::ActOnDocumentableDecl(Decl
*D
) {
14868 ActOnDocumentableDecls(D
);
14871 void Sema::ActOnDocumentableDecls(ArrayRef
<Decl
*> Group
) {
14872 // Don't parse the comment if Doxygen diagnostics are ignored.
14873 if (Group
.empty() || !Group
[0])
14876 if (Diags
.isIgnored(diag::warn_doc_param_not_found
,
14877 Group
[0]->getLocation()) &&
14878 Diags
.isIgnored(diag::warn_unknown_comment_command_name
,
14879 Group
[0]->getLocation()))
14882 if (Group
.size() >= 2) {
14883 // This is a decl group. Normally it will contain only declarations
14884 // produced from declarator list. But in case we have any definitions or
14885 // additional declaration references:
14886 // 'typedef struct S {} S;'
14887 // 'typedef struct S *S;'
14889 // FinalizeDeclaratorGroup adds these as separate declarations.
14890 Decl
*MaybeTagDecl
= Group
[0];
14891 if (MaybeTagDecl
&& isa
<TagDecl
>(MaybeTagDecl
)) {
14892 Group
= Group
.slice(1);
14896 // FIMXE: We assume every Decl in the group is in the same file.
14897 // This is false when preprocessor constructs the group from decls in
14898 // different files (e. g. macros or #include).
14899 Context
.attachCommentsToJustParsedDecls(Group
, &getPreprocessor());
14902 /// Common checks for a parameter-declaration that should apply to both function
14903 /// parameters and non-type template parameters.
14904 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope
*S
, Declarator
&D
) {
14905 // Check that there are no default arguments inside the type of this
14907 if (getLangOpts().CPlusPlus
)
14908 CheckExtraCXXDefaultArguments(D
);
14910 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14911 if (D
.getCXXScopeSpec().isSet()) {
14912 Diag(D
.getIdentifierLoc(), diag::err_qualified_param_declarator
)
14913 << D
.getCXXScopeSpec().getRange();
14916 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14917 // simple identifier except [...irrelevant cases...].
14918 switch (D
.getName().getKind()) {
14919 case UnqualifiedIdKind::IK_Identifier
:
14922 case UnqualifiedIdKind::IK_OperatorFunctionId
:
14923 case UnqualifiedIdKind::IK_ConversionFunctionId
:
14924 case UnqualifiedIdKind::IK_LiteralOperatorId
:
14925 case UnqualifiedIdKind::IK_ConstructorName
:
14926 case UnqualifiedIdKind::IK_DestructorName
:
14927 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
14928 case UnqualifiedIdKind::IK_DeductionGuideName
:
14929 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name
)
14930 << GetNameForDeclarator(D
).getName();
14933 case UnqualifiedIdKind::IK_TemplateId
:
14934 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
14935 // GetNameForDeclarator would not produce a useful name in this case.
14936 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name_template_id
);
14941 static void CheckExplicitObjectParameter(Sema
&S
, ParmVarDecl
*P
,
14942 SourceLocation ExplicitThisLoc
) {
14943 if (!ExplicitThisLoc
.isValid())
14945 assert(S
.getLangOpts().CPlusPlus
&&
14946 "explicit parameter in non-cplusplus mode");
14947 if (!S
.getLangOpts().CPlusPlus23
)
14948 S
.Diag(ExplicitThisLoc
, diag::err_cxx20_deducing_this
)
14949 << P
->getSourceRange();
14951 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14953 if (P
->isParameterPack()) {
14954 S
.Diag(P
->getBeginLoc(), diag::err_explicit_object_parameter_pack
)
14955 << P
->getSourceRange();
14958 P
->setExplicitObjectParameterLoc(ExplicitThisLoc
);
14959 if (LambdaScopeInfo
*LSI
= S
.getCurLambda())
14960 LSI
->ExplicitObjectParameter
= P
;
14963 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14964 /// to introduce parameters into function prototype scope.
14965 Decl
*Sema::ActOnParamDeclarator(Scope
*S
, Declarator
&D
,
14966 SourceLocation ExplicitThisLoc
) {
14967 const DeclSpec
&DS
= D
.getDeclSpec();
14969 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14971 // C++03 [dcl.stc]p2 also permits 'auto'.
14972 StorageClass SC
= SC_None
;
14973 if (DS
.getStorageClassSpec() == DeclSpec::SCS_register
) {
14975 // In C++11, the 'register' storage class specifier is deprecated.
14976 // In C++17, it is not allowed, but we tolerate it as an extension.
14977 if (getLangOpts().CPlusPlus11
) {
14978 Diag(DS
.getStorageClassSpecLoc(),
14979 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
14980 : diag::warn_deprecated_register
)
14981 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
14983 } else if (getLangOpts().CPlusPlus
&&
14984 DS
.getStorageClassSpec() == DeclSpec::SCS_auto
) {
14986 } else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
) {
14987 Diag(DS
.getStorageClassSpecLoc(),
14988 diag::err_invalid_storage_class_in_func_decl
);
14989 D
.getMutableDeclSpec().ClearStorageClassSpecs();
14992 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
14993 Diag(DS
.getThreadStorageClassSpecLoc(), diag::err_invalid_thread
)
14994 << DeclSpec::getSpecifierName(TSCS
);
14995 if (DS
.isInlineSpecified())
14996 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
14997 << getLangOpts().CPlusPlus17
;
14998 if (DS
.hasConstexprSpecifier())
14999 Diag(DS
.getConstexprSpecLoc(), diag::err_invalid_constexpr
)
15000 << 0 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
15002 DiagnoseFunctionSpecifiers(DS
);
15004 CheckFunctionOrTemplateParamDeclarator(S
, D
);
15006 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
15007 QualType parmDeclType
= TInfo
->getType();
15009 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15010 IdentifierInfo
*II
= D
.getIdentifier();
15012 LookupResult
R(*this, II
, D
.getIdentifierLoc(), LookupOrdinaryName
,
15013 ForVisibleRedeclaration
);
15016 NamedDecl
*PrevDecl
= *R
.begin();
15017 if (R
.isSingleResult() && PrevDecl
->isTemplateParameter()) {
15018 // Maybe we will complain about the shadowed template parameter.
15019 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
15020 // Just pretend that we didn't see the previous declaration.
15021 PrevDecl
= nullptr;
15023 if (PrevDecl
&& S
->isDeclScope(PrevDecl
)) {
15024 Diag(D
.getIdentifierLoc(), diag::err_param_redefinition
) << II
;
15025 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
15026 // Recover by removing the name
15028 D
.SetIdentifier(nullptr, D
.getIdentifierLoc());
15029 D
.setInvalidType(true);
15034 // Temporarily put parameter variables in the translation unit, not
15035 // the enclosing context. This prevents them from accidentally
15036 // looking like class members in C++.
15038 CheckParameter(Context
.getTranslationUnitDecl(), D
.getBeginLoc(),
15039 D
.getIdentifierLoc(), II
, parmDeclType
, TInfo
, SC
);
15041 if (D
.isInvalidType())
15042 New
->setInvalidDecl();
15044 CheckExplicitObjectParameter(*this, New
, ExplicitThisLoc
);
15046 assert(S
->isFunctionPrototypeScope());
15047 assert(S
->getFunctionPrototypeDepth() >= 1);
15048 New
->setScopeInfo(S
->getFunctionPrototypeDepth() - 1,
15049 S
->getNextFunctionPrototypeIndex());
15051 // Add the parameter declaration into this scope.
15054 IdResolver
.AddDecl(New
);
15056 ProcessDeclAttributes(S
, New
, D
);
15058 if (D
.getDeclSpec().isModulePrivateSpecified())
15059 Diag(New
->getLocation(), diag::err_module_private_local
)
15060 << 1 << New
<< SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
15061 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
15063 if (New
->hasAttr
<BlocksAttr
>()) {
15064 Diag(New
->getLocation(), diag::err_block_on_nonlocal
);
15067 if (getLangOpts().OpenCL
)
15068 deduceOpenCLAddressSpace(New
);
15073 /// Synthesizes a variable for a parameter arising from a
15075 ParmVarDecl
*Sema::BuildParmVarDeclForTypedef(DeclContext
*DC
,
15076 SourceLocation Loc
,
15078 /* FIXME: setting StartLoc == Loc.
15079 Would it be worth to modify callers so as to provide proper source
15080 location for the unnamed parameters, embedding the parameter's type? */
15081 ParmVarDecl
*Param
= ParmVarDecl::Create(Context
, DC
, Loc
, Loc
, nullptr,
15082 T
, Context
.getTrivialTypeSourceInfo(T
, Loc
),
15084 Param
->setImplicit();
15088 void Sema::DiagnoseUnusedParameters(ArrayRef
<ParmVarDecl
*> Parameters
) {
15089 // Don't diagnose unused-parameter errors in template instantiations; we
15090 // will already have done so in the template itself.
15091 if (inTemplateInstantiation())
15094 for (const ParmVarDecl
*Parameter
: Parameters
) {
15095 if (!Parameter
->isReferenced() && Parameter
->getDeclName() &&
15096 !Parameter
->hasAttr
<UnusedAttr
>() &&
15097 !Parameter
->getIdentifier()->isPlaceholder()) {
15098 Diag(Parameter
->getLocation(), diag::warn_unused_parameter
)
15099 << Parameter
->getDeclName();
15104 void Sema::DiagnoseSizeOfParametersAndReturnValue(
15105 ArrayRef
<ParmVarDecl
*> Parameters
, QualType ReturnTy
, NamedDecl
*D
) {
15106 if (LangOpts
.NumLargeByValueCopy
== 0) // No check.
15109 // Warn if the return value is pass-by-value and larger than the specified
15111 if (!ReturnTy
->isDependentType() && ReturnTy
.isPODType(Context
)) {
15112 unsigned Size
= Context
.getTypeSizeInChars(ReturnTy
).getQuantity();
15113 if (Size
> LangOpts
.NumLargeByValueCopy
)
15114 Diag(D
->getLocation(), diag::warn_return_value_size
) << D
<< Size
;
15117 // Warn if any parameter is pass-by-value and larger than the specified
15119 for (const ParmVarDecl
*Parameter
: Parameters
) {
15120 QualType T
= Parameter
->getType();
15121 if (T
->isDependentType() || !T
.isPODType(Context
))
15123 unsigned Size
= Context
.getTypeSizeInChars(T
).getQuantity();
15124 if (Size
> LangOpts
.NumLargeByValueCopy
)
15125 Diag(Parameter
->getLocation(), diag::warn_parameter_size
)
15126 << Parameter
<< Size
;
15130 ParmVarDecl
*Sema::CheckParameter(DeclContext
*DC
, SourceLocation StartLoc
,
15131 SourceLocation NameLoc
, IdentifierInfo
*Name
,
15132 QualType T
, TypeSourceInfo
*TSInfo
,
15134 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15135 if (getLangOpts().ObjCAutoRefCount
&&
15136 T
.getObjCLifetime() == Qualifiers::OCL_None
&&
15137 T
->isObjCLifetimeType()) {
15139 Qualifiers::ObjCLifetime lifetime
;
15141 // Special cases for arrays:
15142 // - if it's const, use __unsafe_unretained
15143 // - otherwise, it's an error
15144 if (T
->isArrayType()) {
15145 if (!T
.isConstQualified()) {
15146 if (DelayedDiagnostics
.shouldDelayDiagnostics())
15147 DelayedDiagnostics
.add(
15148 sema::DelayedDiagnostic::makeForbiddenType(
15149 NameLoc
, diag::err_arc_array_param_no_ownership
, T
, false));
15151 Diag(NameLoc
, diag::err_arc_array_param_no_ownership
)
15152 << TSInfo
->getTypeLoc().getSourceRange();
15154 lifetime
= Qualifiers::OCL_ExplicitNone
;
15156 lifetime
= T
->getObjCARCImplicitLifetime();
15158 T
= Context
.getLifetimeQualifiedType(T
, lifetime
);
15161 ParmVarDecl
*New
= ParmVarDecl::Create(Context
, DC
, StartLoc
, NameLoc
, Name
,
15162 Context
.getAdjustedParameterType(T
),
15163 TSInfo
, SC
, nullptr);
15165 // Make a note if we created a new pack in the scope of a lambda, so that
15166 // we know that references to that pack must also be expanded within the
15168 if (New
->isParameterPack())
15169 if (auto *LSI
= getEnclosingLambda())
15170 LSI
->LocalPacks
.push_back(New
);
15172 if (New
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15173 New
->getType().hasNonTrivialToPrimitiveCopyCUnion())
15174 checkNonTrivialCUnion(New
->getType(), New
->getLocation(),
15175 NTCUC_FunctionParam
, NTCUK_Destruct
|NTCUK_Copy
);
15177 // Parameter declarators cannot be interface types. All ObjC objects are
15178 // passed by reference.
15179 if (T
->isObjCObjectType()) {
15180 SourceLocation TypeEndLoc
=
15181 getLocForEndOfToken(TSInfo
->getTypeLoc().getEndLoc());
15183 diag::err_object_cannot_be_passed_returned_by_value
) << 1 << T
15184 << FixItHint::CreateInsertion(TypeEndLoc
, "*");
15185 T
= Context
.getObjCObjectPointerType(T
);
15189 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15190 // duration shall not be qualified by an address-space qualifier."
15191 // Since all parameters have automatic store duration, they can not have
15192 // an address space.
15193 if (T
.getAddressSpace() != LangAS::Default
&&
15194 // OpenCL allows function arguments declared to be an array of a type
15195 // to be qualified with an address space.
15196 !(getLangOpts().OpenCL
&&
15197 (T
->isArrayType() || T
.getAddressSpace() == LangAS::opencl_private
)) &&
15198 // WebAssembly allows reference types as parameters. Funcref in particular
15199 // lives in a different address space.
15200 !(T
->isFunctionPointerType() &&
15201 T
.getAddressSpace() == LangAS::wasm_funcref
)) {
15202 Diag(NameLoc
, diag::err_arg_with_address_space
);
15203 New
->setInvalidDecl();
15206 // PPC MMA non-pointer types are not allowed as function argument types.
15207 if (Context
.getTargetInfo().getTriple().isPPC64() &&
15208 CheckPPCMMAType(New
->getOriginalType(), New
->getLocation())) {
15209 New
->setInvalidDecl();
15215 void Sema::ActOnFinishKNRParamDeclarations(Scope
*S
, Declarator
&D
,
15216 SourceLocation LocAfterDecls
) {
15217 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
15219 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15220 // in the declaration list shall have at least one declarator, those
15221 // declarators shall only declare identifiers from the identifier list, and
15222 // every identifier in the identifier list shall be declared.
15224 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15225 // identifiers it names shall be declared in the declaration list."
15227 // This is why we only diagnose in C99 and later. Note, the other conditions
15228 // listed are checked elsewhere.
15229 if (!FTI
.hasPrototype
) {
15230 for (int i
= FTI
.NumParams
; i
!= 0; /* decrement in loop */) {
15232 if (FTI
.Params
[i
].Param
== nullptr) {
15233 if (getLangOpts().C99
) {
15234 SmallString
<256> Code
;
15235 llvm::raw_svector_ostream(Code
)
15236 << " int " << FTI
.Params
[i
].Ident
->getName() << ";\n";
15237 Diag(FTI
.Params
[i
].IdentLoc
, diag::ext_param_not_declared
)
15238 << FTI
.Params
[i
].Ident
15239 << FixItHint::CreateInsertion(LocAfterDecls
, Code
);
15242 // Implicitly declare the argument as type 'int' for lack of a better
15244 AttributeFactory attrs
;
15245 DeclSpec
DS(attrs
);
15246 const char* PrevSpec
; // unused
15247 unsigned DiagID
; // unused
15248 DS
.SetTypeSpecType(DeclSpec::TST_int
, FTI
.Params
[i
].IdentLoc
, PrevSpec
,
15249 DiagID
, Context
.getPrintingPolicy());
15250 // Use the identifier location for the type source range.
15251 DS
.SetRangeStart(FTI
.Params
[i
].IdentLoc
);
15252 DS
.SetRangeEnd(FTI
.Params
[i
].IdentLoc
);
15253 Declarator
ParamD(DS
, ParsedAttributesView::none(),
15254 DeclaratorContext::KNRTypeList
);
15255 ParamD
.SetIdentifier(FTI
.Params
[i
].Ident
, FTI
.Params
[i
].IdentLoc
);
15256 FTI
.Params
[i
].Param
= ActOnParamDeclarator(S
, ParamD
);
15263 Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Declarator
&D
,
15264 MultiTemplateParamsArg TemplateParameterLists
,
15265 SkipBodyInfo
*SkipBody
, FnBodyKind BodyKind
) {
15266 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15267 assert(D
.isFunctionDeclarator() && "Not a function declarator!");
15268 Scope
*ParentScope
= FnBodyScope
->getParent();
15270 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15271 // we define a non-templated function definition, we will create a declaration
15272 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15273 // The base function declaration will have the equivalent of an `omp declare
15274 // variant` annotation which specifies the mangled definition as a
15275 // specialization function under the OpenMP context defined as part of the
15276 // `omp begin declare variant`.
15277 SmallVector
<FunctionDecl
*, 4> Bases
;
15278 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
15279 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15280 ParentScope
, D
, TemplateParameterLists
, Bases
);
15282 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
15283 Decl
*DP
= HandleDeclarator(ParentScope
, D
, TemplateParameterLists
);
15284 Decl
*Dcl
= ActOnStartOfFunctionDef(FnBodyScope
, DP
, SkipBody
, BodyKind
);
15286 if (!Bases
.empty())
15287 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
15292 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl
*D
) {
15293 Consumer
.HandleInlineFunctionDefinition(D
);
15296 static bool FindPossiblePrototype(const FunctionDecl
*FD
,
15297 const FunctionDecl
*&PossiblePrototype
) {
15298 for (const FunctionDecl
*Prev
= FD
->getPreviousDecl(); Prev
;
15299 Prev
= Prev
->getPreviousDecl()) {
15300 // Ignore any declarations that occur in function or method
15301 // scope, because they aren't visible from the header.
15302 if (Prev
->getLexicalDeclContext()->isFunctionOrMethod())
15305 PossiblePrototype
= Prev
;
15306 return Prev
->getType()->isFunctionProtoType();
15312 ShouldWarnAboutMissingPrototype(const FunctionDecl
*FD
,
15313 const FunctionDecl
*&PossiblePrototype
) {
15314 // Don't warn about invalid declarations.
15315 if (FD
->isInvalidDecl())
15318 // Or declarations that aren't global.
15319 if (!FD
->isGlobal())
15322 // Don't warn about C++ member functions.
15323 if (isa
<CXXMethodDecl
>(FD
))
15326 // Don't warn about 'main'.
15327 if (isa
<TranslationUnitDecl
>(FD
->getDeclContext()->getRedeclContext()))
15328 if (IdentifierInfo
*II
= FD
->getIdentifier())
15329 if (II
->isStr("main") || II
->isStr("efi_main"))
15332 // Don't warn about inline functions.
15333 if (FD
->isInlined())
15336 // Don't warn about function templates.
15337 if (FD
->getDescribedFunctionTemplate())
15340 // Don't warn about function template specializations.
15341 if (FD
->isFunctionTemplateSpecialization())
15344 // Don't warn for OpenCL kernels.
15345 if (FD
->hasAttr
<OpenCLKernelAttr
>())
15348 // Don't warn on explicitly deleted functions.
15349 if (FD
->isDeleted())
15352 // Don't warn on implicitly local functions (such as having local-typed
15354 if (!FD
->isExternallyVisible())
15357 // If we were able to find a potential prototype, don't warn.
15358 if (FindPossiblePrototype(FD
, PossiblePrototype
))
15365 Sema::CheckForFunctionRedefinition(FunctionDecl
*FD
,
15366 const FunctionDecl
*EffectiveDefinition
,
15367 SkipBodyInfo
*SkipBody
) {
15368 const FunctionDecl
*Definition
= EffectiveDefinition
;
15370 !FD
->isDefined(Definition
, /*CheckForPendingFriendDefinition*/ true))
15373 if (Definition
->getFriendObjectKind() != Decl::FOK_None
) {
15374 if (FunctionDecl
*OrigDef
= Definition
->getInstantiatedFromMemberFunction()) {
15375 if (FunctionDecl
*OrigFD
= FD
->getInstantiatedFromMemberFunction()) {
15376 // A merged copy of the same function, instantiated as a member of
15377 // the same class, is OK.
15378 if (declaresSameEntity(OrigFD
, OrigDef
) &&
15379 declaresSameEntity(cast
<Decl
>(Definition
->getLexicalDeclContext()),
15380 cast
<Decl
>(FD
->getLexicalDeclContext())))
15386 if (canRedefineFunction(Definition
, getLangOpts()))
15389 // Don't emit an error when this is redefinition of a typo-corrected
15391 if (TypoCorrectedFunctionDefinitions
.count(Definition
))
15394 // If we don't have a visible definition of the function, and it's inline or
15395 // a template, skip the new definition.
15396 if (SkipBody
&& !hasVisibleDefinition(Definition
) &&
15397 (Definition
->getFormalLinkage() == InternalLinkage
||
15398 Definition
->isInlined() ||
15399 Definition
->getDescribedFunctionTemplate() ||
15400 Definition
->getNumTemplateParameterLists())) {
15401 SkipBody
->ShouldSkip
= true;
15402 SkipBody
->Previous
= const_cast<FunctionDecl
*>(Definition
);
15403 if (auto *TD
= Definition
->getDescribedFunctionTemplate())
15404 makeMergedDefinitionVisible(TD
);
15405 makeMergedDefinitionVisible(const_cast<FunctionDecl
*>(Definition
));
15409 if (getLangOpts().GNUMode
&& Definition
->isInlineSpecified() &&
15410 Definition
->getStorageClass() == SC_Extern
)
15411 Diag(FD
->getLocation(), diag::err_redefinition_extern_inline
)
15412 << FD
<< getLangOpts().CPlusPlus
;
15414 Diag(FD
->getLocation(), diag::err_redefinition
) << FD
;
15416 Diag(Definition
->getLocation(), diag::note_previous_definition
);
15417 FD
->setInvalidDecl();
15420 LambdaScopeInfo
*Sema::RebuildLambdaScopeInfo(CXXMethodDecl
*CallOperator
) {
15421 CXXRecordDecl
*LambdaClass
= CallOperator
->getParent();
15423 LambdaScopeInfo
*LSI
= PushLambdaScope();
15424 LSI
->CallOperator
= CallOperator
;
15425 LSI
->Lambda
= LambdaClass
;
15426 LSI
->ReturnType
= CallOperator
->getReturnType();
15427 // This function in calls in situation where the context of the call operator
15428 // is not entered, so we set AfterParameterList to false, so that
15429 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15430 LSI
->AfterParameterList
= false;
15431 const LambdaCaptureDefault LCD
= LambdaClass
->getLambdaCaptureDefault();
15433 if (LCD
== LCD_None
)
15434 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_None
;
15435 else if (LCD
== LCD_ByCopy
)
15436 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByval
;
15437 else if (LCD
== LCD_ByRef
)
15438 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByref
;
15439 DeclarationNameInfo DNI
= CallOperator
->getNameInfo();
15441 LSI
->IntroducerRange
= DNI
.getCXXOperatorNameRange();
15442 LSI
->Mutable
= !CallOperator
->isConst();
15443 if (CallOperator
->isExplicitObjectMemberFunction())
15444 LSI
->ExplicitObjectParameter
= CallOperator
->getParamDecl(0);
15446 // Add the captures to the LSI so they can be noted as already
15447 // captured within tryCaptureVar.
15448 auto I
= LambdaClass
->field_begin();
15449 for (const auto &C
: LambdaClass
->captures()) {
15450 if (C
.capturesVariable()) {
15451 ValueDecl
*VD
= C
.getCapturedVar();
15452 if (VD
->isInitCapture())
15453 CurrentInstantiationScope
->InstantiatedLocal(VD
, VD
);
15454 const bool ByRef
= C
.getCaptureKind() == LCK_ByRef
;
15455 LSI
->addCapture(VD
, /*IsBlock*/false, ByRef
,
15456 /*RefersToEnclosingVariableOrCapture*/true, C
.getLocation(),
15457 /*EllipsisLoc*/C
.isPackExpansion()
15458 ? C
.getEllipsisLoc() : SourceLocation(),
15459 I
->getType(), /*Invalid*/false);
15461 } else if (C
.capturesThis()) {
15462 LSI
->addThisCapture(/*Nested*/ false, C
.getLocation(), I
->getType(),
15463 C
.getCaptureKind() == LCK_StarThis
);
15465 LSI
->addVLATypeCapture(C
.getLocation(), I
->getCapturedVLAType(),
15473 Decl
*Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Decl
*D
,
15474 SkipBodyInfo
*SkipBody
,
15475 FnBodyKind BodyKind
) {
15477 // Parsing the function declaration failed in some way. Push on a fake scope
15478 // anyway so we can try to parse the function body.
15479 PushFunctionScope();
15480 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
15484 FunctionDecl
*FD
= nullptr;
15486 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
))
15487 FD
= FunTmpl
->getTemplatedDecl();
15489 FD
= cast
<FunctionDecl
>(D
);
15491 // Do not push if it is a lambda because one is already pushed when building
15492 // the lambda in ActOnStartOfLambdaDefinition().
15493 if (!isLambdaCallOperator(FD
))
15494 // [expr.const]/p14.1
15495 // An expression or conversion is in an immediate function context if it is
15496 // potentially evaluated and either: its innermost enclosing non-block scope
15497 // is a function parameter scope of an immediate function.
15498 PushExpressionEvaluationContext(
15499 FD
->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15500 : ExprEvalContexts
.back().Context
);
15502 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15503 // context is nested in an immediate function context, so smaller contexts
15504 // that appear inside immediate functions (like variable initializers) are
15505 // considered to be inside an immediate function context even though by
15506 // themselves they are not immediate function contexts. But when a new
15507 // function is entered, we need to reset this tracking, since the entered
15508 // function might be not an immediate function.
15509 ExprEvalContexts
.back().InImmediateFunctionContext
= FD
->isConsteval();
15510 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
15511 getLangOpts().CPlusPlus20
&& FD
->isImmediateEscalating();
15513 // Check for defining attributes before the check for redefinition.
15514 if (const auto *Attr
= FD
->getAttr
<AliasAttr
>()) {
15515 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 0;
15516 FD
->dropAttr
<AliasAttr
>();
15517 FD
->setInvalidDecl();
15519 if (const auto *Attr
= FD
->getAttr
<IFuncAttr
>()) {
15520 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 1;
15521 FD
->dropAttr
<IFuncAttr
>();
15522 FD
->setInvalidDecl();
15524 if (const auto *Attr
= FD
->getAttr
<TargetVersionAttr
>()) {
15525 if (!Context
.getTargetInfo().hasFeature("fmv") &&
15526 !Attr
->isDefaultVersion()) {
15527 // If function multi versioning disabled skip parsing function body
15528 // defined with non-default target_version attribute
15530 SkipBody
->ShouldSkip
= true;
15535 if (auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
15536 if (Ctor
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
15537 Ctor
->isDefaultConstructor() &&
15538 Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
15539 // If this is an MS ABI dllexport default constructor, instantiate any
15540 // default arguments.
15541 InstantiateDefaultCtorDefaultArgs(Ctor
);
15545 // See if this is a redefinition. If 'will have body' (or similar) is already
15546 // set, then these checks were already performed when it was set.
15547 if (!FD
->willHaveBody() && !FD
->isLateTemplateParsed() &&
15548 !FD
->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15549 CheckForFunctionRedefinition(FD
, nullptr, SkipBody
);
15551 // If we're skipping the body, we're done. Don't enter the scope.
15552 if (SkipBody
&& SkipBody
->ShouldSkip
)
15556 // Mark this function as "will have a body eventually". This lets users to
15557 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15559 FD
->setWillHaveBody();
15561 // If we are instantiating a generic lambda call operator, push
15562 // a LambdaScopeInfo onto the function stack. But use the information
15563 // that's already been calculated (ActOnLambdaExpr) to prime the current
15564 // LambdaScopeInfo.
15565 // When the template operator is being specialized, the LambdaScopeInfo,
15566 // has to be properly restored so that tryCaptureVariable doesn't try
15567 // and capture any new variables. In addition when calculating potential
15568 // captures during transformation of nested lambdas, it is necessary to
15569 // have the LSI properly restored.
15570 if (isGenericLambdaCallOperatorSpecialization(FD
)) {
15571 assert(inTemplateInstantiation() &&
15572 "There should be an active template instantiation on the stack "
15573 "when instantiating a generic lambda!");
15574 RebuildLambdaScopeInfo(cast
<CXXMethodDecl
>(D
));
15576 // Enter a new function scope
15577 PushFunctionScope();
15580 // Builtin functions cannot be defined.
15581 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
15582 if (!Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
) &&
15583 !Context
.BuiltinInfo
.isPredefinedRuntimeFunction(BuiltinID
)) {
15584 Diag(FD
->getLocation(), diag::err_builtin_definition
) << FD
;
15585 FD
->setInvalidDecl();
15589 // The return type of a function definition must be complete (C99 6.9.1p3).
15590 // C++23 [dcl.fct.def.general]/p2
15591 // The type of [...] the return for a function definition
15592 // shall not be a (possibly cv-qualified) class type that is incomplete
15593 // or abstract within the function body unless the function is deleted.
15594 QualType ResultType
= FD
->getReturnType();
15595 if (!ResultType
->isDependentType() && !ResultType
->isVoidType() &&
15596 !FD
->isInvalidDecl() && BodyKind
!= FnBodyKind::Delete
&&
15597 (RequireCompleteType(FD
->getLocation(), ResultType
,
15598 diag::err_func_def_incomplete_result
) ||
15599 RequireNonAbstractType(FD
->getLocation(), FD
->getReturnType(),
15600 diag::err_abstract_type_in_decl
,
15601 AbstractReturnType
)))
15602 FD
->setInvalidDecl();
15605 PushDeclContext(FnBodyScope
, FD
);
15607 // Check the validity of our function parameters
15608 if (BodyKind
!= FnBodyKind::Delete
)
15609 CheckParmsForFunctionDef(FD
->parameters(),
15610 /*CheckParameterNames=*/true);
15612 // Add non-parameter declarations already in the function to the current
15615 for (Decl
*NPD
: FD
->decls()) {
15616 auto *NonParmDecl
= dyn_cast
<NamedDecl
>(NPD
);
15619 assert(!isa
<ParmVarDecl
>(NonParmDecl
) &&
15620 "parameters should not be in newly created FD yet");
15622 // If the decl has a name, make it accessible in the current scope.
15623 if (NonParmDecl
->getDeclName())
15624 PushOnScopeChains(NonParmDecl
, FnBodyScope
, /*AddToContext=*/false);
15626 // Similarly, dive into enums and fish their constants out, making them
15627 // accessible in this scope.
15628 if (auto *ED
= dyn_cast
<EnumDecl
>(NonParmDecl
)) {
15629 for (auto *EI
: ED
->enumerators())
15630 PushOnScopeChains(EI
, FnBodyScope
, /*AddToContext=*/false);
15635 // Introduce our parameters into the function scope
15636 for (auto *Param
: FD
->parameters()) {
15637 Param
->setOwningFunction(FD
);
15639 // If this has an identifier, add it to the scope stack.
15640 if (Param
->getIdentifier() && FnBodyScope
) {
15641 CheckShadow(FnBodyScope
, Param
);
15643 PushOnScopeChains(Param
, FnBodyScope
);
15647 // C++ [module.import/6] external definitions are not permitted in header
15648 // units. Deleted and Defaulted functions are implicitly inline (but the
15649 // inline state is not set at this point, so check the BodyKind explicitly).
15650 // FIXME: Consider an alternate location for the test where the inlined()
15651 // state is complete.
15652 if (getLangOpts().CPlusPlusModules
&& currentModuleIsHeaderUnit() &&
15653 !FD
->isInvalidDecl() && !FD
->isInlined() &&
15654 BodyKind
!= FnBodyKind::Delete
&& BodyKind
!= FnBodyKind::Default
&&
15655 FD
->getFormalLinkage() == Linkage::ExternalLinkage
&&
15656 !FD
->isTemplated() && !FD
->isTemplateInstantiation()) {
15657 assert(FD
->isThisDeclarationADefinition());
15658 Diag(FD
->getLocation(), diag::err_extern_def_in_header_unit
);
15659 FD
->setInvalidDecl();
15662 // Ensure that the function's exception specification is instantiated.
15663 if (const FunctionProtoType
*FPT
= FD
->getType()->getAs
<FunctionProtoType
>())
15664 ResolveExceptionSpec(D
->getLocation(), FPT
);
15666 // dllimport cannot be applied to non-inline function definitions.
15667 if (FD
->hasAttr
<DLLImportAttr
>() && !FD
->isInlined() &&
15668 !FD
->isTemplateInstantiation()) {
15669 assert(!FD
->hasAttr
<DLLExportAttr
>());
15670 Diag(FD
->getLocation(), diag::err_attribute_dllimport_function_definition
);
15671 FD
->setInvalidDecl();
15674 // We want to attach documentation to original Decl (which might be
15675 // a function template).
15676 ActOnDocumentableDecl(D
);
15677 if (getCurLexicalContext()->isObjCContainer() &&
15678 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl
&&
15679 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation
)
15680 Diag(FD
->getLocation(), diag::warn_function_def_in_objc_container
);
15685 /// Given the set of return statements within a function body,
15686 /// compute the variables that are subject to the named return value
15689 /// Each of the variables that is subject to the named return value
15690 /// optimization will be marked as NRVO variables in the AST, and any
15691 /// return statement that has a marked NRVO variable as its NRVO candidate can
15692 /// use the named return value optimization.
15694 /// This function applies a very simplistic algorithm for NRVO: if every return
15695 /// statement in the scope of a variable has the same NRVO candidate, that
15696 /// candidate is an NRVO variable.
15697 void Sema::computeNRVO(Stmt
*Body
, FunctionScopeInfo
*Scope
) {
15698 ReturnStmt
**Returns
= Scope
->Returns
.data();
15700 for (unsigned I
= 0, E
= Scope
->Returns
.size(); I
!= E
; ++I
) {
15701 if (const VarDecl
*NRVOCandidate
= Returns
[I
]->getNRVOCandidate()) {
15702 if (!NRVOCandidate
->isNRVOVariable())
15703 Returns
[I
]->setNRVOCandidate(nullptr);
15708 bool Sema::canDelayFunctionBody(const Declarator
&D
) {
15709 // We can't delay parsing the body of a constexpr function template (yet).
15710 if (D
.getDeclSpec().hasConstexprSpecifier())
15713 // We can't delay parsing the body of a function template with a deduced
15714 // return type (yet).
15715 if (D
.getDeclSpec().hasAutoTypeSpec()) {
15716 // If the placeholder introduces a non-deduced trailing return type,
15717 // we can still delay parsing it.
15718 if (D
.getNumTypeObjects()) {
15719 const auto &Outer
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
15720 if (Outer
.Kind
== DeclaratorChunk::Function
&&
15721 Outer
.Fun
.hasTrailingReturnType()) {
15722 QualType Ty
= GetTypeFromParser(Outer
.Fun
.getTrailingReturnType());
15723 return Ty
.isNull() || !Ty
->isUndeducedType();
15732 bool Sema::canSkipFunctionBody(Decl
*D
) {
15733 // We cannot skip the body of a function (or function template) which is
15734 // constexpr, since we may need to evaluate its body in order to parse the
15735 // rest of the file.
15736 // We cannot skip the body of a function with an undeduced return type,
15737 // because any callers of that function need to know the type.
15738 if (const FunctionDecl
*FD
= D
->getAsFunction()) {
15739 if (FD
->isConstexpr())
15741 // We can't simply call Type::isUndeducedType here, because inside template
15742 // auto can be deduced to a dependent type, which is not considered
15744 if (FD
->getReturnType()->getContainedDeducedType())
15747 return Consumer
.shouldSkipFunctionBody(D
);
15750 Decl
*Sema::ActOnSkippedFunctionBody(Decl
*Decl
) {
15753 if (FunctionDecl
*FD
= Decl
->getAsFunction())
15754 FD
->setHasSkippedBody();
15755 else if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(Decl
))
15756 MD
->setHasSkippedBody();
15760 Decl
*Sema::ActOnFinishFunctionBody(Decl
*D
, Stmt
*BodyArg
) {
15761 return ActOnFinishFunctionBody(D
, BodyArg
, false);
15764 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15766 class ExitFunctionBodyRAII
{
15768 ExitFunctionBodyRAII(Sema
&S
, bool IsLambda
) : S(S
), IsLambda(IsLambda
) {}
15769 ~ExitFunctionBodyRAII() {
15771 S
.PopExpressionEvaluationContext();
15776 bool IsLambda
= false;
15779 static void diagnoseImplicitlyRetainedSelf(Sema
&S
) {
15780 llvm::DenseMap
<const BlockDecl
*, bool> EscapeInfo
;
15782 auto IsOrNestedInEscapingBlock
= [&](const BlockDecl
*BD
) {
15783 if (EscapeInfo
.count(BD
))
15784 return EscapeInfo
[BD
];
15787 const BlockDecl
*CurBD
= BD
;
15790 R
= !CurBD
->doesNotEscape();
15793 CurBD
= CurBD
->getParent()->getInnermostBlockDecl();
15796 return EscapeInfo
[BD
] = R
;
15799 // If the location where 'self' is implicitly retained is inside a escaping
15800 // block, emit a diagnostic.
15801 for (const std::pair
<SourceLocation
, const BlockDecl
*> &P
:
15802 S
.ImplicitlyRetainedSelfLocs
)
15803 if (IsOrNestedInEscapingBlock(P
.second
))
15804 S
.Diag(P
.first
, diag::warn_implicitly_retains_self
)
15805 << FixItHint::CreateInsertion(P
.first
, "self->");
15808 Decl
*Sema::ActOnFinishFunctionBody(Decl
*dcl
, Stmt
*Body
,
15809 bool IsInstantiation
) {
15810 FunctionScopeInfo
*FSI
= getCurFunction();
15811 FunctionDecl
*FD
= dcl
? dcl
->getAsFunction() : nullptr;
15813 if (FSI
->UsesFPIntrin
&& FD
&& !FD
->hasAttr
<StrictFPAttr
>())
15814 FD
->addAttr(StrictFPAttr::CreateImplicit(Context
));
15816 sema::AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
15817 sema::AnalysisBasedWarnings::Policy
*ActivePolicy
= nullptr;
15819 if (getLangOpts().Coroutines
&& FSI
->isCoroutine())
15820 CheckCompletedCoroutineBody(FD
, Body
);
15823 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15824 // one is already popped when finishing the lambda in BuildLambdaExpr().
15825 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15826 ExitFunctionBodyRAII
ExitRAII(*this, isLambdaCallOperator(FD
));
15829 FD
->setWillHaveBody(false);
15830 CheckImmediateEscalatingFunctionDefinition(FD
, FSI
);
15832 if (getLangOpts().CPlusPlus14
) {
15833 if (!FD
->isInvalidDecl() && Body
&& !FD
->isDependentContext() &&
15834 FD
->getReturnType()->isUndeducedType()) {
15835 // For a function with a deduced result type to return void,
15836 // the result type as written must be 'auto' or 'decltype(auto)',
15837 // possibly cv-qualified or constrained, but not ref-qualified.
15838 if (!FD
->getReturnType()->getAs
<AutoType
>()) {
15839 Diag(dcl
->getLocation(), diag::err_auto_fn_no_return_but_not_auto
)
15840 << FD
->getReturnType();
15841 FD
->setInvalidDecl();
15843 // Falling off the end of the function is the same as 'return;'.
15844 Expr
*Dummy
= nullptr;
15845 if (DeduceFunctionTypeFromReturnExpr(
15846 FD
, dcl
->getLocation(), Dummy
,
15847 FD
->getReturnType()->getAs
<AutoType
>()))
15848 FD
->setInvalidDecl();
15851 } else if (getLangOpts().CPlusPlus11
&& isLambdaCallOperator(FD
)) {
15852 // In C++11, we don't use 'auto' deduction rules for lambda call
15853 // operators because we don't support return type deduction.
15854 auto *LSI
= getCurLambda();
15855 if (LSI
->HasImplicitReturnType
) {
15856 deduceClosureReturnType(*LSI
);
15858 // C++11 [expr.prim.lambda]p4:
15859 // [...] if there are no return statements in the compound-statement
15860 // [the deduced type is] the type void
15862 LSI
->ReturnType
.isNull() ? Context
.VoidTy
: LSI
->ReturnType
;
15864 // Update the return type to the deduced type.
15865 const auto *Proto
= FD
->getType()->castAs
<FunctionProtoType
>();
15866 FD
->setType(Context
.getFunctionType(RetType
, Proto
->getParamTypes(),
15867 Proto
->getExtProtoInfo()));
15871 // If the function implicitly returns zero (like 'main') or is naked,
15872 // don't complain about missing return statements.
15873 if (FD
->hasImplicitReturnZero() || FD
->hasAttr
<NakedAttr
>())
15874 WP
.disableCheckFallThrough();
15876 // MSVC permits the use of pure specifier (=0) on function definition,
15877 // defined at class scope, warn about this non-standard construct.
15878 if (getLangOpts().MicrosoftExt
&& FD
->isPure() && !FD
->isOutOfLine())
15879 Diag(FD
->getLocation(), diag::ext_pure_function_definition
);
15881 if (!FD
->isInvalidDecl()) {
15882 // Don't diagnose unused parameters of defaulted, deleted or naked
15884 if (!FD
->isDeleted() && !FD
->isDefaulted() && !FD
->hasSkippedBody() &&
15885 !FD
->hasAttr
<NakedAttr
>())
15886 DiagnoseUnusedParameters(FD
->parameters());
15887 DiagnoseSizeOfParametersAndReturnValue(FD
->parameters(),
15888 FD
->getReturnType(), FD
);
15890 // If this is a structor, we need a vtable.
15891 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(FD
))
15892 MarkVTableUsed(FD
->getLocation(), Constructor
->getParent());
15893 else if (CXXDestructorDecl
*Destructor
=
15894 dyn_cast
<CXXDestructorDecl
>(FD
))
15895 MarkVTableUsed(FD
->getLocation(), Destructor
->getParent());
15897 // Try to apply the named return value optimization. We have to check
15898 // if we can do this here because lambdas keep return statements around
15899 // to deduce an implicit return type.
15900 if (FD
->getReturnType()->isRecordType() &&
15901 (!getLangOpts().CPlusPlus
|| !FD
->isDependentContext()))
15902 computeNRVO(Body
, FSI
);
15905 // GNU warning -Wmissing-prototypes:
15906 // Warn if a global function is defined without a previous
15907 // prototype declaration. This warning is issued even if the
15908 // definition itself provides a prototype. The aim is to detect
15909 // global functions that fail to be declared in header files.
15910 const FunctionDecl
*PossiblePrototype
= nullptr;
15911 if (ShouldWarnAboutMissingPrototype(FD
, PossiblePrototype
)) {
15912 Diag(FD
->getLocation(), diag::warn_missing_prototype
) << FD
;
15914 if (PossiblePrototype
) {
15915 // We found a declaration that is not a prototype,
15916 // but that could be a zero-parameter prototype
15917 if (TypeSourceInfo
*TI
= PossiblePrototype
->getTypeSourceInfo()) {
15918 TypeLoc TL
= TI
->getTypeLoc();
15919 if (FunctionNoProtoTypeLoc FTL
= TL
.getAs
<FunctionNoProtoTypeLoc
>())
15920 Diag(PossiblePrototype
->getLocation(),
15921 diag::note_declaration_not_a_prototype
)
15922 << (FD
->getNumParams() != 0)
15923 << (FD
->getNumParams() == 0 ? FixItHint::CreateInsertion(
15924 FTL
.getRParenLoc(), "void")
15928 // Returns true if the token beginning at this Loc is `const`.
15929 auto isLocAtConst
= [&](SourceLocation Loc
, const SourceManager
&SM
,
15930 const LangOptions
&LangOpts
) {
15931 std::pair
<FileID
, unsigned> LocInfo
= SM
.getDecomposedLoc(Loc
);
15932 if (LocInfo
.first
.isInvalid())
15935 bool Invalid
= false;
15936 StringRef Buffer
= SM
.getBufferData(LocInfo
.first
, &Invalid
);
15940 if (LocInfo
.second
> Buffer
.size())
15943 const char *LexStart
= Buffer
.data() + LocInfo
.second
;
15944 StringRef
StartTok(LexStart
, Buffer
.size() - LocInfo
.second
);
15946 return StartTok
.consume_front("const") &&
15947 (StartTok
.empty() || isWhitespace(StartTok
[0]) ||
15948 StartTok
.startswith("/*") || StartTok
.startswith("//"));
15951 auto findBeginLoc
= [&]() {
15952 // If the return type has `const` qualifier, we want to insert
15953 // `static` before `const` (and not before the typename).
15954 if ((FD
->getReturnType()->isAnyPointerType() &&
15955 FD
->getReturnType()->getPointeeType().isConstQualified()) ||
15956 FD
->getReturnType().isConstQualified()) {
15957 // But only do this if we can determine where the `const` is.
15959 if (isLocAtConst(FD
->getBeginLoc(), getSourceManager(),
15962 return FD
->getBeginLoc();
15964 return FD
->getTypeSpecStartLoc();
15966 Diag(FD
->getTypeSpecStartLoc(),
15967 diag::note_static_for_internal_linkage
)
15968 << /* function */ 1
15969 << (FD
->getStorageClass() == SC_None
15970 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15975 // We might not have found a prototype because we didn't wish to warn on
15976 // the lack of a missing prototype. Try again without the checks for
15977 // whether we want to warn on the missing prototype.
15978 if (!PossiblePrototype
)
15979 (void)FindPossiblePrototype(FD
, PossiblePrototype
);
15981 // If the function being defined does not have a prototype, then we may
15982 // need to diagnose it as changing behavior in C23 because we now know
15983 // whether the function accepts arguments or not. This only handles the
15984 // case where the definition has no prototype but does have parameters
15985 // and either there is no previous potential prototype, or the previous
15986 // potential prototype also has no actual prototype. This handles cases
15988 // void f(); void f(a) int a; {}
15989 // void g(a) int a; {}
15990 // See MergeFunctionDecl() for other cases of the behavior change
15991 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15992 // type without a prototype.
15993 if (!FD
->hasWrittenPrototype() && FD
->getNumParams() != 0 &&
15994 (!PossiblePrototype
|| (!PossiblePrototype
->hasWrittenPrototype() &&
15995 !PossiblePrototype
->isImplicit()))) {
15996 // The function definition has parameters, so this will change behavior
15997 // in C23. If there is a possible prototype, it comes before the
15998 // function definition.
15999 // FIXME: The declaration may have already been diagnosed as being
16000 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16001 // there's no way to test for the "changes behavior" condition in
16002 // SemaType.cpp when forming the declaration's function type. So, we do
16003 // this awkward dance instead.
16005 // If we have a possible prototype and it declares a function with a
16006 // prototype, we don't want to diagnose it; if we have a possible
16007 // prototype and it has no prototype, it may have already been
16008 // diagnosed in SemaType.cpp as deprecated depending on whether
16009 // -Wstrict-prototypes is enabled. If we already warned about it being
16010 // deprecated, add a note that it also changes behavior. If we didn't
16011 // warn about it being deprecated (because the diagnostic is not
16012 // enabled), warn now that it is deprecated and changes behavior.
16014 // This K&R C function definition definitely changes behavior in C23,
16016 Diag(FD
->getLocation(), diag::warn_non_prototype_changes_behavior
)
16017 << /*definition*/ 1 << /* not supported in C23 */ 0;
16019 // If we have a possible prototype for the function which is a user-
16020 // visible declaration, we already tested that it has no prototype.
16021 // This will change behavior in C23. This gets a warning rather than a
16022 // note because it's the same behavior-changing problem as with the
16024 if (PossiblePrototype
)
16025 Diag(PossiblePrototype
->getLocation(),
16026 diag::warn_non_prototype_changes_behavior
)
16027 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16028 << /*definition*/ 1;
16031 // Warn on CPUDispatch with an actual body.
16032 if (FD
->isMultiVersion() && FD
->hasAttr
<CPUDispatchAttr
>() && Body
)
16033 if (const auto *CmpndBody
= dyn_cast
<CompoundStmt
>(Body
))
16034 if (!CmpndBody
->body_empty())
16035 Diag(CmpndBody
->body_front()->getBeginLoc(),
16036 diag::warn_dispatch_body_ignored
);
16038 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
16039 const CXXMethodDecl
*KeyFunction
;
16040 if (MD
->isOutOfLine() && (MD
= MD
->getCanonicalDecl()) &&
16042 (KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent())) &&
16043 MD
== KeyFunction
->getCanonicalDecl()) {
16044 // Update the key-function state if necessary for this ABI.
16045 if (FD
->isInlined() &&
16046 !Context
.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16047 Context
.setNonKeyFunction(MD
);
16049 // If the newly-chosen key function is already defined, then we
16050 // need to mark the vtable as used retroactively.
16051 KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent());
16052 const FunctionDecl
*Definition
;
16053 if (KeyFunction
&& KeyFunction
->isDefined(Definition
))
16054 MarkVTableUsed(Definition
->getLocation(), MD
->getParent(), true);
16056 // We just defined they key function; mark the vtable as used.
16057 MarkVTableUsed(FD
->getLocation(), MD
->getParent(), true);
16063 (FD
== getCurFunctionDecl() || getCurLambda()->CallOperator
== FD
) &&
16064 "Function parsing confused");
16065 } else if (ObjCMethodDecl
*MD
= dyn_cast_or_null
<ObjCMethodDecl
>(dcl
)) {
16066 assert(MD
== getCurMethodDecl() && "Method parsing confused");
16068 if (!MD
->isInvalidDecl()) {
16069 DiagnoseSizeOfParametersAndReturnValue(MD
->parameters(),
16070 MD
->getReturnType(), MD
);
16073 computeNRVO(Body
, FSI
);
16075 if (FSI
->ObjCShouldCallSuper
) {
16076 Diag(MD
->getEndLoc(), diag::warn_objc_missing_super_call
)
16077 << MD
->getSelector().getAsString();
16078 FSI
->ObjCShouldCallSuper
= false;
16080 if (FSI
->ObjCWarnForNoDesignatedInitChain
) {
16081 const ObjCMethodDecl
*InitMethod
= nullptr;
16082 bool isDesignated
=
16083 MD
->isDesignatedInitializerForTheInterface(&InitMethod
);
16084 assert(isDesignated
&& InitMethod
);
16085 (void)isDesignated
;
16087 auto superIsNSObject
= [&](const ObjCMethodDecl
*MD
) {
16088 auto IFace
= MD
->getClassInterface();
16091 auto SuperD
= IFace
->getSuperClass();
16094 return SuperD
->getIdentifier() ==
16095 NSAPIObj
->getNSClassId(NSAPI::ClassId_NSObject
);
16097 // Don't issue this warning for unavailable inits or direct subclasses
16099 if (!MD
->isUnavailable() && !superIsNSObject(MD
)) {
16100 Diag(MD
->getLocation(),
16101 diag::warn_objc_designated_init_missing_super_call
);
16102 Diag(InitMethod
->getLocation(),
16103 diag::note_objc_designated_init_marked_here
);
16105 FSI
->ObjCWarnForNoDesignatedInitChain
= false;
16107 if (FSI
->ObjCWarnForNoInitDelegation
) {
16108 // Don't issue this warning for unavaialable inits.
16109 if (!MD
->isUnavailable())
16110 Diag(MD
->getLocation(),
16111 diag::warn_objc_secondary_init_missing_init_call
);
16112 FSI
->ObjCWarnForNoInitDelegation
= false;
16115 diagnoseImplicitlyRetainedSelf(*this);
16117 // Parsing the function declaration failed in some way. Pop the fake scope
16119 PopFunctionScopeInfo(ActivePolicy
, dcl
);
16123 if (Body
&& FSI
->HasPotentialAvailabilityViolations
)
16124 DiagnoseUnguardedAvailabilityViolations(dcl
);
16126 assert(!FSI
->ObjCShouldCallSuper
&&
16127 "This should only be set for ObjC methods, which should have been "
16128 "handled in the block above.");
16130 // Verify and clean out per-function state.
16131 if (Body
&& (!FD
|| !FD
->isDefaulted())) {
16132 // C++ constructors that have function-try-blocks can't have return
16133 // statements in the handlers of that block. (C++ [except.handle]p14)
16135 if (FD
&& isa
<CXXConstructorDecl
>(FD
) && isa
<CXXTryStmt
>(Body
))
16136 DiagnoseReturnInConstructorExceptionHandler(cast
<CXXTryStmt
>(Body
));
16138 // Verify that gotos and switch cases don't jump into scopes illegally.
16139 if (FSI
->NeedsScopeChecking() && !PP
.isCodeCompletionEnabled())
16140 DiagnoseInvalidJumps(Body
);
16142 if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(dcl
)) {
16143 if (!Destructor
->getParent()->isDependentType())
16144 CheckDestructor(Destructor
);
16146 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
16147 Destructor
->getParent());
16150 // If any errors have occurred, clear out any temporaries that may have
16151 // been leftover. This ensures that these temporaries won't be picked up
16152 // for deletion in some later function.
16153 if (hasUncompilableErrorOccurred() ||
16154 hasAnyUnrecoverableErrorsInThisFunction() ||
16155 getDiagnostics().getSuppressAllDiagnostics()) {
16156 DiscardCleanupsInEvaluationContext();
16158 if (!hasUncompilableErrorOccurred() && !isa
<FunctionTemplateDecl
>(dcl
)) {
16159 // Since the body is valid, issue any analysis-based warnings that are
16161 ActivePolicy
= &WP
;
16164 if (!IsInstantiation
&& FD
&& FD
->isConstexpr() && !FD
->isInvalidDecl() &&
16165 !CheckConstexprFunctionDefinition(FD
, CheckConstexprKind::Diagnose
))
16166 FD
->setInvalidDecl();
16168 if (FD
&& FD
->hasAttr
<NakedAttr
>()) {
16169 for (const Stmt
*S
: Body
->children()) {
16170 // Allow local register variables without initializer as they don't
16171 // require prologue.
16172 bool RegisterVariables
= false;
16173 if (auto *DS
= dyn_cast
<DeclStmt
>(S
)) {
16174 for (const auto *Decl
: DS
->decls()) {
16175 if (const auto *Var
= dyn_cast
<VarDecl
>(Decl
)) {
16176 RegisterVariables
=
16177 Var
->hasAttr
<AsmLabelAttr
>() && !Var
->hasInit();
16178 if (!RegisterVariables
)
16183 if (RegisterVariables
)
16185 if (!isa
<AsmStmt
>(S
) && !isa
<NullStmt
>(S
)) {
16186 Diag(S
->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function
);
16187 Diag(FD
->getAttr
<NakedAttr
>()->getLocation(), diag::note_attribute
);
16188 FD
->setInvalidDecl();
16194 assert(ExprCleanupObjects
.size() ==
16195 ExprEvalContexts
.back().NumCleanupObjects
&&
16196 "Leftover temporaries in function");
16197 assert(!Cleanup
.exprNeedsCleanups() &&
16198 "Unaccounted cleanups in function");
16199 assert(MaybeODRUseExprs
.empty() &&
16200 "Leftover expressions for odr-use checking");
16202 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16203 // the declaration context below. Otherwise, we're unable to transform
16204 // 'this' expressions when transforming immediate context functions.
16206 if (!IsInstantiation
)
16209 PopFunctionScopeInfo(ActivePolicy
, dcl
);
16210 // If any errors have occurred, clear out any temporaries that may have
16211 // been leftover. This ensures that these temporaries won't be picked up for
16212 // deletion in some later function.
16213 if (hasUncompilableErrorOccurred()) {
16214 DiscardCleanupsInEvaluationContext();
16217 if (FD
&& ((LangOpts
.OpenMP
&& (LangOpts
.OpenMPIsTargetDevice
||
16218 !LangOpts
.OMPTargetTriples
.empty())) ||
16219 LangOpts
.CUDA
|| LangOpts
.SYCLIsDevice
)) {
16220 auto ES
= getEmissionStatus(FD
);
16221 if (ES
== Sema::FunctionEmissionStatus::Emitted
||
16222 ES
== Sema::FunctionEmissionStatus::Unknown
)
16223 DeclsToCheckForDeferredDiags
.insert(FD
);
16226 if (FD
&& !FD
->isDeleted())
16227 checkTypeSupport(FD
->getType(), FD
->getLocation(), FD
);
16232 /// When we finish delayed parsing of an attribute, we must attach it to the
16234 void Sema::ActOnFinishDelayedAttribute(Scope
*S
, Decl
*D
,
16235 ParsedAttributes
&Attrs
) {
16236 // Always attach attributes to the underlying decl.
16237 if (TemplateDecl
*TD
= dyn_cast
<TemplateDecl
>(D
))
16238 D
= TD
->getTemplatedDecl();
16239 ProcessDeclAttributeList(S
, D
, Attrs
);
16241 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(D
))
16242 if (Method
->isStatic())
16243 checkThisInStaticMemberFunctionAttributes(Method
);
16246 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16247 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16248 NamedDecl
*Sema::ImplicitlyDefineFunction(SourceLocation Loc
,
16249 IdentifierInfo
&II
, Scope
*S
) {
16250 // It is not valid to implicitly define a function in C23.
16251 assert(LangOpts
.implicitFunctionsAllowed() &&
16252 "Implicit function declarations aren't allowed in this language mode");
16254 // Find the scope in which the identifier is injected and the corresponding
16256 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16257 // In that case, we inject the declaration into the translation unit scope
16259 Scope
*BlockScope
= S
;
16260 while (!BlockScope
->isCompoundStmtScope() && BlockScope
->getParent())
16261 BlockScope
= BlockScope
->getParent();
16263 // Loop until we find a DeclContext that is either a function/method or the
16264 // translation unit, which are the only two valid places to implicitly define
16265 // a function. This avoids accidentally defining the function within a tag
16266 // declaration, for example.
16267 Scope
*ContextScope
= BlockScope
;
16268 while (!ContextScope
->getEntity() ||
16269 (!ContextScope
->getEntity()->isFunctionOrMethod() &&
16270 !ContextScope
->getEntity()->isTranslationUnit()))
16271 ContextScope
= ContextScope
->getParent();
16272 ContextRAII
SavedContext(*this, ContextScope
->getEntity());
16274 // Before we produce a declaration for an implicitly defined
16275 // function, see whether there was a locally-scoped declaration of
16276 // this name as a function or variable. If so, use that
16277 // (non-visible) declaration, and complain about it.
16278 NamedDecl
*ExternCPrev
= findLocallyScopedExternCDecl(&II
);
16280 // We still need to inject the function into the enclosing block scope so
16281 // that later (non-call) uses can see it.
16282 PushOnScopeChains(ExternCPrev
, BlockScope
, /*AddToContext*/false);
16284 // C89 footnote 38:
16285 // If in fact it is not defined as having type "function returning int",
16286 // the behavior is undefined.
16287 if (!isa
<FunctionDecl
>(ExternCPrev
) ||
16288 !Context
.typesAreCompatible(
16289 cast
<FunctionDecl
>(ExternCPrev
)->getType(),
16290 Context
.getFunctionNoProtoType(Context
.IntTy
))) {
16291 Diag(Loc
, diag::ext_use_out_of_scope_declaration
)
16292 << ExternCPrev
<< !getLangOpts().C99
;
16293 Diag(ExternCPrev
->getLocation(), diag::note_previous_declaration
);
16294 return ExternCPrev
;
16298 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16300 if (II
.getName().startswith("__builtin_"))
16301 diag_id
= diag::warn_builtin_unknown
;
16302 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16303 else if (getLangOpts().C99
)
16304 diag_id
= diag::ext_implicit_function_decl_c99
;
16306 diag_id
= diag::warn_implicit_function_decl
;
16308 TypoCorrection Corrected
;
16309 // Because typo correction is expensive, only do it if the implicit
16310 // function declaration is going to be treated as an error.
16312 // Perform the correction before issuing the main diagnostic, as some
16313 // consumers use typo-correction callbacks to enhance the main diagnostic.
16314 if (S
&& !ExternCPrev
&&
16315 (Diags
.getDiagnosticLevel(diag_id
, Loc
) >= DiagnosticsEngine::Error
)) {
16316 DeclFilterCCC
<FunctionDecl
> CCC
{};
16317 Corrected
= CorrectTypo(DeclarationNameInfo(&II
, Loc
), LookupOrdinaryName
,
16318 S
, nullptr, CCC
, CTK_NonError
);
16321 Diag(Loc
, diag_id
) << &II
;
16323 // If the correction is going to suggest an implicitly defined function,
16324 // skip the correction as not being a particularly good idea.
16325 bool Diagnose
= true;
16326 if (const auto *D
= Corrected
.getCorrectionDecl())
16327 Diagnose
= !D
->isImplicit();
16329 diagnoseTypo(Corrected
, PDiag(diag::note_function_suggestion
),
16330 /*ErrorRecovery*/ false);
16333 // If we found a prior declaration of this function, don't bother building
16334 // another one. We've already pushed that one into scope, so there's nothing
16337 return ExternCPrev
;
16339 // Set a Declarator for the implicit definition: int foo();
16341 AttributeFactory attrFactory
;
16342 DeclSpec
DS(attrFactory
);
16344 bool Error
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, Dummy
, DiagID
,
16345 Context
.getPrintingPolicy());
16346 (void)Error
; // Silence warning.
16347 assert(!Error
&& "Error setting up implicit decl!");
16348 SourceLocation NoLoc
;
16349 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::Block
);
16350 D
.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16351 /*IsAmbiguous=*/false,
16352 /*LParenLoc=*/NoLoc
,
16353 /*Params=*/nullptr,
16355 /*EllipsisLoc=*/NoLoc
,
16356 /*RParenLoc=*/NoLoc
,
16357 /*RefQualifierIsLvalueRef=*/true,
16358 /*RefQualifierLoc=*/NoLoc
,
16359 /*MutableLoc=*/NoLoc
, EST_None
,
16360 /*ESpecRange=*/SourceRange(),
16361 /*Exceptions=*/nullptr,
16362 /*ExceptionRanges=*/nullptr,
16363 /*NumExceptions=*/0,
16364 /*NoexceptExpr=*/nullptr,
16365 /*ExceptionSpecTokens=*/nullptr,
16366 /*DeclsInPrototype=*/std::nullopt
,
16368 std::move(DS
.getAttributes()), SourceLocation());
16369 D
.SetIdentifier(&II
, Loc
);
16371 // Insert this function into the enclosing block scope.
16372 FunctionDecl
*FD
= cast
<FunctionDecl
>(ActOnDeclarator(BlockScope
, D
));
16375 AddKnownFunctionAttributes(FD
);
16380 /// If this function is a C++ replaceable global allocation function
16381 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16382 /// adds any function attributes that we know a priori based on the standard.
16384 /// We need to check for duplicate attributes both here and where user-written
16385 /// attributes are applied to declarations.
16386 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16387 FunctionDecl
*FD
) {
16388 if (FD
->isInvalidDecl())
16391 if (FD
->getDeclName().getCXXOverloadedOperator() != OO_New
&&
16392 FD
->getDeclName().getCXXOverloadedOperator() != OO_Array_New
)
16395 std::optional
<unsigned> AlignmentParam
;
16396 bool IsNothrow
= false;
16397 if (!FD
->isReplaceableGlobalAllocationFunction(&AlignmentParam
, &IsNothrow
))
16400 // C++2a [basic.stc.dynamic.allocation]p4:
16401 // An allocation function that has a non-throwing exception specification
16402 // indicates failure by returning a null pointer value. Any other allocation
16403 // function never returns a null pointer value and indicates failure only by
16404 // throwing an exception [...]
16406 // However, -fcheck-new invalidates this possible assumption, so don't add
16407 // NonNull when that is enabled.
16408 if (!IsNothrow
&& !FD
->hasAttr
<ReturnsNonNullAttr
>() &&
16409 !getLangOpts().CheckNew
)
16410 FD
->addAttr(ReturnsNonNullAttr::CreateImplicit(Context
, FD
->getLocation()));
16412 // C++2a [basic.stc.dynamic.allocation]p2:
16413 // An allocation function attempts to allocate the requested amount of
16414 // storage. [...] If the request succeeds, the value returned by a
16415 // replaceable allocation function is a [...] pointer value p0 different
16416 // from any previously returned value p1 [...]
16418 // However, this particular information is being added in codegen,
16419 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16421 // C++2a [basic.stc.dynamic.allocation]p2:
16422 // An allocation function attempts to allocate the requested amount of
16423 // storage. If it is successful, it returns the address of the start of a
16424 // block of storage whose length in bytes is at least as large as the
16426 if (!FD
->hasAttr
<AllocSizeAttr
>()) {
16427 FD
->addAttr(AllocSizeAttr::CreateImplicit(
16428 Context
, /*ElemSizeParam=*/ParamIdx(1, FD
),
16429 /*NumElemsParam=*/ParamIdx(), FD
->getLocation()));
16432 // C++2a [basic.stc.dynamic.allocation]p3:
16433 // For an allocation function [...], the pointer returned on a successful
16434 // call shall represent the address of storage that is aligned as follows:
16435 // (3.1) If the allocation function takes an argument of type
16436 // std​::​align_Âval_Ât, the storage will have the alignment
16437 // specified by the value of this argument.
16438 if (AlignmentParam
&& !FD
->hasAttr
<AllocAlignAttr
>()) {
16439 FD
->addAttr(AllocAlignAttr::CreateImplicit(
16440 Context
, ParamIdx(*AlignmentParam
, FD
), FD
->getLocation()));
16444 // C++2a [basic.stc.dynamic.allocation]p3:
16445 // For an allocation function [...], the pointer returned on a successful
16446 // call shall represent the address of storage that is aligned as follows:
16447 // (3.2) Otherwise, if the allocation function is named operator new[],
16448 // the storage is aligned for any object that does not have
16449 // new-extended alignment ([basic.align]) and is no larger than the
16451 // (3.3) Otherwise, the storage is aligned for any object that does not
16452 // have new-extended alignment and is of the requested size.
16455 /// Adds any function attributes that we know a priori based on
16456 /// the declaration of this function.
16458 /// These attributes can apply both to implicitly-declared builtins
16459 /// (like __builtin___printf_chk) or to library-declared functions
16460 /// like NSLog or printf.
16462 /// We need to check for duplicate attributes both here and where user-written
16463 /// attributes are applied to declarations.
16464 void Sema::AddKnownFunctionAttributes(FunctionDecl
*FD
) {
16465 if (FD
->isInvalidDecl())
16468 // If this is a built-in function, map its builtin attributes to
16469 // actual attributes.
16470 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
16471 // Handle printf-formatting attributes.
16472 unsigned FormatIdx
;
16474 if (Context
.BuiltinInfo
.isPrintfLike(BuiltinID
, FormatIdx
, HasVAListArg
)) {
16475 if (!FD
->hasAttr
<FormatAttr
>()) {
16476 const char *fmt
= "printf";
16477 unsigned int NumParams
= FD
->getNumParams();
16478 if (FormatIdx
< NumParams
&& // NumParams may be 0 (e.g. vfprintf)
16479 FD
->getParamDecl(FormatIdx
)->getType()->isObjCObjectPointerType())
16481 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16482 &Context
.Idents
.get(fmt
),
16484 HasVAListArg
? 0 : FormatIdx
+2,
16485 FD
->getLocation()));
16488 if (Context
.BuiltinInfo
.isScanfLike(BuiltinID
, FormatIdx
,
16490 if (!FD
->hasAttr
<FormatAttr
>())
16491 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16492 &Context
.Idents
.get("scanf"),
16494 HasVAListArg
? 0 : FormatIdx
+2,
16495 FD
->getLocation()));
16498 // Handle automatically recognized callbacks.
16499 SmallVector
<int, 4> Encoding
;
16500 if (!FD
->hasAttr
<CallbackAttr
>() &&
16501 Context
.BuiltinInfo
.performsCallback(BuiltinID
, Encoding
))
16502 FD
->addAttr(CallbackAttr::CreateImplicit(
16503 Context
, Encoding
.data(), Encoding
.size(), FD
->getLocation()));
16505 // Mark const if we don't care about errno and/or floating point exceptions
16506 // that are the only thing preventing the function from being const. This
16507 // allows IRgen to use LLVM intrinsics for such functions.
16508 bool NoExceptions
=
16509 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore
;
16510 bool ConstWithoutErrnoAndExceptions
=
16511 Context
.BuiltinInfo
.isConstWithoutErrnoAndExceptions(BuiltinID
);
16512 bool ConstWithoutExceptions
=
16513 Context
.BuiltinInfo
.isConstWithoutExceptions(BuiltinID
);
16514 if (!FD
->hasAttr
<ConstAttr
>() &&
16515 (ConstWithoutErrnoAndExceptions
|| ConstWithoutExceptions
) &&
16516 (!ConstWithoutErrnoAndExceptions
||
16517 (!getLangOpts().MathErrno
&& NoExceptions
)) &&
16518 (!ConstWithoutExceptions
|| NoExceptions
))
16519 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16521 // We make "fma" on GNU or Windows const because we know it does not set
16522 // errno in those environments even though it could set errno based on the
16524 const llvm::Triple
&Trip
= Context
.getTargetInfo().getTriple();
16525 if ((Trip
.isGNUEnvironment() || Trip
.isOSMSVCRT()) &&
16526 !FD
->hasAttr
<ConstAttr
>()) {
16527 switch (BuiltinID
) {
16528 case Builtin::BI__builtin_fma
:
16529 case Builtin::BI__builtin_fmaf
:
16530 case Builtin::BI__builtin_fmal
:
16531 case Builtin::BIfma
:
16532 case Builtin::BIfmaf
:
16533 case Builtin::BIfmal
:
16534 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16541 if (Context
.BuiltinInfo
.isReturnsTwice(BuiltinID
) &&
16542 !FD
->hasAttr
<ReturnsTwiceAttr
>())
16543 FD
->addAttr(ReturnsTwiceAttr::CreateImplicit(Context
,
16544 FD
->getLocation()));
16545 if (Context
.BuiltinInfo
.isNoThrow(BuiltinID
) && !FD
->hasAttr
<NoThrowAttr
>())
16546 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
16547 if (Context
.BuiltinInfo
.isPure(BuiltinID
) && !FD
->hasAttr
<PureAttr
>())
16548 FD
->addAttr(PureAttr::CreateImplicit(Context
, FD
->getLocation()));
16549 if (Context
.BuiltinInfo
.isConst(BuiltinID
) && !FD
->hasAttr
<ConstAttr
>())
16550 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16551 if (getLangOpts().CUDA
&& Context
.BuiltinInfo
.isTSBuiltin(BuiltinID
) &&
16552 !FD
->hasAttr
<CUDADeviceAttr
>() && !FD
->hasAttr
<CUDAHostAttr
>()) {
16553 // Add the appropriate attribute, depending on the CUDA compilation mode
16554 // and which target the builtin belongs to. For example, during host
16555 // compilation, aux builtins are __device__, while the rest are __host__.
16556 if (getLangOpts().CUDAIsDevice
!=
16557 Context
.BuiltinInfo
.isAuxBuiltinID(BuiltinID
))
16558 FD
->addAttr(CUDADeviceAttr::CreateImplicit(Context
, FD
->getLocation()));
16560 FD
->addAttr(CUDAHostAttr::CreateImplicit(Context
, FD
->getLocation()));
16563 // Add known guaranteed alignment for allocation functions.
16564 switch (BuiltinID
) {
16565 case Builtin::BImemalign
:
16566 case Builtin::BIaligned_alloc
:
16567 if (!FD
->hasAttr
<AllocAlignAttr
>())
16568 FD
->addAttr(AllocAlignAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16569 FD
->getLocation()));
16575 // Add allocsize attribute for allocation functions.
16576 switch (BuiltinID
) {
16577 case Builtin::BIcalloc
:
16578 FD
->addAttr(AllocSizeAttr::CreateImplicit(
16579 Context
, ParamIdx(1, FD
), ParamIdx(2, FD
), FD
->getLocation()));
16581 case Builtin::BImemalign
:
16582 case Builtin::BIaligned_alloc
:
16583 case Builtin::BIrealloc
:
16584 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(2, FD
),
16585 ParamIdx(), FD
->getLocation()));
16587 case Builtin::BImalloc
:
16588 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16589 ParamIdx(), FD
->getLocation()));
16595 // Add lifetime attribute to std::move, std::fowrard et al.
16596 switch (BuiltinID
) {
16597 case Builtin::BIaddressof
:
16598 case Builtin::BI__addressof
:
16599 case Builtin::BI__builtin_addressof
:
16600 case Builtin::BIas_const
:
16601 case Builtin::BIforward
:
16602 case Builtin::BIforward_like
:
16603 case Builtin::BImove
:
16604 case Builtin::BImove_if_noexcept
:
16605 if (ParmVarDecl
*P
= FD
->getParamDecl(0u);
16606 !P
->hasAttr
<LifetimeBoundAttr
>())
16608 LifetimeBoundAttr::CreateImplicit(Context
, FD
->getLocation()));
16615 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD
);
16617 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16618 // throw, add an implicit nothrow attribute to any extern "C" function we come
16620 if (getLangOpts().CXXExceptions
&& getLangOpts().ExternCNoUnwind
&&
16621 FD
->isExternC() && !FD
->hasAttr
<NoThrowAttr
>()) {
16622 const auto *FPT
= FD
->getType()->getAs
<FunctionProtoType
>();
16623 if (!FPT
|| FPT
->getExceptionSpecType() == EST_None
)
16624 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
16627 IdentifierInfo
*Name
= FD
->getIdentifier();
16630 if ((!getLangOpts().CPlusPlus
&& FD
->getDeclContext()->isTranslationUnit()) ||
16631 (isa
<LinkageSpecDecl
>(FD
->getDeclContext()) &&
16632 cast
<LinkageSpecDecl
>(FD
->getDeclContext())->getLanguage() ==
16633 LinkageSpecLanguageIDs::C
)) {
16634 // Okay: this could be a libc/libm/Objective-C function we know
16639 if (Name
->isStr("asprintf") || Name
->isStr("vasprintf")) {
16640 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16641 // target-specific builtins, perhaps?
16642 if (!FD
->hasAttr
<FormatAttr
>())
16643 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16644 &Context
.Idents
.get("printf"), 2,
16645 Name
->isStr("vasprintf") ? 0 : 3,
16646 FD
->getLocation()));
16649 if (Name
->isStr("__CFStringMakeConstantString")) {
16650 // We already have a __builtin___CFStringMakeConstantString,
16651 // but builds that use -fno-constant-cfstrings don't go through that.
16652 if (!FD
->hasAttr
<FormatArgAttr
>())
16653 FD
->addAttr(FormatArgAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16654 FD
->getLocation()));
16658 TypedefDecl
*Sema::ParseTypedefDecl(Scope
*S
, Declarator
&D
, QualType T
,
16659 TypeSourceInfo
*TInfo
) {
16660 assert(D
.getIdentifier() && "Wrong callback for declspec without declarator");
16661 assert(!T
.isNull() && "GetTypeForDeclarator() returned null type");
16664 assert(D
.isInvalidType() && "no declarator info for valid type");
16665 TInfo
= Context
.getTrivialTypeSourceInfo(T
);
16668 // Scope manipulation handled by caller.
16669 TypedefDecl
*NewTD
=
16670 TypedefDecl::Create(Context
, CurContext
, D
.getBeginLoc(),
16671 D
.getIdentifierLoc(), D
.getIdentifier(), TInfo
);
16673 // Bail out immediately if we have an invalid declaration.
16674 if (D
.isInvalidType()) {
16675 NewTD
->setInvalidDecl();
16679 if (D
.getDeclSpec().isModulePrivateSpecified()) {
16680 if (CurContext
->isFunctionOrMethod())
16681 Diag(NewTD
->getLocation(), diag::err_module_private_local
)
16683 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
16684 << FixItHint::CreateRemoval(
16685 D
.getDeclSpec().getModulePrivateSpecLoc());
16687 NewTD
->setModulePrivate();
16690 // C++ [dcl.typedef]p8:
16691 // If the typedef declaration defines an unnamed class (or
16692 // enum), the first typedef-name declared by the declaration
16693 // to be that class type (or enum type) is used to denote the
16694 // class type (or enum type) for linkage purposes only.
16695 // We need to check whether the type was declared in the declaration.
16696 switch (D
.getDeclSpec().getTypeSpecType()) {
16699 case TST_interface
:
16702 TagDecl
*tagFromDeclSpec
= cast
<TagDecl
>(D
.getDeclSpec().getRepAsDecl());
16703 setTagNameForLinkagePurposes(tagFromDeclSpec
, NewTD
);
16714 /// Check that this is a valid underlying type for an enum declaration.
16715 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo
*TI
) {
16716 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
16717 QualType T
= TI
->getType();
16719 if (T
->isDependentType())
16722 // This doesn't use 'isIntegralType' despite the error message mentioning
16723 // integral type because isIntegralType would also allow enum types in C.
16724 if (const BuiltinType
*BT
= T
->getAs
<BuiltinType
>())
16725 if (BT
->isInteger())
16728 return Diag(UnderlyingLoc
, diag::err_enum_invalid_underlying
)
16729 << T
<< T
->isBitIntType();
16732 /// Check whether this is a valid redeclaration of a previous enumeration.
16733 /// \return true if the redeclaration was invalid.
16734 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc
, bool IsScoped
,
16735 QualType EnumUnderlyingTy
, bool IsFixed
,
16736 const EnumDecl
*Prev
) {
16737 if (IsScoped
!= Prev
->isScoped()) {
16738 Diag(EnumLoc
, diag::err_enum_redeclare_scoped_mismatch
)
16739 << Prev
->isScoped();
16740 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
16744 if (IsFixed
&& Prev
->isFixed()) {
16745 if (!EnumUnderlyingTy
->isDependentType() &&
16746 !Prev
->getIntegerType()->isDependentType() &&
16747 !Context
.hasSameUnqualifiedType(EnumUnderlyingTy
,
16748 Prev
->getIntegerType())) {
16749 // TODO: Highlight the underlying type of the redeclaration.
16750 Diag(EnumLoc
, diag::err_enum_redeclare_type_mismatch
)
16751 << EnumUnderlyingTy
<< Prev
->getIntegerType();
16752 Diag(Prev
->getLocation(), diag::note_previous_declaration
)
16753 << Prev
->getIntegerTypeRange();
16756 } else if (IsFixed
!= Prev
->isFixed()) {
16757 Diag(EnumLoc
, diag::err_enum_redeclare_fixed_mismatch
)
16758 << Prev
->isFixed();
16759 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
16766 /// Get diagnostic %select index for tag kind for
16767 /// redeclaration diagnostic message.
16768 /// WARNING: Indexes apply to particular diagnostics only!
16770 /// \returns diagnostic %select index.
16771 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag
) {
16773 case TTK_Struct
: return 0;
16774 case TTK_Interface
: return 1;
16775 case TTK_Class
: return 2;
16776 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16780 /// Determine if tag kind is a class-key compatible with
16781 /// class for redeclaration (class, struct, or __interface).
16783 /// \returns true iff the tag kind is compatible.
16784 static bool isClassCompatTagKind(TagTypeKind Tag
)
16786 return Tag
== TTK_Struct
|| Tag
== TTK_Class
|| Tag
== TTK_Interface
;
16789 Sema::NonTagKind
Sema::getNonTagTypeDeclKind(const Decl
*PrevDecl
,
16791 if (isa
<TypedefDecl
>(PrevDecl
))
16792 return NTK_Typedef
;
16793 else if (isa
<TypeAliasDecl
>(PrevDecl
))
16794 return NTK_TypeAlias
;
16795 else if (isa
<ClassTemplateDecl
>(PrevDecl
))
16796 return NTK_Template
;
16797 else if (isa
<TypeAliasTemplateDecl
>(PrevDecl
))
16798 return NTK_TypeAliasTemplate
;
16799 else if (isa
<TemplateTemplateParmDecl
>(PrevDecl
))
16800 return NTK_TemplateTemplateArgument
;
16803 case TTK_Interface
:
16805 return getLangOpts().CPlusPlus
? NTK_NonClass
: NTK_NonStruct
;
16807 return NTK_NonUnion
;
16809 return NTK_NonEnum
;
16811 llvm_unreachable("invalid TTK");
16814 /// Determine whether a tag with a given kind is acceptable
16815 /// as a redeclaration of the given tag declaration.
16817 /// \returns true if the new tag kind is acceptable, false otherwise.
16818 bool Sema::isAcceptableTagRedeclaration(const TagDecl
*Previous
,
16819 TagTypeKind NewTag
, bool isDefinition
,
16820 SourceLocation NewTagLoc
,
16821 const IdentifierInfo
*Name
) {
16822 // C++ [dcl.type.elab]p3:
16823 // The class-key or enum keyword present in the
16824 // elaborated-type-specifier shall agree in kind with the
16825 // declaration to which the name in the elaborated-type-specifier
16826 // refers. This rule also applies to the form of
16827 // elaborated-type-specifier that declares a class-name or
16828 // friend class since it can be construed as referring to the
16829 // definition of the class. Thus, in any
16830 // elaborated-type-specifier, the enum keyword shall be used to
16831 // refer to an enumeration (7.2), the union class-key shall be
16832 // used to refer to a union (clause 9), and either the class or
16833 // struct class-key shall be used to refer to a class (clause 9)
16834 // declared using the class or struct class-key.
16835 TagTypeKind OldTag
= Previous
->getTagKind();
16836 if (OldTag
!= NewTag
&&
16837 !(isClassCompatTagKind(OldTag
) && isClassCompatTagKind(NewTag
)))
16840 // Tags are compatible, but we might still want to warn on mismatched tags.
16841 // Non-class tags can't be mismatched at this point.
16842 if (!isClassCompatTagKind(NewTag
))
16845 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16846 // by our warning analysis. We don't want to warn about mismatches with (eg)
16847 // declarations in system headers that are designed to be specialized, but if
16848 // a user asks us to warn, we should warn if their code contains mismatched
16850 auto IsIgnoredLoc
= [&](SourceLocation Loc
) {
16851 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch
,
16854 if (IsIgnoredLoc(NewTagLoc
))
16857 auto IsIgnored
= [&](const TagDecl
*Tag
) {
16858 return IsIgnoredLoc(Tag
->getLocation());
16860 while (IsIgnored(Previous
)) {
16861 Previous
= Previous
->getPreviousDecl();
16864 OldTag
= Previous
->getTagKind();
16867 bool isTemplate
= false;
16868 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Previous
))
16869 isTemplate
= Record
->getDescribedClassTemplate();
16871 if (inTemplateInstantiation()) {
16872 if (OldTag
!= NewTag
) {
16873 // In a template instantiation, do not offer fix-its for tag mismatches
16874 // since they usually mess up the template instead of fixing the problem.
16875 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16876 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16877 << getRedeclDiagFromTagKind(OldTag
);
16878 // FIXME: Note previous location?
16883 if (isDefinition
) {
16884 // On definitions, check all previous tags and issue a fix-it for each
16885 // one that doesn't match the current tag.
16886 if (Previous
->getDefinition()) {
16887 // Don't suggest fix-its for redefinitions.
16891 bool previousMismatch
= false;
16892 for (const TagDecl
*I
: Previous
->redecls()) {
16893 if (I
->getTagKind() != NewTag
) {
16894 // Ignore previous declarations for which the warning was disabled.
16898 if (!previousMismatch
) {
16899 previousMismatch
= true;
16900 Diag(NewTagLoc
, diag::warn_struct_class_previous_tag_mismatch
)
16901 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16902 << getRedeclDiagFromTagKind(I
->getTagKind());
16904 Diag(I
->getInnerLocStart(), diag::note_struct_class_suggestion
)
16905 << getRedeclDiagFromTagKind(NewTag
)
16906 << FixItHint::CreateReplacement(I
->getInnerLocStart(),
16907 TypeWithKeyword::getTagTypeKindName(NewTag
));
16913 // Identify the prevailing tag kind: this is the kind of the definition (if
16914 // there is a non-ignored definition), or otherwise the kind of the prior
16915 // (non-ignored) declaration.
16916 const TagDecl
*PrevDef
= Previous
->getDefinition();
16917 if (PrevDef
&& IsIgnored(PrevDef
))
16919 const TagDecl
*Redecl
= PrevDef
? PrevDef
: Previous
;
16920 if (Redecl
->getTagKind() != NewTag
) {
16921 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16922 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16923 << getRedeclDiagFromTagKind(OldTag
);
16924 Diag(Redecl
->getLocation(), diag::note_previous_use
);
16926 // If there is a previous definition, suggest a fix-it.
16928 Diag(NewTagLoc
, diag::note_struct_class_suggestion
)
16929 << getRedeclDiagFromTagKind(Redecl
->getTagKind())
16930 << FixItHint::CreateReplacement(SourceRange(NewTagLoc
),
16931 TypeWithKeyword::getTagTypeKindName(Redecl
->getTagKind()));
16938 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16939 /// from an outer enclosing namespace or file scope inside a friend declaration.
16940 /// This should provide the commented out code in the following snippet:
16944 /// struct Y { friend struct /*N::*/ X; };
16947 static FixItHint
createFriendTagNNSFixIt(Sema
&SemaRef
, NamedDecl
*ND
, Scope
*S
,
16948 SourceLocation NameLoc
) {
16949 // While the decl is in a namespace, do repeated lookup of that name and see
16950 // if we get the same namespace back. If we do not, continue until
16951 // translation unit scope, at which point we have a fully qualified NNS.
16952 SmallVector
<IdentifierInfo
*, 4> Namespaces
;
16953 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
16954 for (; !DC
->isTranslationUnit(); DC
= DC
->getParent()) {
16955 // This tag should be declared in a namespace, which can only be enclosed by
16956 // other namespaces. Bail if there's an anonymous namespace in the chain.
16957 NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(DC
);
16958 if (!Namespace
|| Namespace
->isAnonymousNamespace())
16959 return FixItHint();
16960 IdentifierInfo
*II
= Namespace
->getIdentifier();
16961 Namespaces
.push_back(II
);
16962 NamedDecl
*Lookup
= SemaRef
.LookupSingleName(
16963 S
, II
, NameLoc
, Sema::LookupNestedNameSpecifierName
);
16964 if (Lookup
== Namespace
)
16968 // Once we have all the namespaces, reverse them to go outermost first, and
16970 SmallString
<64> Insertion
;
16971 llvm::raw_svector_ostream
OS(Insertion
);
16972 if (DC
->isTranslationUnit())
16974 std::reverse(Namespaces
.begin(), Namespaces
.end());
16975 for (auto *II
: Namespaces
)
16976 OS
<< II
->getName() << "::";
16977 return FixItHint::CreateInsertion(NameLoc
, Insertion
);
16980 /// Determine whether a tag originally declared in context \p OldDC can
16981 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16982 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16983 /// using-declaration).
16984 static bool isAcceptableTagRedeclContext(Sema
&S
, DeclContext
*OldDC
,
16985 DeclContext
*NewDC
) {
16986 OldDC
= OldDC
->getRedeclContext();
16987 NewDC
= NewDC
->getRedeclContext();
16989 if (OldDC
->Equals(NewDC
))
16992 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16993 // encloses the other).
16994 if (S
.getLangOpts().MSVCCompat
&&
16995 (OldDC
->Encloses(NewDC
) || NewDC
->Encloses(OldDC
)))
17001 /// This is invoked when we see 'struct foo' or 'struct {'. In the
17002 /// former case, Name will be non-null. In the later case, Name will be null.
17003 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17004 /// reference/declaration/definition of a tag.
17006 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
17007 /// trailing-type-specifier) other than one in an alias-declaration.
17009 /// \param SkipBody If non-null, will be set to indicate if the caller should
17010 /// skip the definition of this tag and treat it as if it were a declaration.
17012 Sema::ActOnTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
, SourceLocation KWLoc
,
17013 CXXScopeSpec
&SS
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
17014 const ParsedAttributesView
&Attrs
, AccessSpecifier AS
,
17015 SourceLocation ModulePrivateLoc
,
17016 MultiTemplateParamsArg TemplateParameterLists
, bool &OwnedDecl
,
17017 bool &IsDependent
, SourceLocation ScopedEnumKWLoc
,
17018 bool ScopedEnumUsesClassTag
, TypeResult UnderlyingType
,
17019 bool IsTypeSpecifier
, bool IsTemplateParamOrArg
,
17020 OffsetOfKind OOK
, SkipBodyInfo
*SkipBody
) {
17021 // If this is not a definition, it must have a name.
17022 IdentifierInfo
*OrigName
= Name
;
17023 assert((Name
!= nullptr || TUK
== TUK_Definition
) &&
17024 "Nameless record must be a definition!");
17025 assert(TemplateParameterLists
.size() == 0 || TUK
!= TUK_Reference
);
17028 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
17029 bool ScopedEnum
= ScopedEnumKWLoc
.isValid();
17031 // FIXME: Check member specializations more carefully.
17032 bool isMemberSpecialization
= false;
17033 bool Invalid
= false;
17035 // We only need to do this matching if we have template parameters
17036 // or a scope specifier, which also conveniently avoids this work
17037 // for non-C++ cases.
17038 if (TemplateParameterLists
.size() > 0 ||
17039 (SS
.isNotEmpty() && TUK
!= TUK_Reference
)) {
17040 if (TemplateParameterList
*TemplateParams
=
17041 MatchTemplateParametersToScopeSpecifier(
17042 KWLoc
, NameLoc
, SS
, nullptr, TemplateParameterLists
,
17043 TUK
== TUK_Friend
, isMemberSpecialization
, Invalid
)) {
17044 if (Kind
== TTK_Enum
) {
17045 Diag(KWLoc
, diag::err_enum_template
);
17049 if (TemplateParams
->size() > 0) {
17050 // This is a declaration or definition of a class template (which may
17051 // be a member of another template).
17057 DeclResult Result
= CheckClassTemplate(
17058 S
, TagSpec
, TUK
, KWLoc
, SS
, Name
, NameLoc
, Attrs
, TemplateParams
,
17059 AS
, ModulePrivateLoc
,
17060 /*FriendLoc*/ SourceLocation(), TemplateParameterLists
.size() - 1,
17061 TemplateParameterLists
.data(), SkipBody
);
17062 return Result
.get();
17064 // The "template<>" header is extraneous.
17065 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
17066 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
17067 isMemberSpecialization
= true;
17071 if (!TemplateParameterLists
.empty() && isMemberSpecialization
&&
17072 CheckTemplateDeclScope(S
, TemplateParameterLists
.back()))
17076 // Figure out the underlying type if this a enum declaration. We need to do
17077 // this early, because it's needed to detect if this is an incompatible
17079 llvm::PointerUnion
<const Type
*, TypeSourceInfo
*> EnumUnderlying
;
17080 bool IsFixed
= !UnderlyingType
.isUnset() || ScopedEnum
;
17082 if (Kind
== TTK_Enum
) {
17083 if (UnderlyingType
.isInvalid() || (!UnderlyingType
.get() && ScopedEnum
)) {
17084 // No underlying type explicitly specified, or we failed to parse the
17085 // type, default to int.
17086 EnumUnderlying
= Context
.IntTy
.getTypePtr();
17087 } else if (UnderlyingType
.get()) {
17088 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17089 // integral type; any cv-qualification is ignored.
17090 TypeSourceInfo
*TI
= nullptr;
17091 GetTypeFromParser(UnderlyingType
.get(), &TI
);
17092 EnumUnderlying
= TI
;
17094 if (CheckEnumUnderlyingType(TI
))
17095 // Recover by falling back to int.
17096 EnumUnderlying
= Context
.IntTy
.getTypePtr();
17098 if (DiagnoseUnexpandedParameterPack(TI
->getTypeLoc().getBeginLoc(), TI
,
17099 UPPC_FixedUnderlyingType
))
17100 EnumUnderlying
= Context
.IntTy
.getTypePtr();
17102 } else if (Context
.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17103 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17104 // of 'int'. However, if this is an unfixed forward declaration, don't set
17105 // the underlying type unless the user enables -fms-compatibility. This
17106 // makes unfixed forward declared enums incomplete and is more conforming.
17107 if (TUK
== TUK_Definition
|| getLangOpts().MSVCCompat
)
17108 EnumUnderlying
= Context
.IntTy
.getTypePtr();
17112 DeclContext
*SearchDC
= CurContext
;
17113 DeclContext
*DC
= CurContext
;
17114 bool isStdBadAlloc
= false;
17115 bool isStdAlignValT
= false;
17117 RedeclarationKind Redecl
= forRedeclarationInCurContext();
17118 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
)
17119 Redecl
= NotForRedeclaration
;
17121 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17122 /// implemented asks for structural equivalence checking, the returned decl
17123 /// here is passed back to the parser, allowing the tag body to be parsed.
17124 auto createTagFromNewDecl
= [&]() -> TagDecl
* {
17125 assert(!getLangOpts().CPlusPlus
&& "not meant for C++ usage");
17126 // If there is an identifier, use the location of the identifier as the
17127 // location of the decl, otherwise use the location of the struct/union
17129 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
17130 TagDecl
*New
= nullptr;
17132 if (Kind
== TTK_Enum
) {
17133 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
, nullptr,
17134 ScopedEnum
, ScopedEnumUsesClassTag
, IsFixed
);
17135 // If this is an undefined enum, bail.
17136 if (TUK
!= TUK_Definition
&& !Invalid
)
17138 if (EnumUnderlying
) {
17139 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
17140 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
17141 ED
->setIntegerTypeSourceInfo(TI
);
17143 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
17144 QualType EnumTy
= ED
->getIntegerType();
17145 ED
->setPromotionType(Context
.isPromotableIntegerType(EnumTy
)
17146 ? Context
.getPromotedIntegerType(EnumTy
)
17149 } else { // struct/union
17150 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17154 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
17155 // Add alignment attributes if necessary; these attributes are checked
17156 // when the ASTContext lays out the structure.
17158 // It is important for implementing the correct semantics that this
17159 // happen here (in ActOnTag). The #pragma pack stack is
17160 // maintained as a result of parser callbacks which can occur at
17161 // many points during the parsing of a struct declaration (because
17162 // the #pragma tokens are effectively skipped over during the
17163 // parsing of the struct).
17164 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
17165 AddAlignmentAttributesForRecord(RD
);
17166 AddMsStructLayoutForRecord(RD
);
17169 New
->setLexicalDeclContext(CurContext
);
17173 LookupResult
Previous(*this, Name
, NameLoc
, LookupTagName
, Redecl
);
17174 if (Name
&& SS
.isNotEmpty()) {
17175 // We have a nested-name tag ('struct foo::bar').
17177 // Check for invalid 'foo::'.
17178 if (SS
.isInvalid()) {
17180 goto CreateNewDecl
;
17183 // If this is a friend or a reference to a class in a dependent
17184 // context, don't try to make a decl for it.
17185 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
17186 DC
= computeDeclContext(SS
, false);
17188 IsDependent
= true;
17192 DC
= computeDeclContext(SS
, true);
17194 Diag(SS
.getRange().getBegin(), diag::err_dependent_nested_name_spec
)
17200 if (RequireCompleteDeclContext(SS
, DC
))
17204 // Look-up name inside 'foo::'.
17205 LookupQualifiedName(Previous
, DC
);
17207 if (Previous
.isAmbiguous())
17210 if (Previous
.empty()) {
17211 // Name lookup did not find anything. However, if the
17212 // nested-name-specifier refers to the current instantiation,
17213 // and that current instantiation has any dependent base
17214 // classes, we might find something at instantiation time: treat
17215 // this as a dependent elaborated-type-specifier.
17216 // But this only makes any sense for reference-like lookups.
17217 if (Previous
.wasNotFoundInCurrentInstantiation() &&
17218 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)) {
17219 IsDependent
= true;
17223 // A tag 'foo::bar' must already exist.
17224 Diag(NameLoc
, diag::err_not_tag_in_scope
)
17225 << Kind
<< Name
<< DC
<< SS
.getRange();
17228 goto CreateNewDecl
;
17231 // C++14 [class.mem]p14:
17232 // If T is the name of a class, then each of the following shall have a
17233 // name different from T:
17234 // -- every member of class T that is itself a type
17235 if (TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
17236 DiagnoseClassNameShadow(SearchDC
, DeclarationNameInfo(Name
, NameLoc
)))
17239 // If this is a named struct, check to see if there was a previous forward
17240 // declaration or definition.
17241 // FIXME: We're looking into outer scopes here, even when we
17242 // shouldn't be. Doing so can result in ambiguities that we
17243 // shouldn't be diagnosing.
17244 LookupName(Previous
, S
);
17246 // When declaring or defining a tag, ignore ambiguities introduced
17247 // by types using'ed into this scope.
17248 if (Previous
.isAmbiguous() &&
17249 (TUK
== TUK_Definition
|| TUK
== TUK_Declaration
)) {
17250 LookupResult::Filter F
= Previous
.makeFilter();
17251 while (F
.hasNext()) {
17252 NamedDecl
*ND
= F
.next();
17253 if (!ND
->getDeclContext()->getRedeclContext()->Equals(
17254 SearchDC
->getRedeclContext()))
17260 // C++11 [namespace.memdef]p3:
17261 // If the name in a friend declaration is neither qualified nor
17262 // a template-id and the declaration is a function or an
17263 // elaborated-type-specifier, the lookup to determine whether
17264 // the entity has been previously declared shall not consider
17265 // any scopes outside the innermost enclosing namespace.
17267 // MSVC doesn't implement the above rule for types, so a friend tag
17268 // declaration may be a redeclaration of a type declared in an enclosing
17269 // scope. They do implement this rule for friend functions.
17271 // Does it matter that this should be by scope instead of by
17272 // semantic context?
17273 if (!Previous
.empty() && TUK
== TUK_Friend
) {
17274 DeclContext
*EnclosingNS
= SearchDC
->getEnclosingNamespaceContext();
17275 LookupResult::Filter F
= Previous
.makeFilter();
17276 bool FriendSawTagOutsideEnclosingNamespace
= false;
17277 while (F
.hasNext()) {
17278 NamedDecl
*ND
= F
.next();
17279 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
17280 if (DC
->isFileContext() &&
17281 !EnclosingNS
->Encloses(ND
->getDeclContext())) {
17282 if (getLangOpts().MSVCCompat
)
17283 FriendSawTagOutsideEnclosingNamespace
= true;
17290 // Diagnose this MSVC extension in the easy case where lookup would have
17291 // unambiguously found something outside the enclosing namespace.
17292 if (Previous
.isSingleResult() && FriendSawTagOutsideEnclosingNamespace
) {
17293 NamedDecl
*ND
= Previous
.getFoundDecl();
17294 Diag(NameLoc
, diag::ext_friend_tag_redecl_outside_namespace
)
17295 << createFriendTagNNSFixIt(*this, ND
, S
, NameLoc
);
17299 // Note: there used to be some attempt at recovery here.
17300 if (Previous
.isAmbiguous())
17303 if (!getLangOpts().CPlusPlus
&& TUK
!= TUK_Reference
) {
17304 // FIXME: This makes sure that we ignore the contexts associated
17305 // with C structs, unions, and enums when looking for a matching
17306 // tag declaration or definition. See the similar lookup tweak
17307 // in Sema::LookupName; is there a better way to deal with this?
17308 while (isa
<RecordDecl
, EnumDecl
, ObjCContainerDecl
>(SearchDC
))
17309 SearchDC
= SearchDC
->getParent();
17310 } else if (getLangOpts().CPlusPlus
) {
17311 // Inside ObjCContainer want to keep it as a lexical decl context but go
17312 // past it (most often to TranslationUnit) to find the semantic decl
17314 while (isa
<ObjCContainerDecl
>(SearchDC
))
17315 SearchDC
= SearchDC
->getParent();
17317 } else if (getLangOpts().CPlusPlus
) {
17318 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17319 // TagDecl the same way as we skip it for named TagDecl.
17320 while (isa
<ObjCContainerDecl
>(SearchDC
))
17321 SearchDC
= SearchDC
->getParent();
17324 if (Previous
.isSingleResult() &&
17325 Previous
.getFoundDecl()->isTemplateParameter()) {
17326 // Maybe we will complain about the shadowed template parameter.
17327 DiagnoseTemplateParameterShadow(NameLoc
, Previous
.getFoundDecl());
17328 // Just pretend that we didn't see the previous declaration.
17332 if (getLangOpts().CPlusPlus
&& Name
&& DC
&& StdNamespace
&&
17333 DC
->Equals(getStdNamespace())) {
17334 if (Name
->isStr("bad_alloc")) {
17335 // This is a declaration of or a reference to "std::bad_alloc".
17336 isStdBadAlloc
= true;
17338 // If std::bad_alloc has been implicitly declared (but made invisible to
17339 // name lookup), fill in this implicit declaration as the previous
17340 // declaration, so that the declarations get chained appropriately.
17341 if (Previous
.empty() && StdBadAlloc
)
17342 Previous
.addDecl(getStdBadAlloc());
17343 } else if (Name
->isStr("align_val_t")) {
17344 isStdAlignValT
= true;
17345 if (Previous
.empty() && StdAlignValT
)
17346 Previous
.addDecl(getStdAlignValT());
17350 // If we didn't find a previous declaration, and this is a reference
17351 // (or friend reference), move to the correct scope. In C++, we
17352 // also need to do a redeclaration lookup there, just in case
17353 // there's a shadow friend decl.
17354 if (Name
&& Previous
.empty() &&
17355 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
|| IsTemplateParamOrArg
)) {
17356 if (Invalid
) goto CreateNewDecl
;
17357 assert(SS
.isEmpty());
17359 if (TUK
== TUK_Reference
|| IsTemplateParamOrArg
) {
17360 // C++ [basic.scope.pdecl]p5:
17361 // -- for an elaborated-type-specifier of the form
17363 // class-key identifier
17365 // if the elaborated-type-specifier is used in the
17366 // decl-specifier-seq or parameter-declaration-clause of a
17367 // function defined in namespace scope, the identifier is
17368 // declared as a class-name in the namespace that contains
17369 // the declaration; otherwise, except as a friend
17370 // declaration, the identifier is declared in the smallest
17371 // non-class, non-function-prototype scope that contains the
17374 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17375 // C structs and unions.
17377 // It is an error in C++ to declare (rather than define) an enum
17378 // type, including via an elaborated type specifier. We'll
17379 // diagnose that later; for now, declare the enum in the same
17380 // scope as we would have picked for any other tag type.
17382 // GNU C also supports this behavior as part of its incomplete
17383 // enum types extension, while GNU C++ does not.
17385 // Find the context where we'll be declaring the tag.
17386 // FIXME: We would like to maintain the current DeclContext as the
17387 // lexical context,
17388 SearchDC
= getTagInjectionContext(SearchDC
);
17390 // Find the scope where we'll be declaring the tag.
17391 S
= getTagInjectionScope(S
, getLangOpts());
17393 assert(TUK
== TUK_Friend
);
17394 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(SearchDC
);
17396 // C++ [namespace.memdef]p3:
17397 // If a friend declaration in a non-local class first declares a
17398 // class or function, the friend class or function is a member of
17399 // the innermost enclosing namespace.
17400 SearchDC
= RD
->isLocalClass() ? RD
->isLocalClass()
17401 : SearchDC
->getEnclosingNamespaceContext();
17404 // In C++, we need to do a redeclaration lookup to properly
17405 // diagnose some problems.
17406 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17407 // hidden declaration so that we don't get ambiguity errors when using a
17408 // type declared by an elaborated-type-specifier. In C that is not correct
17409 // and we should instead merge compatible types found by lookup.
17410 if (getLangOpts().CPlusPlus
) {
17411 // FIXME: This can perform qualified lookups into function contexts,
17412 // which are meaningless.
17413 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
17414 LookupQualifiedName(Previous
, SearchDC
);
17416 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
17417 LookupName(Previous
, S
);
17421 // If we have a known previous declaration to use, then use it.
17422 if (Previous
.empty() && SkipBody
&& SkipBody
->Previous
)
17423 Previous
.addDecl(SkipBody
->Previous
);
17425 if (!Previous
.empty()) {
17426 NamedDecl
*PrevDecl
= Previous
.getFoundDecl();
17427 NamedDecl
*DirectPrevDecl
= Previous
.getRepresentativeDecl();
17429 // It's okay to have a tag decl in the same scope as a typedef
17430 // which hides a tag decl in the same scope. Finding this
17431 // with a redeclaration lookup can only actually happen in C++.
17433 // This is also okay for elaborated-type-specifiers, which is
17434 // technically forbidden by the current standard but which is
17435 // okay according to the likely resolution of an open issue;
17436 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17437 if (getLangOpts().CPlusPlus
) {
17438 if (TypedefNameDecl
*TD
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
17439 if (const TagType
*TT
= TD
->getUnderlyingType()->getAs
<TagType
>()) {
17440 TagDecl
*Tag
= TT
->getDecl();
17441 if (Tag
->getDeclName() == Name
&&
17442 Tag
->getDeclContext()->getRedeclContext()
17443 ->Equals(TD
->getDeclContext()->getRedeclContext())) {
17446 Previous
.addDecl(Tag
);
17447 Previous
.resolveKind();
17453 // If this is a redeclaration of a using shadow declaration, it must
17454 // declare a tag in the same context. In MSVC mode, we allow a
17455 // redefinition if either context is within the other.
17456 if (auto *Shadow
= dyn_cast
<UsingShadowDecl
>(DirectPrevDecl
)) {
17457 auto *OldTag
= dyn_cast
<TagDecl
>(PrevDecl
);
17458 if (SS
.isEmpty() && TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
17459 isDeclInScope(Shadow
, SearchDC
, S
, isMemberSpecialization
) &&
17460 !(OldTag
&& isAcceptableTagRedeclContext(
17461 *this, OldTag
->getDeclContext(), SearchDC
))) {
17462 Diag(KWLoc
, diag::err_using_decl_conflict_reverse
);
17463 Diag(Shadow
->getTargetDecl()->getLocation(),
17464 diag::note_using_decl_target
);
17465 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
17467 // Recover by ignoring the old declaration.
17469 goto CreateNewDecl
;
17473 if (TagDecl
*PrevTagDecl
= dyn_cast
<TagDecl
>(PrevDecl
)) {
17474 // If this is a use of a previous tag, or if the tag is already declared
17475 // in the same scope (so that the definition/declaration completes or
17476 // rementions the tag), reuse the decl.
17477 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
||
17478 isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
17479 SS
.isNotEmpty() || isMemberSpecialization
)) {
17480 // Make sure that this wasn't declared as an enum and now used as a
17481 // struct or something similar.
17482 if (!isAcceptableTagRedeclaration(PrevTagDecl
, Kind
,
17483 TUK
== TUK_Definition
, KWLoc
,
17485 bool SafeToContinue
17486 = (PrevTagDecl
->getTagKind() != TTK_Enum
&&
17488 if (SafeToContinue
)
17489 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
17491 << FixItHint::CreateReplacement(SourceRange(KWLoc
),
17492 PrevTagDecl
->getKindName());
17494 Diag(KWLoc
, diag::err_use_with_wrong_tag
) << Name
;
17495 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
17497 if (SafeToContinue
)
17498 Kind
= PrevTagDecl
->getTagKind();
17500 // Recover by making this an anonymous redefinition.
17507 if (Kind
== TTK_Enum
&& PrevTagDecl
->getTagKind() == TTK_Enum
) {
17508 const EnumDecl
*PrevEnum
= cast
<EnumDecl
>(PrevTagDecl
);
17509 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)
17510 return PrevTagDecl
;
17512 QualType EnumUnderlyingTy
;
17513 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
17514 EnumUnderlyingTy
= TI
->getType().getUnqualifiedType();
17515 else if (const Type
*T
= EnumUnderlying
.dyn_cast
<const Type
*>())
17516 EnumUnderlyingTy
= QualType(T
, 0);
17518 // All conflicts with previous declarations are recovered by
17519 // returning the previous declaration, unless this is a definition,
17520 // in which case we want the caller to bail out.
17521 if (CheckEnumRedeclaration(NameLoc
.isValid() ? NameLoc
: KWLoc
,
17522 ScopedEnum
, EnumUnderlyingTy
,
17523 IsFixed
, PrevEnum
))
17524 return TUK
== TUK_Declaration
? PrevTagDecl
: nullptr;
17527 // C++11 [class.mem]p1:
17528 // A member shall not be declared twice in the member-specification,
17529 // except that a nested class or member class template can be declared
17530 // and then later defined.
17531 if (TUK
== TUK_Declaration
&& PrevDecl
->isCXXClassMember() &&
17532 S
->isDeclScope(PrevDecl
)) {
17533 Diag(NameLoc
, diag::ext_member_redeclared
);
17534 Diag(PrevTagDecl
->getLocation(), diag::note_previous_declaration
);
17538 // If this is a use, just return the declaration we found, unless
17539 // we have attributes.
17540 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
17541 if (!Attrs
.empty()) {
17542 // FIXME: Diagnose these attributes. For now, we create a new
17543 // declaration to hold them.
17544 } else if (TUK
== TUK_Reference
&&
17545 (PrevTagDecl
->getFriendObjectKind() ==
17546 Decl::FOK_Undeclared
||
17547 PrevDecl
->getOwningModule() != getCurrentModule()) &&
17549 // This declaration is a reference to an existing entity, but
17550 // has different visibility from that entity: it either makes
17551 // a friend visible or it makes a type visible in a new module.
17552 // In either case, create a new declaration. We only do this if
17553 // the declaration would have meant the same thing if no prior
17554 // declaration were found, that is, if it was found in the same
17555 // scope where we would have injected a declaration.
17556 if (!getTagInjectionContext(CurContext
)->getRedeclContext()
17557 ->Equals(PrevDecl
->getDeclContext()->getRedeclContext()))
17558 return PrevTagDecl
;
17559 // This is in the injected scope, create a new declaration in
17561 S
= getTagInjectionScope(S
, getLangOpts());
17563 return PrevTagDecl
;
17567 // Diagnose attempts to redefine a tag.
17568 if (TUK
== TUK_Definition
) {
17569 if (NamedDecl
*Def
= PrevTagDecl
->getDefinition()) {
17570 // If we're defining a specialization and the previous definition
17571 // is from an implicit instantiation, don't emit an error
17572 // here; we'll catch this in the general case below.
17573 bool IsExplicitSpecializationAfterInstantiation
= false;
17574 if (isMemberSpecialization
) {
17575 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Def
))
17576 IsExplicitSpecializationAfterInstantiation
=
17577 RD
->getTemplateSpecializationKind() !=
17578 TSK_ExplicitSpecialization
;
17579 else if (EnumDecl
*ED
= dyn_cast
<EnumDecl
>(Def
))
17580 IsExplicitSpecializationAfterInstantiation
=
17581 ED
->getTemplateSpecializationKind() !=
17582 TSK_ExplicitSpecialization
;
17585 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17586 // not keep more that one definition around (merge them). However,
17587 // ensure the decl passes the structural compatibility check in
17588 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17589 NamedDecl
*Hidden
= nullptr;
17590 if (SkipBody
&& !hasVisibleDefinition(Def
, &Hidden
)) {
17591 // There is a definition of this tag, but it is not visible. We
17592 // explicitly make use of C++'s one definition rule here, and
17593 // assume that this definition is identical to the hidden one
17594 // we already have. Make the existing definition visible and
17595 // use it in place of this one.
17596 if (!getLangOpts().CPlusPlus
) {
17597 // Postpone making the old definition visible until after we
17598 // complete parsing the new one and do the structural
17600 SkipBody
->CheckSameAsPrevious
= true;
17601 SkipBody
->New
= createTagFromNewDecl();
17602 SkipBody
->Previous
= Def
;
17605 SkipBody
->ShouldSkip
= true;
17606 SkipBody
->Previous
= Def
;
17607 makeMergedDefinitionVisible(Hidden
);
17608 // Carry on and handle it like a normal definition. We'll
17609 // skip starting the definitiion later.
17611 } else if (!IsExplicitSpecializationAfterInstantiation
) {
17612 // A redeclaration in function prototype scope in C isn't
17613 // visible elsewhere, so merely issue a warning.
17614 if (!getLangOpts().CPlusPlus
&& S
->containedInPrototypeScope())
17615 Diag(NameLoc
, diag::warn_redefinition_in_param_list
) << Name
;
17617 Diag(NameLoc
, diag::err_redefinition
) << Name
;
17618 notePreviousDefinition(Def
,
17619 NameLoc
.isValid() ? NameLoc
: KWLoc
);
17620 // If this is a redefinition, recover by making this
17621 // struct be anonymous, which will make any later
17622 // references get the previous definition.
17628 // If the type is currently being defined, complain
17629 // about a nested redefinition.
17630 auto *TD
= Context
.getTagDeclType(PrevTagDecl
)->getAsTagDecl();
17631 if (TD
->isBeingDefined()) {
17632 Diag(NameLoc
, diag::err_nested_redefinition
) << Name
;
17633 Diag(PrevTagDecl
->getLocation(),
17634 diag::note_previous_definition
);
17641 // Okay, this is definition of a previously declared or referenced
17642 // tag. We're going to create a new Decl for it.
17645 // Okay, we're going to make a redeclaration. If this is some kind
17646 // of reference, make sure we build the redeclaration in the same DC
17647 // as the original, and ignore the current access specifier.
17648 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
17649 SearchDC
= PrevTagDecl
->getDeclContext();
17653 // If we get here we have (another) forward declaration or we
17654 // have a definition. Just create a new decl.
17657 // If we get here, this is a definition of a new tag type in a nested
17658 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17659 // new decl/type. We set PrevDecl to NULL so that the entities
17660 // have distinct types.
17663 // If we get here, we're going to create a new Decl. If PrevDecl
17664 // is non-NULL, it's a definition of the tag declared by
17665 // PrevDecl. If it's NULL, we have a new definition.
17667 // Otherwise, PrevDecl is not a tag, but was found with tag
17668 // lookup. This is only actually possible in C++, where a few
17669 // things like templates still live in the tag namespace.
17671 // Use a better diagnostic if an elaborated-type-specifier
17672 // found the wrong kind of type on the first
17673 // (non-redeclaration) lookup.
17674 if ((TUK
== TUK_Reference
|| TUK
== TUK_Friend
) &&
17675 !Previous
.isForRedeclaration()) {
17676 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
17677 Diag(NameLoc
, diag::err_tag_reference_non_tag
) << PrevDecl
<< NTK
17679 Diag(PrevDecl
->getLocation(), diag::note_declared_at
);
17682 // Otherwise, only diagnose if the declaration is in scope.
17683 } else if (!isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
17684 SS
.isNotEmpty() || isMemberSpecialization
)) {
17687 // Diagnose implicit declarations introduced by elaborated types.
17688 } else if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
17689 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
17690 Diag(NameLoc
, diag::err_tag_reference_conflict
) << NTK
;
17691 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
17694 // Otherwise it's a declaration. Call out a particularly common
17696 } else if (TypedefNameDecl
*TND
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
17698 if (isa
<TypeAliasDecl
>(PrevDecl
)) Kind
= 1;
17699 Diag(NameLoc
, diag::err_tag_definition_of_typedef
)
17700 << Name
<< Kind
<< TND
->getUnderlyingType();
17701 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
17704 // Otherwise, diagnose.
17706 // The tag name clashes with something else in the target scope,
17707 // issue an error and recover by making this tag be anonymous.
17708 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
17709 notePreviousDefinition(PrevDecl
, NameLoc
);
17714 // The existing declaration isn't relevant to us; we're in a
17715 // new scope, so clear out the previous declaration.
17722 TagDecl
*PrevDecl
= nullptr;
17723 if (Previous
.isSingleResult())
17724 PrevDecl
= cast
<TagDecl
>(Previous
.getFoundDecl());
17726 // If there is an identifier, use the location of the identifier as the
17727 // location of the decl, otherwise use the location of the struct/union
17729 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
17731 // Otherwise, create a new declaration. If there is a previous
17732 // declaration of the same entity, the two will be linked via
17736 if (Kind
== TTK_Enum
) {
17737 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17738 // enum X { A, B, C } D; D should chain to X.
17739 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
,
17740 cast_or_null
<EnumDecl
>(PrevDecl
), ScopedEnum
,
17741 ScopedEnumUsesClassTag
, IsFixed
);
17743 if (isStdAlignValT
&& (!StdAlignValT
|| getStdAlignValT()->isImplicit()))
17744 StdAlignValT
= cast
<EnumDecl
>(New
);
17746 // If this is an undefined enum, warn.
17747 if (TUK
!= TUK_Definition
&& !Invalid
) {
17749 if (IsFixed
&& cast
<EnumDecl
>(New
)->isFixed()) {
17750 // C++0x: 7.2p2: opaque-enum-declaration.
17751 // Conflicts are diagnosed above. Do nothing.
17753 else if (PrevDecl
&& (Def
= cast
<EnumDecl
>(PrevDecl
)->getDefinition())) {
17754 Diag(Loc
, diag::ext_forward_ref_enum_def
)
17756 Diag(Def
->getLocation(), diag::note_previous_definition
);
17758 unsigned DiagID
= diag::ext_forward_ref_enum
;
17759 if (getLangOpts().MSVCCompat
)
17760 DiagID
= diag::ext_ms_forward_ref_enum
;
17761 else if (getLangOpts().CPlusPlus
)
17762 DiagID
= diag::err_forward_ref_enum
;
17767 if (EnumUnderlying
) {
17768 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
17769 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
17770 ED
->setIntegerTypeSourceInfo(TI
);
17772 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
17773 QualType EnumTy
= ED
->getIntegerType();
17774 ED
->setPromotionType(Context
.isPromotableIntegerType(EnumTy
)
17775 ? Context
.getPromotedIntegerType(EnumTy
)
17777 assert(ED
->isComplete() && "enum with type should be complete");
17780 // struct/union/class
17782 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17783 // struct X { int A; } D; D should chain to X.
17784 if (getLangOpts().CPlusPlus
) {
17785 // FIXME: Look for a way to use RecordDecl for simple structs.
17786 New
= CXXRecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17787 cast_or_null
<CXXRecordDecl
>(PrevDecl
));
17789 if (isStdBadAlloc
&& (!StdBadAlloc
|| getStdBadAlloc()->isImplicit()))
17790 StdBadAlloc
= cast
<CXXRecordDecl
>(New
);
17792 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17793 cast_or_null
<RecordDecl
>(PrevDecl
));
17796 if (OOK
!= OOK_Outside
&& TUK
== TUK_Definition
&& !getLangOpts().CPlusPlus
)
17797 Diag(New
->getLocation(), diag::ext_type_defined_in_offsetof
)
17798 << (OOK
== OOK_Macro
) << New
->getSourceRange();
17800 // C++11 [dcl.type]p3:
17801 // A type-specifier-seq shall not define a class or enumeration [...].
17802 if (!Invalid
&& getLangOpts().CPlusPlus
&&
17803 (IsTypeSpecifier
|| IsTemplateParamOrArg
) && TUK
== TUK_Definition
) {
17804 Diag(New
->getLocation(), diag::err_type_defined_in_type_specifier
)
17805 << Context
.getTagDeclType(New
);
17809 if (!Invalid
&& getLangOpts().CPlusPlus
&& TUK
== TUK_Definition
&&
17810 DC
->getDeclKind() == Decl::Enum
) {
17811 Diag(New
->getLocation(), diag::err_type_defined_in_enum
)
17812 << Context
.getTagDeclType(New
);
17816 // Maybe add qualifier info.
17817 if (SS
.isNotEmpty()) {
17819 // If this is either a declaration or a definition, check the
17820 // nested-name-specifier against the current context.
17821 if ((TUK
== TUK_Definition
|| TUK
== TUK_Declaration
) &&
17822 diagnoseQualifiedDeclaration(SS
, DC
, OrigName
, Loc
,
17823 isMemberSpecialization
))
17826 New
->setQualifierInfo(SS
.getWithLocInContext(Context
));
17827 if (TemplateParameterLists
.size() > 0) {
17828 New
->setTemplateParameterListsInfo(Context
, TemplateParameterLists
);
17835 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
17836 // Add alignment attributes if necessary; these attributes are checked when
17837 // the ASTContext lays out the structure.
17839 // It is important for implementing the correct semantics that this
17840 // happen here (in ActOnTag). The #pragma pack stack is
17841 // maintained as a result of parser callbacks which can occur at
17842 // many points during the parsing of a struct declaration (because
17843 // the #pragma tokens are effectively skipped over during the
17844 // parsing of the struct).
17845 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
17846 AddAlignmentAttributesForRecord(RD
);
17847 AddMsStructLayoutForRecord(RD
);
17851 if (ModulePrivateLoc
.isValid()) {
17852 if (isMemberSpecialization
)
17853 Diag(New
->getLocation(), diag::err_module_private_specialization
)
17855 << FixItHint::CreateRemoval(ModulePrivateLoc
);
17856 // __module_private__ does not apply to local classes. However, we only
17857 // diagnose this as an error when the declaration specifiers are
17858 // freestanding. Here, we just ignore the __module_private__.
17859 else if (!SearchDC
->isFunctionOrMethod())
17860 New
->setModulePrivate();
17863 // If this is a specialization of a member class (of a class template),
17864 // check the specialization.
17865 if (isMemberSpecialization
&& CheckMemberSpecialization(New
, Previous
))
17868 // If we're declaring or defining a tag in function prototype scope in C,
17869 // note that this type can only be used within the function and add it to
17870 // the list of decls to inject into the function definition scope.
17871 if ((Name
|| Kind
== TTK_Enum
) &&
17872 getNonFieldDeclScope(S
)->isFunctionPrototypeScope()) {
17873 if (getLangOpts().CPlusPlus
) {
17874 // C++ [dcl.fct]p6:
17875 // Types shall not be defined in return or parameter types.
17876 if (TUK
== TUK_Definition
&& !IsTypeSpecifier
) {
17877 Diag(Loc
, diag::err_type_defined_in_param_type
)
17881 } else if (!PrevDecl
) {
17882 Diag(Loc
, diag::warn_decl_in_param_list
) << Context
.getTagDeclType(New
);
17887 New
->setInvalidDecl();
17889 // Set the lexical context. If the tag has a C++ scope specifier, the
17890 // lexical context will be different from the semantic context.
17891 New
->setLexicalDeclContext(CurContext
);
17893 // Mark this as a friend decl if applicable.
17894 // In Microsoft mode, a friend declaration also acts as a forward
17895 // declaration so we always pass true to setObjectOfFriendDecl to make
17896 // the tag name visible.
17897 if (TUK
== TUK_Friend
)
17898 New
->setObjectOfFriendDecl(getLangOpts().MSVCCompat
);
17900 // Set the access specifier.
17901 if (!Invalid
&& SearchDC
->isRecord())
17902 SetMemberAccessSpecifier(New
, PrevDecl
, AS
);
17905 CheckRedeclarationInModule(New
, PrevDecl
);
17907 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
))
17908 New
->startDefinition();
17910 ProcessDeclAttributeList(S
, New
, Attrs
);
17911 AddPragmaAttributes(S
, New
);
17913 // If this has an identifier, add it to the scope stack.
17914 if (TUK
== TUK_Friend
) {
17915 // We might be replacing an existing declaration in the lookup tables;
17916 // if so, borrow its access specifier.
17918 New
->setAccess(PrevDecl
->getAccess());
17920 DeclContext
*DC
= New
->getDeclContext()->getRedeclContext();
17921 DC
->makeDeclVisibleInContext(New
);
17922 if (Name
) // can be null along some error paths
17923 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
17924 PushOnScopeChains(New
, EnclosingScope
, /* AddToContext = */ false);
17926 S
= getNonFieldDeclScope(S
);
17927 PushOnScopeChains(New
, S
, true);
17929 CurContext
->addDecl(New
);
17932 // If this is the C FILE type, notify the AST context.
17933 if (IdentifierInfo
*II
= New
->getIdentifier())
17934 if (!New
->isInvalidDecl() &&
17935 New
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17937 Context
.setFILEDecl(New
);
17940 mergeDeclAttributes(New
, PrevDecl
);
17942 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(New
))
17943 inferGslOwnerPointerAttribute(CXXRD
);
17945 // If there's a #pragma GCC visibility in scope, set the visibility of this
17947 AddPushedVisibilityAttribute(New
);
17949 if (isMemberSpecialization
&& !New
->isInvalidDecl())
17950 CompleteMemberSpecialization(New
, Previous
);
17953 // In C++, don't return an invalid declaration. We can't recover well from
17954 // the cases where we make the type anonymous.
17955 if (Invalid
&& getLangOpts().CPlusPlus
) {
17956 if (New
->isBeingDefined())
17957 if (auto RD
= dyn_cast
<RecordDecl
>(New
))
17958 RD
->completeDefinition();
17960 } else if (SkipBody
&& SkipBody
->ShouldSkip
) {
17961 return SkipBody
->Previous
;
17967 void Sema::ActOnTagStartDefinition(Scope
*S
, Decl
*TagD
) {
17968 AdjustDeclIfTemplate(TagD
);
17969 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17971 // Enter the tag context.
17972 PushDeclContext(S
, Tag
);
17974 ActOnDocumentableDecl(TagD
);
17976 // If there's a #pragma GCC visibility in scope, set the visibility of this
17978 AddPushedVisibilityAttribute(Tag
);
17981 bool Sema::ActOnDuplicateDefinition(Decl
*Prev
, SkipBodyInfo
&SkipBody
) {
17982 if (!hasStructuralCompatLayout(Prev
, SkipBody
.New
))
17985 // Make the previous decl visible.
17986 makeMergedDefinitionVisible(SkipBody
.Previous
);
17990 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl
*IDecl
) {
17991 assert(IDecl
->getLexicalParent() == CurContext
&&
17992 "The next DeclContext should be lexically contained in the current one.");
17993 CurContext
= IDecl
;
17996 void Sema::ActOnStartCXXMemberDeclarations(Scope
*S
, Decl
*TagD
,
17997 SourceLocation FinalLoc
,
17998 bool IsFinalSpelledSealed
,
18000 SourceLocation LBraceLoc
) {
18001 AdjustDeclIfTemplate(TagD
);
18002 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(TagD
);
18004 FieldCollector
->StartClass();
18006 if (!Record
->getIdentifier())
18010 Record
->markAbstract();
18012 if (FinalLoc
.isValid()) {
18013 Record
->addAttr(FinalAttr::Create(Context
, FinalLoc
,
18014 IsFinalSpelledSealed
18015 ? FinalAttr::Keyword_sealed
18016 : FinalAttr::Keyword_final
));
18019 // [...] The class-name is also inserted into the scope of the
18020 // class itself; this is known as the injected-class-name. For
18021 // purposes of access checking, the injected-class-name is treated
18022 // as if it were a public member name.
18023 CXXRecordDecl
*InjectedClassName
= CXXRecordDecl::Create(
18024 Context
, Record
->getTagKind(), CurContext
, Record
->getBeginLoc(),
18025 Record
->getLocation(), Record
->getIdentifier(),
18026 /*PrevDecl=*/nullptr,
18027 /*DelayTypeCreation=*/true);
18028 Context
.getTypeDeclType(InjectedClassName
, Record
);
18029 InjectedClassName
->setImplicit();
18030 InjectedClassName
->setAccess(AS_public
);
18031 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate())
18032 InjectedClassName
->setDescribedClassTemplate(Template
);
18033 PushOnScopeChains(InjectedClassName
, S
);
18034 assert(InjectedClassName
->isInjectedClassName() &&
18035 "Broken injected-class-name");
18038 void Sema::ActOnTagFinishDefinition(Scope
*S
, Decl
*TagD
,
18039 SourceRange BraceRange
) {
18040 AdjustDeclIfTemplate(TagD
);
18041 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
18042 Tag
->setBraceRange(BraceRange
);
18044 // Make sure we "complete" the definition even it is invalid.
18045 if (Tag
->isBeingDefined()) {
18046 assert(Tag
->isInvalidDecl() && "We should already have completed it");
18047 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
18048 RD
->completeDefinition();
18051 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
18052 FieldCollector
->FinishClass();
18053 if (RD
->hasAttr
<SYCLSpecialClassAttr
>()) {
18054 auto *Def
= RD
->getDefinition();
18055 assert(Def
&& "The record is expected to have a completed definition");
18056 unsigned NumInitMethods
= 0;
18057 for (auto *Method
: Def
->methods()) {
18058 if (!Method
->getIdentifier())
18060 if (Method
->getName() == "__init")
18063 if (NumInitMethods
> 1 || !Def
->hasInitMethod())
18064 Diag(RD
->getLocation(), diag::err_sycl_special_type_num_init_method
);
18068 // Exit this scope of this tag's definition.
18071 if (getCurLexicalContext()->isObjCContainer() &&
18072 Tag
->getDeclContext()->isFileContext())
18073 Tag
->setTopLevelDeclInObjCContainer();
18075 // Notify the consumer that we've defined a tag.
18076 if (!Tag
->isInvalidDecl())
18077 Consumer
.HandleTagDeclDefinition(Tag
);
18079 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18080 // from XLs and instead matches the XL #pragma pack(1) behavior.
18081 if (Context
.getTargetInfo().getTriple().isOSAIX() &&
18082 AlignPackStack
.hasValue()) {
18083 AlignPackInfo APInfo
= AlignPackStack
.CurrentValue
;
18084 // Only diagnose #pragma align(packed).
18085 if (!APInfo
.IsAlignAttr() || APInfo
.getAlignMode() != AlignPackInfo::Packed
)
18087 const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
);
18090 // Only warn if there is at least 1 bitfield member.
18091 if (llvm::any_of(RD
->fields(),
18092 [](const FieldDecl
*FD
) { return FD
->isBitField(); }))
18093 Diag(BraceRange
.getBegin(), diag::warn_pragma_align_not_xl_compatible
);
18097 void Sema::ActOnObjCContainerFinishDefinition() {
18098 // Exit this scope of this interface definition.
18102 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl
*ObjCCtx
) {
18103 assert(ObjCCtx
== CurContext
&& "Mismatch of container contexts");
18104 OriginalLexicalContext
= ObjCCtx
;
18105 ActOnObjCContainerFinishDefinition();
18108 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl
*ObjCCtx
) {
18109 ActOnObjCContainerStartDefinition(ObjCCtx
);
18110 OriginalLexicalContext
= nullptr;
18113 void Sema::ActOnTagDefinitionError(Scope
*S
, Decl
*TagD
) {
18114 AdjustDeclIfTemplate(TagD
);
18115 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
18116 Tag
->setInvalidDecl();
18118 // Make sure we "complete" the definition even it is invalid.
18119 if (Tag
->isBeingDefined()) {
18120 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
18121 RD
->completeDefinition();
18124 // We're undoing ActOnTagStartDefinition here, not
18125 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18126 // the FieldCollector.
18131 // Note that FieldName may be null for anonymous bitfields.
18132 ExprResult
Sema::VerifyBitField(SourceLocation FieldLoc
,
18133 IdentifierInfo
*FieldName
, QualType FieldTy
,
18134 bool IsMsStruct
, Expr
*BitWidth
) {
18136 if (BitWidth
->containsErrors())
18137 return ExprError();
18139 // C99 6.7.2.1p4 - verify the field type.
18140 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18141 if (!FieldTy
->isDependentType() && !FieldTy
->isIntegralOrEnumerationType()) {
18142 // Handle incomplete and sizeless types with a specific error.
18143 if (RequireCompleteSizedType(FieldLoc
, FieldTy
,
18144 diag::err_field_incomplete_or_sizeless
))
18145 return ExprError();
18147 return Diag(FieldLoc
, diag::err_not_integral_type_bitfield
)
18148 << FieldName
<< FieldTy
<< BitWidth
->getSourceRange();
18149 return Diag(FieldLoc
, diag::err_not_integral_type_anon_bitfield
)
18150 << FieldTy
<< BitWidth
->getSourceRange();
18151 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr
*>(BitWidth
),
18152 UPPC_BitFieldWidth
))
18153 return ExprError();
18155 // If the bit-width is type- or value-dependent, don't try to check
18157 if (BitWidth
->isValueDependent() || BitWidth
->isTypeDependent())
18160 llvm::APSInt Value
;
18161 ExprResult ICE
= VerifyIntegerConstantExpression(BitWidth
, &Value
, AllowFold
);
18162 if (ICE
.isInvalid())
18164 BitWidth
= ICE
.get();
18166 // Zero-width bitfield is ok for anonymous field.
18167 if (Value
== 0 && FieldName
)
18168 return Diag(FieldLoc
, diag::err_bitfield_has_zero_width
)
18169 << FieldName
<< BitWidth
->getSourceRange();
18171 if (Value
.isSigned() && Value
.isNegative()) {
18173 return Diag(FieldLoc
, diag::err_bitfield_has_negative_width
)
18174 << FieldName
<< toString(Value
, 10);
18175 return Diag(FieldLoc
, diag::err_anon_bitfield_has_negative_width
)
18176 << toString(Value
, 10);
18179 // The size of the bit-field must not exceed our maximum permitted object
18181 if (Value
.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context
)) {
18182 return Diag(FieldLoc
, diag::err_bitfield_too_wide
)
18183 << !FieldName
<< FieldName
<< toString(Value
, 10);
18186 if (!FieldTy
->isDependentType()) {
18187 uint64_t TypeStorageSize
= Context
.getTypeSize(FieldTy
);
18188 uint64_t TypeWidth
= Context
.getIntWidth(FieldTy
);
18189 bool BitfieldIsOverwide
= Value
.ugt(TypeWidth
);
18191 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18193 bool CStdConstraintViolation
=
18194 BitfieldIsOverwide
&& !getLangOpts().CPlusPlus
;
18195 bool MSBitfieldViolation
=
18196 Value
.ugt(TypeStorageSize
) &&
18197 (IsMsStruct
|| Context
.getTargetInfo().getCXXABI().isMicrosoft());
18198 if (CStdConstraintViolation
|| MSBitfieldViolation
) {
18199 unsigned DiagWidth
=
18200 CStdConstraintViolation
? TypeWidth
: TypeStorageSize
;
18201 return Diag(FieldLoc
, diag::err_bitfield_width_exceeds_type_width
)
18202 << (bool)FieldName
<< FieldName
<< toString(Value
, 10)
18203 << !CStdConstraintViolation
<< DiagWidth
;
18206 // Warn on types where the user might conceivably expect to get all
18207 // specified bits as value bits: that's all integral types other than
18209 if (BitfieldIsOverwide
&& !FieldTy
->isBooleanType() && FieldName
) {
18210 Diag(FieldLoc
, diag::warn_bitfield_width_exceeds_type_width
)
18211 << FieldName
<< toString(Value
, 10)
18212 << (unsigned)TypeWidth
;
18219 /// ActOnField - Each field of a C struct/union is passed into this in order
18220 /// to create a FieldDecl object for it.
18221 Decl
*Sema::ActOnField(Scope
*S
, Decl
*TagD
, SourceLocation DeclStart
,
18222 Declarator
&D
, Expr
*BitfieldWidth
) {
18223 FieldDecl
*Res
= HandleField(S
, cast_if_present
<RecordDecl
>(TagD
), DeclStart
,
18225 /*InitStyle=*/ICIS_NoInit
, AS_public
);
18229 /// HandleField - Analyze a field of a C struct or a C++ data member.
18231 FieldDecl
*Sema::HandleField(Scope
*S
, RecordDecl
*Record
,
18232 SourceLocation DeclStart
,
18233 Declarator
&D
, Expr
*BitWidth
,
18234 InClassInitStyle InitStyle
,
18235 AccessSpecifier AS
) {
18236 if (D
.isDecompositionDeclarator()) {
18237 const DecompositionDeclarator
&Decomp
= D
.getDecompositionDeclarator();
18238 Diag(Decomp
.getLSquareLoc(), diag::err_decomp_decl_context
)
18239 << Decomp
.getSourceRange();
18243 IdentifierInfo
*II
= D
.getIdentifier();
18244 SourceLocation Loc
= DeclStart
;
18245 if (II
) Loc
= D
.getIdentifierLoc();
18247 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
18248 QualType T
= TInfo
->getType();
18249 if (getLangOpts().CPlusPlus
) {
18250 CheckExtraCXXDefaultArguments(D
);
18252 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
18253 UPPC_DataMemberType
)) {
18254 D
.setInvalidType();
18256 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
18260 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
18262 if (D
.getDeclSpec().isInlineSpecified())
18263 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
18264 << getLangOpts().CPlusPlus17
;
18265 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
18266 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
18267 diag::err_invalid_thread
)
18268 << DeclSpec::getSpecifierName(TSCS
);
18270 // Check to see if this name was declared as a member previously
18271 NamedDecl
*PrevDecl
= nullptr;
18272 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
,
18273 ForVisibleRedeclaration
);
18274 LookupName(Previous
, S
);
18275 switch (Previous
.getResultKind()) {
18276 case LookupResult::Found
:
18277 case LookupResult::FoundUnresolvedValue
:
18278 PrevDecl
= Previous
.getAsSingle
<NamedDecl
>();
18281 case LookupResult::FoundOverloaded
:
18282 PrevDecl
= Previous
.getRepresentativeDecl();
18285 case LookupResult::NotFound
:
18286 case LookupResult::NotFoundInCurrentInstantiation
:
18287 case LookupResult::Ambiguous
:
18290 Previous
.suppressDiagnostics();
18292 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
18293 // Maybe we will complain about the shadowed template parameter.
18294 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
18295 // Just pretend that we didn't see the previous declaration.
18296 PrevDecl
= nullptr;
18299 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
18300 PrevDecl
= nullptr;
18303 = (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable
);
18304 SourceLocation TSSL
= D
.getBeginLoc();
18306 = CheckFieldDecl(II
, T
, TInfo
, Record
, Loc
, Mutable
, BitWidth
, InitStyle
,
18307 TSSL
, AS
, PrevDecl
, &D
);
18309 if (NewFD
->isInvalidDecl())
18310 Record
->setInvalidDecl();
18312 if (D
.getDeclSpec().isModulePrivateSpecified())
18313 NewFD
->setModulePrivate();
18315 if (NewFD
->isInvalidDecl() && PrevDecl
) {
18316 // Don't introduce NewFD into scope; there's already something
18317 // with the same name in the same scope.
18319 PushOnScopeChains(NewFD
, S
);
18321 Record
->addDecl(NewFD
);
18326 /// Build a new FieldDecl and check its well-formedness.
18328 /// This routine builds a new FieldDecl given the fields name, type,
18329 /// record, etc. \p PrevDecl should refer to any previous declaration
18330 /// with the same name and in the same scope as the field to be
18333 /// \returns a new FieldDecl.
18335 /// \todo The Declarator argument is a hack. It will be removed once
18336 FieldDecl
*Sema::CheckFieldDecl(DeclarationName Name
, QualType T
,
18337 TypeSourceInfo
*TInfo
,
18338 RecordDecl
*Record
, SourceLocation Loc
,
18339 bool Mutable
, Expr
*BitWidth
,
18340 InClassInitStyle InitStyle
,
18341 SourceLocation TSSL
,
18342 AccessSpecifier AS
, NamedDecl
*PrevDecl
,
18344 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
18345 bool InvalidDecl
= false;
18346 if (D
) InvalidDecl
= D
->isInvalidType();
18348 // If we receive a broken type, recover by assuming 'int' and
18349 // marking this declaration as invalid.
18350 if (T
.isNull() || T
->containsErrors()) {
18351 InvalidDecl
= true;
18355 QualType EltTy
= Context
.getBaseElementType(T
);
18356 if (!EltTy
->isDependentType() && !EltTy
->containsErrors()) {
18357 if (RequireCompleteSizedType(Loc
, EltTy
,
18358 diag::err_field_incomplete_or_sizeless
)) {
18359 // Fields of incomplete type force their record to be invalid.
18360 Record
->setInvalidDecl();
18361 InvalidDecl
= true;
18364 EltTy
->isIncompleteType(&Def
);
18365 if (Def
&& Def
->isInvalidDecl()) {
18366 Record
->setInvalidDecl();
18367 InvalidDecl
= true;
18372 // TR 18037 does not allow fields to be declared with address space
18373 if (T
.hasAddressSpace() || T
->isDependentAddressSpaceType() ||
18374 T
->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18375 Diag(Loc
, diag::err_field_with_address_space
);
18376 Record
->setInvalidDecl();
18377 InvalidDecl
= true;
18380 if (LangOpts
.OpenCL
) {
18381 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18382 // used as structure or union field: image, sampler, event or block types.
18383 if (T
->isEventT() || T
->isImageType() || T
->isSamplerT() ||
18384 T
->isBlockPointerType()) {
18385 Diag(Loc
, diag::err_opencl_type_struct_or_union_field
) << T
;
18386 Record
->setInvalidDecl();
18387 InvalidDecl
= true;
18389 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18391 if (BitWidth
&& !getOpenCLOptions().isAvailableOption(
18392 "__cl_clang_bitfields", LangOpts
)) {
18393 Diag(Loc
, diag::err_opencl_bitfields
);
18394 InvalidDecl
= true;
18398 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18399 if (!InvalidDecl
&& getLangOpts().CPlusPlus
&& !II
&& BitWidth
&&
18400 T
.hasQualifiers()) {
18401 InvalidDecl
= true;
18402 Diag(Loc
, diag::err_anon_bitfield_qualifiers
);
18405 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18406 // than a variably modified type.
18407 if (!InvalidDecl
&& T
->isVariablyModifiedType()) {
18408 if (!tryToFixVariablyModifiedVarType(
18409 TInfo
, T
, Loc
, diag::err_typecheck_field_variable_size
))
18410 InvalidDecl
= true;
18413 // Fields can not have abstract class types
18414 if (!InvalidDecl
&& RequireNonAbstractType(Loc
, T
,
18415 diag::err_abstract_type_in_decl
,
18416 AbstractFieldType
))
18417 InvalidDecl
= true;
18420 BitWidth
= nullptr;
18421 // If this is declared as a bit-field, check the bit-field.
18424 VerifyBitField(Loc
, II
, T
, Record
->isMsStruct(Context
), BitWidth
).get();
18426 InvalidDecl
= true;
18427 BitWidth
= nullptr;
18431 // Check that 'mutable' is consistent with the type of the declaration.
18432 if (!InvalidDecl
&& Mutable
) {
18433 unsigned DiagID
= 0;
18434 if (T
->isReferenceType())
18435 DiagID
= getLangOpts().MSVCCompat
? diag::ext_mutable_reference
18436 : diag::err_mutable_reference
;
18437 else if (T
.isConstQualified())
18438 DiagID
= diag::err_mutable_const
;
18441 SourceLocation ErrLoc
= Loc
;
18442 if (D
&& D
->getDeclSpec().getStorageClassSpecLoc().isValid())
18443 ErrLoc
= D
->getDeclSpec().getStorageClassSpecLoc();
18444 Diag(ErrLoc
, DiagID
);
18445 if (DiagID
!= diag::ext_mutable_reference
) {
18447 InvalidDecl
= true;
18452 // C++11 [class.union]p8 (DR1460):
18453 // At most one variant member of a union may have a
18454 // brace-or-equal-initializer.
18455 if (InitStyle
!= ICIS_NoInit
)
18456 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Record
), Loc
);
18458 FieldDecl
*NewFD
= FieldDecl::Create(Context
, Record
, TSSL
, Loc
, II
, T
, TInfo
,
18459 BitWidth
, Mutable
, InitStyle
);
18461 NewFD
->setInvalidDecl();
18463 if (PrevDecl
&& !isa
<TagDecl
>(PrevDecl
) &&
18464 !PrevDecl
->isPlaceholderVar(getLangOpts())) {
18465 Diag(Loc
, diag::err_duplicate_member
) << II
;
18466 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
18467 NewFD
->setInvalidDecl();
18470 if (!InvalidDecl
&& getLangOpts().CPlusPlus
) {
18471 if (Record
->isUnion()) {
18472 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
18473 CXXRecordDecl
* RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
18474 if (RDecl
->getDefinition()) {
18475 // C++ [class.union]p1: An object of a class with a non-trivial
18476 // constructor, a non-trivial copy constructor, a non-trivial
18477 // destructor, or a non-trivial copy assignment operator
18478 // cannot be a member of a union, nor can an array of such
18480 if (CheckNontrivialField(NewFD
))
18481 NewFD
->setInvalidDecl();
18485 // C++ [class.union]p1: If a union contains a member of reference type,
18486 // the program is ill-formed, except when compiling with MSVC extensions
18488 if (EltTy
->isReferenceType()) {
18489 Diag(NewFD
->getLocation(), getLangOpts().MicrosoftExt
?
18490 diag::ext_union_member_of_reference_type
:
18491 diag::err_union_member_of_reference_type
)
18492 << NewFD
->getDeclName() << EltTy
;
18493 if (!getLangOpts().MicrosoftExt
)
18494 NewFD
->setInvalidDecl();
18499 // FIXME: We need to pass in the attributes given an AST
18500 // representation, not a parser representation.
18502 // FIXME: The current scope is almost... but not entirely... correct here.
18503 ProcessDeclAttributes(getCurScope(), NewFD
, *D
);
18505 if (NewFD
->hasAttrs())
18506 CheckAlignasUnderalignment(NewFD
);
18509 // In auto-retain/release, infer strong retension for fields of
18510 // retainable type.
18511 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewFD
))
18512 NewFD
->setInvalidDecl();
18514 if (T
.isObjCGCWeak())
18515 Diag(Loc
, diag::warn_attribute_weak_on_field
);
18517 // PPC MMA non-pointer types are not allowed as field types.
18518 if (Context
.getTargetInfo().getTriple().isPPC64() &&
18519 CheckPPCMMAType(T
, NewFD
->getLocation()))
18520 NewFD
->setInvalidDecl();
18522 NewFD
->setAccess(AS
);
18526 bool Sema::CheckNontrivialField(FieldDecl
*FD
) {
18528 assert(getLangOpts().CPlusPlus
&& "valid check only for C++");
18530 if (FD
->isInvalidDecl() || FD
->getType()->isDependentType())
18533 QualType EltTy
= Context
.getBaseElementType(FD
->getType());
18534 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
18535 CXXRecordDecl
*RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
18536 if (RDecl
->getDefinition()) {
18537 // We check for copy constructors before constructors
18538 // because otherwise we'll never get complaints about
18539 // copy constructors.
18541 CXXSpecialMember member
= CXXInvalid
;
18542 // We're required to check for any non-trivial constructors. Since the
18543 // implicit default constructor is suppressed if there are any
18544 // user-declared constructors, we just need to check that there is a
18545 // trivial default constructor and a trivial copy constructor. (We don't
18546 // worry about move constructors here, since this is a C++98 check.)
18547 if (RDecl
->hasNonTrivialCopyConstructor())
18548 member
= CXXCopyConstructor
;
18549 else if (!RDecl
->hasTrivialDefaultConstructor())
18550 member
= CXXDefaultConstructor
;
18551 else if (RDecl
->hasNonTrivialCopyAssignment())
18552 member
= CXXCopyAssignment
;
18553 else if (RDecl
->hasNonTrivialDestructor())
18554 member
= CXXDestructor
;
18556 if (member
!= CXXInvalid
) {
18557 if (!getLangOpts().CPlusPlus11
&&
18558 getLangOpts().ObjCAutoRefCount
&& RDecl
->hasObjectMember()) {
18559 // Objective-C++ ARC: it is an error to have a non-trivial field of
18560 // a union. However, system headers in Objective-C programs
18561 // occasionally have Objective-C lifetime objects within unions,
18562 // and rather than cause the program to fail, we make those
18563 // members unavailable.
18564 SourceLocation Loc
= FD
->getLocation();
18565 if (getSourceManager().isInSystemHeader(Loc
)) {
18566 if (!FD
->hasAttr
<UnavailableAttr
>())
18567 FD
->addAttr(UnavailableAttr::CreateImplicit(Context
, "",
18568 UnavailableAttr::IR_ARCFieldWithOwnership
, Loc
));
18573 Diag(FD
->getLocation(), getLangOpts().CPlusPlus11
?
18574 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
:
18575 diag::err_illegal_union_or_anon_struct_member
)
18576 << FD
->getParent()->isUnion() << FD
->getDeclName() << member
;
18577 DiagnoseNontrivial(RDecl
, member
);
18578 return !getLangOpts().CPlusPlus11
;
18586 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18587 /// AST enum value.
18588 static ObjCIvarDecl::AccessControl
18589 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility
) {
18590 switch (ivarVisibility
) {
18591 default: llvm_unreachable("Unknown visitibility kind");
18592 case tok::objc_private
: return ObjCIvarDecl::Private
;
18593 case tok::objc_public
: return ObjCIvarDecl::Public
;
18594 case tok::objc_protected
: return ObjCIvarDecl::Protected
;
18595 case tok::objc_package
: return ObjCIvarDecl::Package
;
18599 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18600 /// in order to create an IvarDecl object for it.
18601 Decl
*Sema::ActOnIvar(Scope
*S
, SourceLocation DeclStart
, Declarator
&D
,
18602 Expr
*BitWidth
, tok::ObjCKeywordKind Visibility
) {
18604 IdentifierInfo
*II
= D
.getIdentifier();
18605 SourceLocation Loc
= DeclStart
;
18606 if (II
) Loc
= D
.getIdentifierLoc();
18608 // FIXME: Unnamed fields can be handled in various different ways, for
18609 // example, unnamed unions inject all members into the struct namespace!
18611 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
18612 QualType T
= TInfo
->getType();
18615 // 6.7.2.1p3, 6.7.2.1p4
18616 BitWidth
= VerifyBitField(Loc
, II
, T
, /*IsMsStruct*/false, BitWidth
).get();
18618 D
.setInvalidType();
18625 if (T
->isReferenceType()) {
18626 Diag(Loc
, diag::err_ivar_reference_type
);
18627 D
.setInvalidType();
18629 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18630 // than a variably modified type.
18631 else if (T
->isVariablyModifiedType()) {
18632 if (!tryToFixVariablyModifiedVarType(
18633 TInfo
, T
, Loc
, diag::err_typecheck_ivar_variable_size
))
18634 D
.setInvalidType();
18637 // Get the visibility (access control) for this ivar.
18638 ObjCIvarDecl::AccessControl ac
=
18639 Visibility
!= tok::objc_not_keyword
? TranslateIvarVisibility(Visibility
)
18640 : ObjCIvarDecl::None
;
18641 // Must set ivar's DeclContext to its enclosing interface.
18642 ObjCContainerDecl
*EnclosingDecl
= cast
<ObjCContainerDecl
>(CurContext
);
18643 if (!EnclosingDecl
|| EnclosingDecl
->isInvalidDecl())
18645 ObjCContainerDecl
*EnclosingContext
;
18646 if (ObjCImplementationDecl
*IMPDecl
=
18647 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
18648 if (LangOpts
.ObjCRuntime
.isFragile()) {
18649 // Case of ivar declared in an implementation. Context is that of its class.
18650 EnclosingContext
= IMPDecl
->getClassInterface();
18651 assert(EnclosingContext
&& "Implementation has no class interface!");
18654 EnclosingContext
= EnclosingDecl
;
18656 if (ObjCCategoryDecl
*CDecl
=
18657 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
18658 if (LangOpts
.ObjCRuntime
.isFragile() || !CDecl
->IsClassExtension()) {
18659 Diag(Loc
, diag::err_misplaced_ivar
) << CDecl
->IsClassExtension();
18663 EnclosingContext
= EnclosingDecl
;
18666 // Construct the decl.
18667 ObjCIvarDecl
*NewID
= ObjCIvarDecl::Create(
18668 Context
, EnclosingContext
, DeclStart
, Loc
, II
, T
, TInfo
, ac
, BitWidth
);
18670 if (T
->containsErrors())
18671 NewID
->setInvalidDecl();
18674 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, Loc
, LookupMemberName
,
18675 ForVisibleRedeclaration
);
18676 if (PrevDecl
&& isDeclInScope(PrevDecl
, EnclosingContext
, S
)
18677 && !isa
<TagDecl
>(PrevDecl
)) {
18678 Diag(Loc
, diag::err_duplicate_member
) << II
;
18679 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
18680 NewID
->setInvalidDecl();
18684 // Process attributes attached to the ivar.
18685 ProcessDeclAttributes(S
, NewID
, D
);
18687 if (D
.isInvalidType())
18688 NewID
->setInvalidDecl();
18690 // In ARC, infer 'retaining' for ivars of retainable type.
18691 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewID
))
18692 NewID
->setInvalidDecl();
18694 if (D
.getDeclSpec().isModulePrivateSpecified())
18695 NewID
->setModulePrivate();
18698 // FIXME: When interfaces are DeclContexts, we'll need to add
18699 // these to the interface.
18701 IdResolver
.AddDecl(NewID
);
18704 if (LangOpts
.ObjCRuntime
.isNonFragile() &&
18705 !NewID
->isInvalidDecl() && isa
<ObjCInterfaceDecl
>(EnclosingDecl
))
18706 Diag(Loc
, diag::warn_ivars_in_interface
);
18711 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18712 /// class and class extensions. For every class \@interface and class
18713 /// extension \@interface, if the last ivar is a bitfield of any type,
18714 /// then add an implicit `char :0` ivar to the end of that interface.
18715 void Sema::ActOnLastBitfield(SourceLocation DeclLoc
,
18716 SmallVectorImpl
<Decl
*> &AllIvarDecls
) {
18717 if (LangOpts
.ObjCRuntime
.isFragile() || AllIvarDecls
.empty())
18720 Decl
*ivarDecl
= AllIvarDecls
[AllIvarDecls
.size()-1];
18721 ObjCIvarDecl
*Ivar
= cast
<ObjCIvarDecl
>(ivarDecl
);
18723 if (!Ivar
->isBitField() || Ivar
->isZeroLengthBitField(Context
))
18725 ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(CurContext
);
18727 if (ObjCCategoryDecl
*CD
= dyn_cast
<ObjCCategoryDecl
>(CurContext
)) {
18728 if (!CD
->IsClassExtension())
18731 // No need to add this to end of @implementation.
18735 // All conditions are met. Add a new bitfield to the tail end of ivars.
18736 llvm::APInt
Zero(Context
.getTypeSize(Context
.IntTy
), 0);
18737 Expr
* BW
= IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
, DeclLoc
);
18739 Ivar
= ObjCIvarDecl::Create(Context
, cast
<ObjCContainerDecl
>(CurContext
),
18740 DeclLoc
, DeclLoc
, nullptr,
18742 Context
.getTrivialTypeSourceInfo(Context
.CharTy
,
18744 ObjCIvarDecl::Private
, BW
,
18746 AllIvarDecls
.push_back(Ivar
);
18749 /// [class.dtor]p4:
18750 /// At the end of the definition of a class, overload resolution is
18751 /// performed among the prospective destructors declared in that class with
18752 /// an empty argument list to select the destructor for the class, also
18753 /// known as the selected destructor.
18755 /// We do the overload resolution here, then mark the selected constructor in the AST.
18756 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18757 static void ComputeSelectedDestructor(Sema
&S
, CXXRecordDecl
*Record
) {
18758 if (!Record
->hasUserDeclaredDestructor()) {
18762 SourceLocation Loc
= Record
->getLocation();
18763 OverloadCandidateSet
OCS(Loc
, OverloadCandidateSet::CSK_Normal
);
18765 for (auto *Decl
: Record
->decls()) {
18766 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(Decl
)) {
18767 if (DD
->isInvalidDecl())
18769 S
.AddOverloadCandidate(DD
, DeclAccessPair::make(DD
, DD
->getAccess()), {},
18771 assert(DD
->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18778 OverloadCandidateSet::iterator Best
;
18780 OverloadCandidateDisplayKind DisplayKind
;
18782 switch (OCS
.BestViableFunction(S
, Loc
, Best
)) {
18785 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(Best
->Function
));
18789 Msg
= diag::err_ambiguous_destructor
;
18790 DisplayKind
= OCD_AmbiguousCandidates
;
18793 case OR_No_Viable_Function
:
18794 Msg
= diag::err_no_viable_destructor
;
18795 DisplayKind
= OCD_AllCandidates
;
18800 // OpenCL have got their own thing going with destructors. It's slightly broken,
18801 // but we allow it.
18802 if (!S
.LangOpts
.OpenCL
) {
18803 PartialDiagnostic Diag
= S
.PDiag(Msg
) << Record
;
18804 OCS
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
, DisplayKind
, {});
18805 Record
->setInvalidDecl();
18807 // It's a bit hacky: At this point we've raised an error but we want the
18808 // rest of the compiler to continue somehow working. However almost
18809 // everything we'll try to do with the class will depend on there being a
18810 // destructor. So let's pretend the first one is selected and hope for the
18812 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(OCS
.begin()->Function
));
18816 /// [class.mem.special]p5
18817 /// Two special member functions are of the same kind if:
18818 /// - they are both default constructors,
18819 /// - they are both copy or move constructors with the same first parameter
18821 /// - they are both copy or move assignment operators with the same first
18822 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18823 static bool AreSpecialMemberFunctionsSameKind(ASTContext
&Context
,
18826 Sema::CXXSpecialMember CSM
) {
18827 // We don't want to compare templates to non-templates: See
18828 // https://github.com/llvm/llvm-project/issues/59206
18829 if (CSM
== Sema::CXXDefaultConstructor
)
18830 return bool(M1
->getDescribedFunctionTemplate()) ==
18831 bool(M2
->getDescribedFunctionTemplate());
18832 // FIXME: better resolve CWG
18833 // https://cplusplus.github.io/CWG/issues/2787.html
18834 if (!Context
.hasSameType(M1
->getNonObjectParameter(0)->getType(),
18835 M2
->getNonObjectParameter(0)->getType()))
18837 if (!Context
.hasSameType(M1
->getFunctionObjectParameterReferenceType(),
18838 M2
->getFunctionObjectParameterReferenceType()))
18844 /// [class.mem.special]p6:
18845 /// An eligible special member function is a special member function for which:
18846 /// - the function is not deleted,
18847 /// - the associated constraints, if any, are satisfied, and
18848 /// - no special member function of the same kind whose associated constraints
18849 /// [CWG2595], if any, are satisfied is more constrained.
18850 static void SetEligibleMethods(Sema
&S
, CXXRecordDecl
*Record
,
18851 ArrayRef
<CXXMethodDecl
*> Methods
,
18852 Sema::CXXSpecialMember CSM
) {
18853 SmallVector
<bool, 4> SatisfactionStatus
;
18855 for (CXXMethodDecl
*Method
: Methods
) {
18856 const Expr
*Constraints
= Method
->getTrailingRequiresClause();
18858 SatisfactionStatus
.push_back(true);
18860 ConstraintSatisfaction Satisfaction
;
18861 if (S
.CheckFunctionConstraints(Method
, Satisfaction
))
18862 SatisfactionStatus
.push_back(false);
18864 SatisfactionStatus
.push_back(Satisfaction
.IsSatisfied
);
18868 for (size_t i
= 0; i
< Methods
.size(); i
++) {
18869 if (!SatisfactionStatus
[i
])
18871 CXXMethodDecl
*Method
= Methods
[i
];
18872 CXXMethodDecl
*OrigMethod
= Method
;
18873 if (FunctionDecl
*MF
= OrigMethod
->getInstantiatedFromMemberFunction())
18874 OrigMethod
= cast
<CXXMethodDecl
>(MF
);
18876 const Expr
*Constraints
= OrigMethod
->getTrailingRequiresClause();
18877 bool AnotherMethodIsMoreConstrained
= false;
18878 for (size_t j
= 0; j
< Methods
.size(); j
++) {
18879 if (i
== j
|| !SatisfactionStatus
[j
])
18881 CXXMethodDecl
*OtherMethod
= Methods
[j
];
18882 if (FunctionDecl
*MF
= OtherMethod
->getInstantiatedFromMemberFunction())
18883 OtherMethod
= cast
<CXXMethodDecl
>(MF
);
18885 if (!AreSpecialMemberFunctionsSameKind(S
.Context
, OrigMethod
, OtherMethod
,
18889 const Expr
*OtherConstraints
= OtherMethod
->getTrailingRequiresClause();
18890 if (!OtherConstraints
)
18892 if (!Constraints
) {
18893 AnotherMethodIsMoreConstrained
= true;
18896 if (S
.IsAtLeastAsConstrained(OtherMethod
, {OtherConstraints
}, OrigMethod
,
18898 AnotherMethodIsMoreConstrained
)) {
18899 // There was an error with the constraints comparison. Exit the loop
18900 // and don't consider this function eligible.
18901 AnotherMethodIsMoreConstrained
= true;
18903 if (AnotherMethodIsMoreConstrained
)
18906 // FIXME: Do not consider deleted methods as eligible after implementing
18907 // DR1734 and DR1496.
18908 if (!AnotherMethodIsMoreConstrained
) {
18909 Method
->setIneligibleOrNotSelected(false);
18910 Record
->addedEligibleSpecialMemberFunction(Method
, 1 << CSM
);
18915 static void ComputeSpecialMemberFunctionsEligiblity(Sema
&S
,
18916 CXXRecordDecl
*Record
) {
18917 SmallVector
<CXXMethodDecl
*, 4> DefaultConstructors
;
18918 SmallVector
<CXXMethodDecl
*, 4> CopyConstructors
;
18919 SmallVector
<CXXMethodDecl
*, 4> MoveConstructors
;
18920 SmallVector
<CXXMethodDecl
*, 4> CopyAssignmentOperators
;
18921 SmallVector
<CXXMethodDecl
*, 4> MoveAssignmentOperators
;
18923 for (auto *Decl
: Record
->decls()) {
18924 auto *MD
= dyn_cast
<CXXMethodDecl
>(Decl
);
18926 auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(Decl
);
18928 MD
= dyn_cast
<CXXMethodDecl
>(FTD
->getTemplatedDecl());
18932 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
18933 if (CD
->isInvalidDecl())
18935 if (CD
->isDefaultConstructor())
18936 DefaultConstructors
.push_back(MD
);
18937 else if (CD
->isCopyConstructor())
18938 CopyConstructors
.push_back(MD
);
18939 else if (CD
->isMoveConstructor())
18940 MoveConstructors
.push_back(MD
);
18941 } else if (MD
->isCopyAssignmentOperator()) {
18942 CopyAssignmentOperators
.push_back(MD
);
18943 } else if (MD
->isMoveAssignmentOperator()) {
18944 MoveAssignmentOperators
.push_back(MD
);
18948 SetEligibleMethods(S
, Record
, DefaultConstructors
,
18949 Sema::CXXDefaultConstructor
);
18950 SetEligibleMethods(S
, Record
, CopyConstructors
, Sema::CXXCopyConstructor
);
18951 SetEligibleMethods(S
, Record
, MoveConstructors
, Sema::CXXMoveConstructor
);
18952 SetEligibleMethods(S
, Record
, CopyAssignmentOperators
,
18953 Sema::CXXCopyAssignment
);
18954 SetEligibleMethods(S
, Record
, MoveAssignmentOperators
,
18955 Sema::CXXMoveAssignment
);
18958 void Sema::ActOnFields(Scope
*S
, SourceLocation RecLoc
, Decl
*EnclosingDecl
,
18959 ArrayRef
<Decl
*> Fields
, SourceLocation LBrac
,
18960 SourceLocation RBrac
,
18961 const ParsedAttributesView
&Attrs
) {
18962 assert(EnclosingDecl
&& "missing record or interface decl");
18964 // If this is an Objective-C @implementation or category and we have
18965 // new fields here we should reset the layout of the interface since
18966 // it will now change.
18967 if (!Fields
.empty() && isa
<ObjCContainerDecl
>(EnclosingDecl
)) {
18968 ObjCContainerDecl
*DC
= cast
<ObjCContainerDecl
>(EnclosingDecl
);
18969 switch (DC
->getKind()) {
18971 case Decl::ObjCCategory
:
18972 Context
.ResetObjCLayout(cast
<ObjCCategoryDecl
>(DC
)->getClassInterface());
18974 case Decl::ObjCImplementation
:
18976 ResetObjCLayout(cast
<ObjCImplementationDecl
>(DC
)->getClassInterface());
18981 RecordDecl
*Record
= dyn_cast
<RecordDecl
>(EnclosingDecl
);
18982 CXXRecordDecl
*CXXRecord
= dyn_cast
<CXXRecordDecl
>(EnclosingDecl
);
18984 // Start counting up the number of named members; make sure to include
18985 // members of anonymous structs and unions in the total.
18986 unsigned NumNamedMembers
= 0;
18988 for (const auto *I
: Record
->decls()) {
18989 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
18990 if (IFD
->getDeclName())
18995 // Verify that all the fields are okay.
18996 SmallVector
<FieldDecl
*, 32> RecFields
;
18998 for (ArrayRef
<Decl
*>::iterator i
= Fields
.begin(), end
= Fields
.end();
19000 FieldDecl
*FD
= cast
<FieldDecl
>(*i
);
19002 // Get the type for the field.
19003 const Type
*FDTy
= FD
->getType().getTypePtr();
19005 if (!FD
->isAnonymousStructOrUnion()) {
19006 // Remember all fields written by the user.
19007 RecFields
.push_back(FD
);
19010 // If the field is already invalid for some reason, don't emit more
19011 // diagnostics about it.
19012 if (FD
->isInvalidDecl()) {
19013 EnclosingDecl
->setInvalidDecl();
19018 // A structure or union shall not contain a member with
19019 // incomplete or function type (hence, a structure shall not
19020 // contain an instance of itself, but may contain a pointer to
19021 // an instance of itself), except that the last member of a
19022 // structure with more than one named member may have incomplete
19023 // array type; such a structure (and any union containing,
19024 // possibly recursively, a member that is such a structure)
19025 // shall not be a member of a structure or an element of an
19027 bool IsLastField
= (i
+ 1 == Fields
.end());
19028 if (FDTy
->isFunctionType()) {
19029 // Field declared as a function.
19030 Diag(FD
->getLocation(), diag::err_field_declared_as_function
)
19031 << FD
->getDeclName();
19032 FD
->setInvalidDecl();
19033 EnclosingDecl
->setInvalidDecl();
19035 } else if (FDTy
->isIncompleteArrayType() &&
19036 (Record
|| isa
<ObjCContainerDecl
>(EnclosingDecl
))) {
19038 // Flexible array member.
19039 // Microsoft and g++ is more permissive regarding flexible array.
19040 // It will accept flexible array in union and also
19041 // as the sole element of a struct/class.
19042 unsigned DiagID
= 0;
19043 if (!Record
->isUnion() && !IsLastField
) {
19044 Diag(FD
->getLocation(), diag::err_flexible_array_not_at_end
)
19045 << FD
->getDeclName() << FD
->getType() << Record
->getTagKind();
19046 Diag((*(i
+ 1))->getLocation(), diag::note_next_field_declaration
);
19047 FD
->setInvalidDecl();
19048 EnclosingDecl
->setInvalidDecl();
19050 } else if (Record
->isUnion())
19051 DiagID
= getLangOpts().MicrosoftExt
19052 ? diag::ext_flexible_array_union_ms
19053 : getLangOpts().CPlusPlus
19054 ? diag::ext_flexible_array_union_gnu
19055 : diag::err_flexible_array_union
;
19056 else if (NumNamedMembers
< 1)
19057 DiagID
= getLangOpts().MicrosoftExt
19058 ? diag::ext_flexible_array_empty_aggregate_ms
19059 : getLangOpts().CPlusPlus
19060 ? diag::ext_flexible_array_empty_aggregate_gnu
19061 : diag::err_flexible_array_empty_aggregate
;
19064 Diag(FD
->getLocation(), DiagID
) << FD
->getDeclName()
19065 << Record
->getTagKind();
19066 // While the layout of types that contain virtual bases is not specified
19067 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19068 // virtual bases after the derived members. This would make a flexible
19069 // array member declared at the end of an object not adjacent to the end
19071 if (CXXRecord
&& CXXRecord
->getNumVBases() != 0)
19072 Diag(FD
->getLocation(), diag::err_flexible_array_virtual_base
)
19073 << FD
->getDeclName() << Record
->getTagKind();
19074 if (!getLangOpts().C99
)
19075 Diag(FD
->getLocation(), diag::ext_c99_flexible_array_member
)
19076 << FD
->getDeclName() << Record
->getTagKind();
19078 // If the element type has a non-trivial destructor, we would not
19079 // implicitly destroy the elements, so disallow it for now.
19081 // FIXME: GCC allows this. We should probably either implicitly delete
19082 // the destructor of the containing class, or just allow this.
19083 QualType BaseElem
= Context
.getBaseElementType(FD
->getType());
19084 if (!BaseElem
->isDependentType() && BaseElem
.isDestructedType()) {
19085 Diag(FD
->getLocation(), diag::err_flexible_array_has_nontrivial_dtor
)
19086 << FD
->getDeclName() << FD
->getType();
19087 FD
->setInvalidDecl();
19088 EnclosingDecl
->setInvalidDecl();
19091 // Okay, we have a legal flexible array member at the end of the struct.
19092 Record
->setHasFlexibleArrayMember(true);
19094 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19095 // unless they are followed by another ivar. That check is done
19096 // elsewhere, after synthesized ivars are known.
19098 } else if (!FDTy
->isDependentType() &&
19099 RequireCompleteSizedType(
19100 FD
->getLocation(), FD
->getType(),
19101 diag::err_field_incomplete_or_sizeless
)) {
19103 FD
->setInvalidDecl();
19104 EnclosingDecl
->setInvalidDecl();
19106 } else if (const RecordType
*FDTTy
= FDTy
->getAs
<RecordType
>()) {
19107 if (Record
&& FDTTy
->getDecl()->hasFlexibleArrayMember()) {
19108 // A type which contains a flexible array member is considered to be a
19109 // flexible array member.
19110 Record
->setHasFlexibleArrayMember(true);
19111 if (!Record
->isUnion()) {
19112 // If this is a struct/class and this is not the last element, reject
19113 // it. Note that GCC supports variable sized arrays in the middle of
19116 Diag(FD
->getLocation(), diag::ext_variable_sized_type_in_struct
)
19117 << FD
->getDeclName() << FD
->getType();
19119 // We support flexible arrays at the end of structs in
19120 // other structs as an extension.
19121 Diag(FD
->getLocation(), diag::ext_flexible_array_in_struct
)
19122 << FD
->getDeclName();
19126 if (isa
<ObjCContainerDecl
>(EnclosingDecl
) &&
19127 RequireNonAbstractType(FD
->getLocation(), FD
->getType(),
19128 diag::err_abstract_type_in_decl
,
19129 AbstractIvarType
)) {
19130 // Ivars can not have abstract class types
19131 FD
->setInvalidDecl();
19133 if (Record
&& FDTTy
->getDecl()->hasObjectMember())
19134 Record
->setHasObjectMember(true);
19135 if (Record
&& FDTTy
->getDecl()->hasVolatileMember())
19136 Record
->setHasVolatileMember(true);
19137 } else if (FDTy
->isObjCObjectType()) {
19138 /// A field cannot be an Objective-c object
19139 Diag(FD
->getLocation(), diag::err_statically_allocated_object
)
19140 << FixItHint::CreateInsertion(FD
->getLocation(), "*");
19141 QualType T
= Context
.getObjCObjectPointerType(FD
->getType());
19143 } else if (Record
&& Record
->isUnion() &&
19144 FD
->getType().hasNonTrivialObjCLifetime() &&
19145 getSourceManager().isInSystemHeader(FD
->getLocation()) &&
19146 !getLangOpts().CPlusPlus
&& !FD
->hasAttr
<UnavailableAttr
>() &&
19147 (FD
->getType().getObjCLifetime() != Qualifiers::OCL_Strong
||
19148 !Context
.hasDirectOwnershipQualifier(FD
->getType()))) {
19149 // For backward compatibility, fields of C unions declared in system
19150 // headers that have non-trivial ObjC ownership qualifications are marked
19151 // as unavailable unless the qualifier is explicit and __strong. This can
19152 // break ABI compatibility between programs compiled with ARC and MRR, but
19153 // is a better option than rejecting programs using those unions under
19155 FD
->addAttr(UnavailableAttr::CreateImplicit(
19156 Context
, "", UnavailableAttr::IR_ARCFieldWithOwnership
,
19157 FD
->getLocation()));
19158 } else if (getLangOpts().ObjC
&&
19159 getLangOpts().getGC() != LangOptions::NonGC
&& Record
&&
19160 !Record
->hasObjectMember()) {
19161 if (FD
->getType()->isObjCObjectPointerType() ||
19162 FD
->getType().isObjCGCStrong())
19163 Record
->setHasObjectMember(true);
19164 else if (Context
.getAsArrayType(FD
->getType())) {
19165 QualType BaseType
= Context
.getBaseElementType(FD
->getType());
19166 if (BaseType
->isRecordType() &&
19167 BaseType
->castAs
<RecordType
>()->getDecl()->hasObjectMember())
19168 Record
->setHasObjectMember(true);
19169 else if (BaseType
->isObjCObjectPointerType() ||
19170 BaseType
.isObjCGCStrong())
19171 Record
->setHasObjectMember(true);
19175 if (Record
&& !getLangOpts().CPlusPlus
&&
19176 !shouldIgnoreForRecordTriviality(FD
)) {
19177 QualType FT
= FD
->getType();
19178 if (FT
.isNonTrivialToPrimitiveDefaultInitialize()) {
19179 Record
->setNonTrivialToPrimitiveDefaultInitialize(true);
19180 if (FT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19182 Record
->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19184 QualType::PrimitiveCopyKind PCK
= FT
.isNonTrivialToPrimitiveCopy();
19185 if (PCK
!= QualType::PCK_Trivial
&& PCK
!= QualType::PCK_VolatileTrivial
) {
19186 Record
->setNonTrivialToPrimitiveCopy(true);
19187 if (FT
.hasNonTrivialToPrimitiveCopyCUnion() || Record
->isUnion())
19188 Record
->setHasNonTrivialToPrimitiveCopyCUnion(true);
19190 if (FT
.isDestructedType()) {
19191 Record
->setNonTrivialToPrimitiveDestroy(true);
19192 Record
->setParamDestroyedInCallee(true);
19193 if (FT
.hasNonTrivialToPrimitiveDestructCUnion() || Record
->isUnion())
19194 Record
->setHasNonTrivialToPrimitiveDestructCUnion(true);
19197 if (const auto *RT
= FT
->getAs
<RecordType
>()) {
19198 if (RT
->getDecl()->getArgPassingRestrictions() ==
19199 RecordArgPassingKind::CanNeverPassInRegs
)
19200 Record
->setArgPassingRestrictions(
19201 RecordArgPassingKind::CanNeverPassInRegs
);
19202 } else if (FT
.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak
)
19203 Record
->setArgPassingRestrictions(
19204 RecordArgPassingKind::CanNeverPassInRegs
);
19207 if (Record
&& FD
->getType().isVolatileQualified())
19208 Record
->setHasVolatileMember(true);
19209 // Keep track of the number of named members.
19210 if (FD
->getIdentifier())
19214 // Okay, we successfully defined 'Record'.
19216 bool Completed
= false;
19218 if (!CXXRecord
->isInvalidDecl()) {
19219 // Set access bits correctly on the directly-declared conversions.
19220 for (CXXRecordDecl::conversion_iterator
19221 I
= CXXRecord
->conversion_begin(),
19222 E
= CXXRecord
->conversion_end(); I
!= E
; ++I
)
19223 I
.setAccess((*I
)->getAccess());
19226 // Add any implicitly-declared members to this class.
19227 AddImplicitlyDeclaredMembersToClass(CXXRecord
);
19229 if (!CXXRecord
->isDependentType()) {
19230 if (!CXXRecord
->isInvalidDecl()) {
19231 // If we have virtual base classes, we may end up finding multiple
19232 // final overriders for a given virtual function. Check for this
19234 if (CXXRecord
->getNumVBases()) {
19235 CXXFinalOverriderMap FinalOverriders
;
19236 CXXRecord
->getFinalOverriders(FinalOverriders
);
19238 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
19239 MEnd
= FinalOverriders
.end();
19241 for (OverridingMethods::iterator SO
= M
->second
.begin(),
19242 SOEnd
= M
->second
.end();
19243 SO
!= SOEnd
; ++SO
) {
19244 assert(SO
->second
.size() > 0 &&
19245 "Virtual function without overriding functions?");
19246 if (SO
->second
.size() == 1)
19249 // C++ [class.virtual]p2:
19250 // In a derived class, if a virtual member function of a base
19251 // class subobject has more than one final overrider the
19252 // program is ill-formed.
19253 Diag(Record
->getLocation(), diag::err_multiple_final_overriders
)
19254 << (const NamedDecl
*)M
->first
<< Record
;
19255 Diag(M
->first
->getLocation(),
19256 diag::note_overridden_virtual_function
);
19257 for (OverridingMethods::overriding_iterator
19258 OM
= SO
->second
.begin(),
19259 OMEnd
= SO
->second
.end();
19261 Diag(OM
->Method
->getLocation(), diag::note_final_overrider
)
19262 << (const NamedDecl
*)M
->first
<< OM
->Method
->getParent();
19264 Record
->setInvalidDecl();
19267 CXXRecord
->completeDefinition(&FinalOverriders
);
19271 ComputeSelectedDestructor(*this, CXXRecord
);
19272 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord
);
19277 Record
->completeDefinition();
19279 // Handle attributes before checking the layout.
19280 ProcessDeclAttributeList(S
, Record
, Attrs
);
19282 // Check to see if a FieldDecl is a pointer to a function.
19283 auto IsFunctionPointerOrForwardDecl
= [&](const Decl
*D
) {
19284 const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
19286 // Check whether this is a forward declaration that was inserted by
19287 // Clang. This happens when a non-forward declared / defined type is
19291 // struct bar *(*f)();
19292 // struct bar *(*g)();
19295 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19296 // incomplete definition.
19297 if (const auto *TD
= dyn_cast
<TagDecl
>(D
))
19298 return !TD
->isCompleteDefinition();
19301 QualType FieldType
= FD
->getType().getDesugaredType(Context
);
19302 if (isa
<PointerType
>(FieldType
)) {
19303 QualType PointeeType
= cast
<PointerType
>(FieldType
)->getPointeeType();
19304 return PointeeType
.getDesugaredType(Context
)->isFunctionType();
19309 // Maybe randomize the record's decls. We automatically randomize a record
19310 // of function pointers, unless it has the "no_randomize_layout" attribute.
19311 if (!getLangOpts().CPlusPlus
&&
19312 (Record
->hasAttr
<RandomizeLayoutAttr
>() ||
19313 (!Record
->hasAttr
<NoRandomizeLayoutAttr
>() &&
19314 llvm::all_of(Record
->decls(), IsFunctionPointerOrForwardDecl
))) &&
19315 !Record
->isUnion() && !getLangOpts().RandstructSeed
.empty() &&
19316 !Record
->isRandomized()) {
19317 SmallVector
<Decl
*, 32> NewDeclOrdering
;
19318 if (randstruct::randomizeStructureLayout(Context
, Record
,
19320 Record
->reorderDecls(NewDeclOrdering
);
19323 // We may have deferred checking for a deleted destructor. Check now.
19325 auto *Dtor
= CXXRecord
->getDestructor();
19326 if (Dtor
&& Dtor
->isImplicit() &&
19327 ShouldDeleteSpecialMember(Dtor
, CXXDestructor
)) {
19328 CXXRecord
->setImplicitDestructorIsDeleted();
19329 SetDeclDeleted(Dtor
, CXXRecord
->getLocation());
19333 if (Record
->hasAttrs()) {
19334 CheckAlignasUnderalignment(Record
);
19336 if (const MSInheritanceAttr
*IA
= Record
->getAttr
<MSInheritanceAttr
>())
19337 checkMSInheritanceAttrOnDefinition(cast
<CXXRecordDecl
>(Record
),
19338 IA
->getRange(), IA
->getBestCase(),
19339 IA
->getInheritanceModel());
19342 // Check if the structure/union declaration is a type that can have zero
19343 // size in C. For C this is a language extension, for C++ it may cause
19344 // compatibility problems.
19345 bool CheckForZeroSize
;
19346 if (!getLangOpts().CPlusPlus
) {
19347 CheckForZeroSize
= true;
19349 // For C++ filter out types that cannot be referenced in C code.
19350 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
);
19352 CXXRecord
->getLexicalDeclContext()->isExternCContext() &&
19353 !CXXRecord
->isDependentType() && !inTemplateInstantiation() &&
19354 CXXRecord
->isCLike();
19356 if (CheckForZeroSize
) {
19357 bool ZeroSize
= true;
19358 bool IsEmpty
= true;
19359 unsigned NonBitFields
= 0;
19360 for (RecordDecl::field_iterator I
= Record
->field_begin(),
19361 E
= Record
->field_end();
19362 (NonBitFields
== 0 || ZeroSize
) && I
!= E
; ++I
) {
19364 if (I
->isUnnamedBitfield()) {
19365 if (!I
->isZeroLengthBitField(Context
))
19369 QualType FieldType
= I
->getType();
19370 if (FieldType
->isIncompleteType() ||
19371 !Context
.getTypeSizeInChars(FieldType
).isZero())
19376 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19377 // allowed in C++, but warn if its declaration is inside
19378 // extern "C" block.
19380 Diag(RecLoc
, getLangOpts().CPlusPlus
?
19381 diag::warn_zero_size_struct_union_in_extern_c
:
19382 diag::warn_zero_size_struct_union_compat
)
19383 << IsEmpty
<< Record
->isUnion() << (NonBitFields
> 1);
19386 // Structs without named members are extension in C (C99 6.7.2.1p7),
19387 // but are accepted by GCC.
19388 if (NonBitFields
== 0 && !getLangOpts().CPlusPlus
) {
19389 Diag(RecLoc
, IsEmpty
? diag::ext_empty_struct_union
:
19390 diag::ext_no_named_members_in_struct_union
)
19391 << Record
->isUnion();
19395 ObjCIvarDecl
**ClsFields
=
19396 reinterpret_cast<ObjCIvarDecl
**>(RecFields
.data());
19397 if (ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(EnclosingDecl
)) {
19398 ID
->setEndOfDefinitionLoc(RBrac
);
19399 // Add ivar's to class's DeclContext.
19400 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
19401 ClsFields
[i
]->setLexicalDeclContext(ID
);
19402 ID
->addDecl(ClsFields
[i
]);
19404 // Must enforce the rule that ivars in the base classes may not be
19406 if (ID
->getSuperClass())
19407 DiagnoseDuplicateIvars(ID
, ID
->getSuperClass());
19408 } else if (ObjCImplementationDecl
*IMPDecl
=
19409 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
19410 assert(IMPDecl
&& "ActOnFields - missing ObjCImplementationDecl");
19411 for (unsigned I
= 0, N
= RecFields
.size(); I
!= N
; ++I
)
19412 // Ivar declared in @implementation never belongs to the implementation.
19413 // Only it is in implementation's lexical context.
19414 ClsFields
[I
]->setLexicalDeclContext(IMPDecl
);
19415 CheckImplementationIvars(IMPDecl
, ClsFields
, RecFields
.size(), RBrac
);
19416 IMPDecl
->setIvarLBraceLoc(LBrac
);
19417 IMPDecl
->setIvarRBraceLoc(RBrac
);
19418 } else if (ObjCCategoryDecl
*CDecl
=
19419 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
19420 // case of ivars in class extension; all other cases have been
19421 // reported as errors elsewhere.
19422 // FIXME. Class extension does not have a LocEnd field.
19423 // CDecl->setLocEnd(RBrac);
19424 // Add ivar's to class extension's DeclContext.
19425 // Diagnose redeclaration of private ivars.
19426 ObjCInterfaceDecl
*IDecl
= CDecl
->getClassInterface();
19427 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
19429 if (const ObjCIvarDecl
*ClsIvar
=
19430 IDecl
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
19431 Diag(ClsFields
[i
]->getLocation(),
19432 diag::err_duplicate_ivar_declaration
);
19433 Diag(ClsIvar
->getLocation(), diag::note_previous_definition
);
19436 for (const auto *Ext
: IDecl
->known_extensions()) {
19437 if (const ObjCIvarDecl
*ClsExtIvar
19438 = Ext
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
19439 Diag(ClsFields
[i
]->getLocation(),
19440 diag::err_duplicate_ivar_declaration
);
19441 Diag(ClsExtIvar
->getLocation(), diag::note_previous_definition
);
19446 ClsFields
[i
]->setLexicalDeclContext(CDecl
);
19447 CDecl
->addDecl(ClsFields
[i
]);
19449 CDecl
->setIvarLBraceLoc(LBrac
);
19450 CDecl
->setIvarRBraceLoc(RBrac
);
19454 // Check the "counted_by" attribute to ensure that the count field exists in
19455 // the struct. Make sure we're performing this check on the outer-most
19456 // record. This is a C-only feature.
19457 if (!getLangOpts().CPlusPlus
&& Record
&&
19458 !isa
<RecordDecl
>(Record
->getParent())) {
19459 auto Pred
= [](const Decl
*D
) {
19460 if (const auto *FD
= dyn_cast_if_present
<FieldDecl
>(D
))
19461 return FD
->hasAttr
<CountedByAttr
>();
19464 if (const FieldDecl
*FD
= Record
->findFieldIf(Pred
))
19465 CheckCountedByAttr(S
, FD
);
19469 /// Determine whether the given integral value is representable within
19470 /// the given type T.
19471 static bool isRepresentableIntegerValue(ASTContext
&Context
,
19472 llvm::APSInt
&Value
,
19474 assert((T
->isIntegralType(Context
) || T
->isEnumeralType()) &&
19475 "Integral type required!");
19476 unsigned BitWidth
= Context
.getIntWidth(T
);
19478 if (Value
.isUnsigned() || Value
.isNonNegative()) {
19479 if (T
->isSignedIntegerOrEnumerationType())
19481 return Value
.getActiveBits() <= BitWidth
;
19483 return Value
.getSignificantBits() <= BitWidth
;
19486 // Given an integral type, return the next larger integral type
19487 // (or a NULL type of no such type exists).
19488 static QualType
getNextLargerIntegralType(ASTContext
&Context
, QualType T
) {
19489 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19490 // enum checking below.
19491 assert((T
->isIntegralType(Context
) ||
19492 T
->isEnumeralType()) && "Integral type required!");
19493 const unsigned NumTypes
= 4;
19494 QualType SignedIntegralTypes
[NumTypes
] = {
19495 Context
.ShortTy
, Context
.IntTy
, Context
.LongTy
, Context
.LongLongTy
19497 QualType UnsignedIntegralTypes
[NumTypes
] = {
19498 Context
.UnsignedShortTy
, Context
.UnsignedIntTy
, Context
.UnsignedLongTy
,
19499 Context
.UnsignedLongLongTy
19502 unsigned BitWidth
= Context
.getTypeSize(T
);
19503 QualType
*Types
= T
->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19504 : UnsignedIntegralTypes
;
19505 for (unsigned I
= 0; I
!= NumTypes
; ++I
)
19506 if (Context
.getTypeSize(Types
[I
]) > BitWidth
)
19512 EnumConstantDecl
*Sema::CheckEnumConstant(EnumDecl
*Enum
,
19513 EnumConstantDecl
*LastEnumConst
,
19514 SourceLocation IdLoc
,
19515 IdentifierInfo
*Id
,
19517 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
19518 llvm::APSInt
EnumVal(IntWidth
);
19521 if (Val
&& DiagnoseUnexpandedParameterPack(Val
, UPPC_EnumeratorValue
))
19525 Val
= DefaultLvalueConversion(Val
).get();
19528 if (Enum
->isDependentType() || Val
->isTypeDependent() ||
19529 Val
->containsErrors())
19530 EltTy
= Context
.DependentTy
;
19532 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19533 // underlying type, but do allow it in all other contexts.
19534 if (getLangOpts().CPlusPlus11
&& Enum
->isFixed()) {
19535 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19536 // constant-expression in the enumerator-definition shall be a converted
19537 // constant expression of the underlying type.
19538 EltTy
= Enum
->getIntegerType();
19539 ExprResult Converted
=
19540 CheckConvertedConstantExpression(Val
, EltTy
, EnumVal
,
19542 if (Converted
.isInvalid())
19545 Val
= Converted
.get();
19546 } else if (!Val
->isValueDependent() &&
19548 VerifyIntegerConstantExpression(Val
, &EnumVal
, AllowFold
)
19550 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19552 if (Enum
->isComplete()) {
19553 EltTy
= Enum
->getIntegerType();
19555 // In Obj-C and Microsoft mode, require the enumeration value to be
19556 // representable in the underlying type of the enumeration. In C++11,
19557 // we perform a non-narrowing conversion as part of converted constant
19558 // expression checking.
19559 if (!isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
19560 if (Context
.getTargetInfo()
19562 .isWindowsMSVCEnvironment()) {
19563 Diag(IdLoc
, diag::ext_enumerator_too_large
) << EltTy
;
19565 Diag(IdLoc
, diag::err_enumerator_too_large
) << EltTy
;
19569 // Cast to the underlying type.
19570 Val
= ImpCastExprToType(Val
, EltTy
,
19571 EltTy
->isBooleanType() ? CK_IntegralToBoolean
19574 } else if (getLangOpts().CPlusPlus
) {
19575 // C++11 [dcl.enum]p5:
19576 // If the underlying type is not fixed, the type of each enumerator
19577 // is the type of its initializing value:
19578 // - If an initializer is specified for an enumerator, the
19579 // initializing value has the same type as the expression.
19580 EltTy
= Val
->getType();
19583 // The expression that defines the value of an enumeration constant
19584 // shall be an integer constant expression that has a value
19585 // representable as an int.
19587 // Complain if the value is not representable in an int.
19588 if (!isRepresentableIntegerValue(Context
, EnumVal
, Context
.IntTy
))
19589 Diag(IdLoc
, diag::ext_enum_value_not_int
)
19590 << toString(EnumVal
, 10) << Val
->getSourceRange()
19591 << (EnumVal
.isUnsigned() || EnumVal
.isNonNegative());
19592 else if (!Context
.hasSameType(Val
->getType(), Context
.IntTy
)) {
19593 // Force the type of the expression to 'int'.
19594 Val
= ImpCastExprToType(Val
, Context
.IntTy
, CK_IntegralCast
).get();
19596 EltTy
= Val
->getType();
19603 if (Enum
->isDependentType())
19604 EltTy
= Context
.DependentTy
;
19605 else if (!LastEnumConst
) {
19606 // C++0x [dcl.enum]p5:
19607 // If the underlying type is not fixed, the type of each enumerator
19608 // is the type of its initializing value:
19609 // - If no initializer is specified for the first enumerator, the
19610 // initializing value has an unspecified integral type.
19612 // GCC uses 'int' for its unspecified integral type, as does
19614 if (Enum
->isFixed()) {
19615 EltTy
= Enum
->getIntegerType();
19618 EltTy
= Context
.IntTy
;
19621 // Assign the last value + 1.
19622 EnumVal
= LastEnumConst
->getInitVal();
19624 EltTy
= LastEnumConst
->getType();
19626 // Check for overflow on increment.
19627 if (EnumVal
< LastEnumConst
->getInitVal()) {
19628 // C++0x [dcl.enum]p5:
19629 // If the underlying type is not fixed, the type of each enumerator
19630 // is the type of its initializing value:
19632 // - Otherwise the type of the initializing value is the same as
19633 // the type of the initializing value of the preceding enumerator
19634 // unless the incremented value is not representable in that type,
19635 // in which case the type is an unspecified integral type
19636 // sufficient to contain the incremented value. If no such type
19637 // exists, the program is ill-formed.
19638 QualType T
= getNextLargerIntegralType(Context
, EltTy
);
19639 if (T
.isNull() || Enum
->isFixed()) {
19640 // There is no integral type larger enough to represent this
19641 // value. Complain, then allow the value to wrap around.
19642 EnumVal
= LastEnumConst
->getInitVal();
19643 EnumVal
= EnumVal
.zext(EnumVal
.getBitWidth() * 2);
19645 if (Enum
->isFixed())
19646 // When the underlying type is fixed, this is ill-formed.
19647 Diag(IdLoc
, diag::err_enumerator_wrapped
)
19648 << toString(EnumVal
, 10)
19651 Diag(IdLoc
, diag::ext_enumerator_increment_too_large
)
19652 << toString(EnumVal
, 10);
19657 // Retrieve the last enumerator's value, extent that type to the
19658 // type that is supposed to be large enough to represent the incremented
19659 // value, then increment.
19660 EnumVal
= LastEnumConst
->getInitVal();
19661 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
19662 EnumVal
= EnumVal
.zextOrTrunc(Context
.getIntWidth(EltTy
));
19665 // If we're not in C++, diagnose the overflow of enumerator values,
19666 // which in C99 means that the enumerator value is not representable in
19667 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19668 // permits enumerator values that are representable in some larger
19670 if (!getLangOpts().CPlusPlus
&& !T
.isNull())
19671 Diag(IdLoc
, diag::warn_enum_value_overflow
);
19672 } else if (!getLangOpts().CPlusPlus
&&
19673 !EltTy
->isDependentType() &&
19674 !isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
19675 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19676 Diag(IdLoc
, diag::ext_enum_value_not_int
)
19677 << toString(EnumVal
, 10) << 1;
19682 if (!EltTy
->isDependentType()) {
19683 // Make the enumerator value match the signedness and size of the
19684 // enumerator's type.
19685 EnumVal
= EnumVal
.extOrTrunc(Context
.getIntWidth(EltTy
));
19686 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
19689 return EnumConstantDecl::Create(Context
, Enum
, IdLoc
, Id
, EltTy
,
19693 Sema::SkipBodyInfo
Sema::shouldSkipAnonEnumBody(Scope
*S
, IdentifierInfo
*II
,
19694 SourceLocation IILoc
) {
19695 if (!(getLangOpts().Modules
|| getLangOpts().ModulesLocalVisibility
) ||
19696 !getLangOpts().CPlusPlus
)
19697 return SkipBodyInfo();
19699 // We have an anonymous enum definition. Look up the first enumerator to
19700 // determine if we should merge the definition with an existing one and
19702 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, IILoc
, LookupOrdinaryName
,
19703 forRedeclarationInCurContext());
19704 auto *PrevECD
= dyn_cast_or_null
<EnumConstantDecl
>(PrevDecl
);
19706 return SkipBodyInfo();
19708 EnumDecl
*PrevED
= cast
<EnumDecl
>(PrevECD
->getDeclContext());
19710 if (!PrevED
->getDeclName() && !hasVisibleDefinition(PrevED
, &Hidden
)) {
19712 Skip
.Previous
= Hidden
;
19716 return SkipBodyInfo();
19719 Decl
*Sema::ActOnEnumConstant(Scope
*S
, Decl
*theEnumDecl
, Decl
*lastEnumConst
,
19720 SourceLocation IdLoc
, IdentifierInfo
*Id
,
19721 const ParsedAttributesView
&Attrs
,
19722 SourceLocation EqualLoc
, Expr
*Val
) {
19723 EnumDecl
*TheEnumDecl
= cast
<EnumDecl
>(theEnumDecl
);
19724 EnumConstantDecl
*LastEnumConst
=
19725 cast_or_null
<EnumConstantDecl
>(lastEnumConst
);
19727 // The scope passed in may not be a decl scope. Zip up the scope tree until
19728 // we find one that is.
19729 S
= getNonFieldDeclScope(S
);
19731 // Verify that there isn't already something declared with this name in this
19733 LookupResult
R(*this, Id
, IdLoc
, LookupOrdinaryName
, ForVisibleRedeclaration
);
19735 NamedDecl
*PrevDecl
= R
.getAsSingle
<NamedDecl
>();
19737 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
19738 // Maybe we will complain about the shadowed template parameter.
19739 DiagnoseTemplateParameterShadow(IdLoc
, PrevDecl
);
19740 // Just pretend that we didn't see the previous declaration.
19741 PrevDecl
= nullptr;
19744 // C++ [class.mem]p15:
19745 // If T is the name of a class, then each of the following shall have a name
19746 // different from T:
19747 // - every enumerator of every member of class T that is an unscoped
19749 if (getLangOpts().CPlusPlus
&& !TheEnumDecl
->isScoped())
19750 DiagnoseClassNameShadow(TheEnumDecl
->getDeclContext(),
19751 DeclarationNameInfo(Id
, IdLoc
));
19753 EnumConstantDecl
*New
=
19754 CheckEnumConstant(TheEnumDecl
, LastEnumConst
, IdLoc
, Id
, Val
);
19759 if (!TheEnumDecl
->isScoped() && isa
<ValueDecl
>(PrevDecl
)) {
19760 // Check for other kinds of shadowing not already handled.
19761 CheckShadow(New
, PrevDecl
, R
);
19764 // When in C++, we may get a TagDecl with the same name; in this case the
19765 // enum constant will 'hide' the tag.
19766 assert((getLangOpts().CPlusPlus
|| !isa
<TagDecl
>(PrevDecl
)) &&
19767 "Received TagDecl when not in C++!");
19768 if (!isa
<TagDecl
>(PrevDecl
) && isDeclInScope(PrevDecl
, CurContext
, S
)) {
19769 if (isa
<EnumConstantDecl
>(PrevDecl
))
19770 Diag(IdLoc
, diag::err_redefinition_of_enumerator
) << Id
;
19772 Diag(IdLoc
, diag::err_redefinition
) << Id
;
19773 notePreviousDefinition(PrevDecl
, IdLoc
);
19778 // Process attributes.
19779 ProcessDeclAttributeList(S
, New
, Attrs
);
19780 AddPragmaAttributes(S
, New
);
19782 // Register this decl in the current scope stack.
19783 New
->setAccess(TheEnumDecl
->getAccess());
19784 PushOnScopeChains(New
, S
);
19786 ActOnDocumentableDecl(New
);
19791 // Returns true when the enum initial expression does not trigger the
19792 // duplicate enum warning. A few common cases are exempted as follows:
19793 // Element2 = Element1
19794 // Element2 = Element1 + 1
19795 // Element2 = Element1 - 1
19796 // Where Element2 and Element1 are from the same enum.
19797 static bool ValidDuplicateEnum(EnumConstantDecl
*ECD
, EnumDecl
*Enum
) {
19798 Expr
*InitExpr
= ECD
->getInitExpr();
19801 InitExpr
= InitExpr
->IgnoreImpCasts();
19803 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(InitExpr
)) {
19804 if (!BO
->isAdditiveOp())
19806 IntegerLiteral
*IL
= dyn_cast
<IntegerLiteral
>(BO
->getRHS());
19809 if (IL
->getValue() != 1)
19812 InitExpr
= BO
->getLHS();
19815 // This checks if the elements are from the same enum.
19816 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InitExpr
);
19820 EnumConstantDecl
*EnumConstant
= dyn_cast
<EnumConstantDecl
>(DRE
->getDecl());
19824 if (cast
<EnumDecl
>(TagDecl::castFromDeclContext(ECD
->getDeclContext())) !=
19831 // Emits a warning when an element is implicitly set a value that
19832 // a previous element has already been set to.
19833 static void CheckForDuplicateEnumValues(Sema
&S
, ArrayRef
<Decl
*> Elements
,
19834 EnumDecl
*Enum
, QualType EnumType
) {
19835 // Avoid anonymous enums
19836 if (!Enum
->getIdentifier())
19839 // Only check for small enums.
19840 if (Enum
->getNumPositiveBits() > 63 || Enum
->getNumNegativeBits() > 64)
19843 if (S
.Diags
.isIgnored(diag::warn_duplicate_enum_values
, Enum
->getLocation()))
19846 typedef SmallVector
<EnumConstantDecl
*, 3> ECDVector
;
19847 typedef SmallVector
<std::unique_ptr
<ECDVector
>, 3> DuplicatesVector
;
19849 typedef llvm::PointerUnion
<EnumConstantDecl
*, ECDVector
*> DeclOrVector
;
19851 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19852 typedef std::unordered_map
<int64_t, DeclOrVector
> ValueToVectorMap
;
19854 // Use int64_t as a key to avoid needing special handling for map keys.
19855 auto EnumConstantToKey
= [](const EnumConstantDecl
*D
) {
19856 llvm::APSInt Val
= D
->getInitVal();
19857 return Val
.isSigned() ? Val
.getSExtValue() : Val
.getZExtValue();
19860 DuplicatesVector DupVector
;
19861 ValueToVectorMap EnumMap
;
19863 // Populate the EnumMap with all values represented by enum constants without
19865 for (auto *Element
: Elements
) {
19866 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(Element
);
19868 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19869 // this constant. Skip this enum since it may be ill-formed.
19874 // Constants with initializers are handled in the next loop.
19875 if (ECD
->getInitExpr())
19878 // Duplicate values are handled in the next loop.
19879 EnumMap
.insert({EnumConstantToKey(ECD
), ECD
});
19882 if (EnumMap
.size() == 0)
19885 // Create vectors for any values that has duplicates.
19886 for (auto *Element
: Elements
) {
19887 // The last loop returned if any constant was null.
19888 EnumConstantDecl
*ECD
= cast
<EnumConstantDecl
>(Element
);
19889 if (!ValidDuplicateEnum(ECD
, Enum
))
19892 auto Iter
= EnumMap
.find(EnumConstantToKey(ECD
));
19893 if (Iter
== EnumMap
.end())
19896 DeclOrVector
& Entry
= Iter
->second
;
19897 if (EnumConstantDecl
*D
= Entry
.dyn_cast
<EnumConstantDecl
*>()) {
19898 // Ensure constants are different.
19902 // Create new vector and push values onto it.
19903 auto Vec
= std::make_unique
<ECDVector
>();
19905 Vec
->push_back(ECD
);
19907 // Update entry to point to the duplicates vector.
19910 // Store the vector somewhere we can consult later for quick emission of
19912 DupVector
.emplace_back(std::move(Vec
));
19916 ECDVector
*Vec
= Entry
.get
<ECDVector
*>();
19917 // Make sure constants are not added more than once.
19918 if (*Vec
->begin() == ECD
)
19921 Vec
->push_back(ECD
);
19924 // Emit diagnostics.
19925 for (const auto &Vec
: DupVector
) {
19926 assert(Vec
->size() > 1 && "ECDVector should have at least 2 elements.");
19928 // Emit warning for one enum constant.
19929 auto *FirstECD
= Vec
->front();
19930 S
.Diag(FirstECD
->getLocation(), diag::warn_duplicate_enum_values
)
19931 << FirstECD
<< toString(FirstECD
->getInitVal(), 10)
19932 << FirstECD
->getSourceRange();
19934 // Emit one note for each of the remaining enum constants with
19936 for (auto *ECD
: llvm::drop_begin(*Vec
))
19937 S
.Diag(ECD
->getLocation(), diag::note_duplicate_element
)
19938 << ECD
<< toString(ECD
->getInitVal(), 10)
19939 << ECD
->getSourceRange();
19943 bool Sema::IsValueInFlagEnum(const EnumDecl
*ED
, const llvm::APInt
&Val
,
19944 bool AllowMask
) const {
19945 assert(ED
->isClosedFlag() && "looking for value in non-flag or open enum");
19946 assert(ED
->isCompleteDefinition() && "expected enum definition");
19948 auto R
= FlagBitsCache
.insert(std::make_pair(ED
, llvm::APInt()));
19949 llvm::APInt
&FlagBits
= R
.first
->second
;
19952 for (auto *E
: ED
->enumerators()) {
19953 const auto &EVal
= E
->getInitVal();
19954 // Only single-bit enumerators introduce new flag values.
19955 if (EVal
.isPowerOf2())
19956 FlagBits
= FlagBits
.zext(EVal
.getBitWidth()) | EVal
;
19960 // A value is in a flag enum if either its bits are a subset of the enum's
19961 // flag bits (the first condition) or we are allowing masks and the same is
19962 // true of its complement (the second condition). When masks are allowed, we
19963 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19965 // While it's true that any value could be used as a mask, the assumption is
19966 // that a mask will have all of the insignificant bits set. Anything else is
19967 // likely a logic error.
19968 llvm::APInt FlagMask
= ~FlagBits
.zextOrTrunc(Val
.getBitWidth());
19969 return !(FlagMask
& Val
) || (AllowMask
&& !(FlagMask
& ~Val
));
19972 void Sema::ActOnEnumBody(SourceLocation EnumLoc
, SourceRange BraceRange
,
19973 Decl
*EnumDeclX
, ArrayRef
<Decl
*> Elements
, Scope
*S
,
19974 const ParsedAttributesView
&Attrs
) {
19975 EnumDecl
*Enum
= cast
<EnumDecl
>(EnumDeclX
);
19976 QualType EnumType
= Context
.getTypeDeclType(Enum
);
19978 ProcessDeclAttributeList(S
, Enum
, Attrs
);
19980 if (Enum
->isDependentType()) {
19981 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
19982 EnumConstantDecl
*ECD
=
19983 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
19984 if (!ECD
) continue;
19986 ECD
->setType(EnumType
);
19989 Enum
->completeDefinition(Context
.DependentTy
, Context
.DependentTy
, 0, 0);
19993 // TODO: If the result value doesn't fit in an int, it must be a long or long
19994 // long value. ISO C does not support this, but GCC does as an extension,
19996 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
19997 unsigned CharWidth
= Context
.getTargetInfo().getCharWidth();
19998 unsigned ShortWidth
= Context
.getTargetInfo().getShortWidth();
20000 // Verify that all the values are okay, compute the size of the values, and
20001 // reverse the list.
20002 unsigned NumNegativeBits
= 0;
20003 unsigned NumPositiveBits
= 0;
20005 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
20006 EnumConstantDecl
*ECD
=
20007 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
20008 if (!ECD
) continue; // Already issued a diagnostic.
20010 const llvm::APSInt
&InitVal
= ECD
->getInitVal();
20012 // Keep track of the size of positive and negative values.
20013 if (InitVal
.isUnsigned() || InitVal
.isNonNegative()) {
20014 // If the enumerator is zero that should still be counted as a positive
20015 // bit since we need a bit to store the value zero.
20016 unsigned ActiveBits
= InitVal
.getActiveBits();
20017 NumPositiveBits
= std::max({NumPositiveBits
, ActiveBits
, 1u});
20020 std::max(NumNegativeBits
, (unsigned)InitVal
.getSignificantBits());
20024 // If we have an empty set of enumerators we still need one bit.
20025 // From [dcl.enum]p8
20026 // If the enumerator-list is empty, the values of the enumeration are as if
20027 // the enumeration had a single enumerator with value 0
20028 if (!NumPositiveBits
&& !NumNegativeBits
)
20029 NumPositiveBits
= 1;
20031 // Figure out the type that should be used for this enum.
20033 unsigned BestWidth
;
20035 // C++0x N3000 [conv.prom]p3:
20036 // An rvalue of an unscoped enumeration type whose underlying
20037 // type is not fixed can be converted to an rvalue of the first
20038 // of the following types that can represent all the values of
20039 // the enumeration: int, unsigned int, long int, unsigned long
20040 // int, long long int, or unsigned long long int.
20042 // An identifier declared as an enumeration constant has type int.
20043 // The C99 rule is modified by a gcc extension
20044 QualType BestPromotionType
;
20046 bool Packed
= Enum
->hasAttr
<PackedAttr
>();
20047 // -fshort-enums is the equivalent to specifying the packed attribute on all
20048 // enum definitions.
20049 if (LangOpts
.ShortEnums
)
20052 // If the enum already has a type because it is fixed or dictated by the
20053 // target, promote that type instead of analyzing the enumerators.
20054 if (Enum
->isComplete()) {
20055 BestType
= Enum
->getIntegerType();
20056 if (Context
.isPromotableIntegerType(BestType
))
20057 BestPromotionType
= Context
.getPromotedIntegerType(BestType
);
20059 BestPromotionType
= BestType
;
20061 BestWidth
= Context
.getIntWidth(BestType
);
20063 else if (NumNegativeBits
) {
20064 // If there is a negative value, figure out the smallest integer type (of
20065 // int/long/longlong) that fits.
20066 // If it's packed, check also if it fits a char or a short.
20067 if (Packed
&& NumNegativeBits
<= CharWidth
&& NumPositiveBits
< CharWidth
) {
20068 BestType
= Context
.SignedCharTy
;
20069 BestWidth
= CharWidth
;
20070 } else if (Packed
&& NumNegativeBits
<= ShortWidth
&&
20071 NumPositiveBits
< ShortWidth
) {
20072 BestType
= Context
.ShortTy
;
20073 BestWidth
= ShortWidth
;
20074 } else if (NumNegativeBits
<= IntWidth
&& NumPositiveBits
< IntWidth
) {
20075 BestType
= Context
.IntTy
;
20076 BestWidth
= IntWidth
;
20078 BestWidth
= Context
.getTargetInfo().getLongWidth();
20080 if (NumNegativeBits
<= BestWidth
&& NumPositiveBits
< BestWidth
) {
20081 BestType
= Context
.LongTy
;
20083 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
20085 if (NumNegativeBits
> BestWidth
|| NumPositiveBits
>= BestWidth
)
20086 Diag(Enum
->getLocation(), diag::ext_enum_too_large
);
20087 BestType
= Context
.LongLongTy
;
20090 BestPromotionType
= (BestWidth
<= IntWidth
? Context
.IntTy
: BestType
);
20092 // If there is no negative value, figure out the smallest type that fits
20093 // all of the enumerator values.
20094 // If it's packed, check also if it fits a char or a short.
20095 if (Packed
&& NumPositiveBits
<= CharWidth
) {
20096 BestType
= Context
.UnsignedCharTy
;
20097 BestPromotionType
= Context
.IntTy
;
20098 BestWidth
= CharWidth
;
20099 } else if (Packed
&& NumPositiveBits
<= ShortWidth
) {
20100 BestType
= Context
.UnsignedShortTy
;
20101 BestPromotionType
= Context
.IntTy
;
20102 BestWidth
= ShortWidth
;
20103 } else if (NumPositiveBits
<= IntWidth
) {
20104 BestType
= Context
.UnsignedIntTy
;
20105 BestWidth
= IntWidth
;
20107 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
20108 ? Context
.UnsignedIntTy
: Context
.IntTy
;
20109 } else if (NumPositiveBits
<=
20110 (BestWidth
= Context
.getTargetInfo().getLongWidth())) {
20111 BestType
= Context
.UnsignedLongTy
;
20113 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
20114 ? Context
.UnsignedLongTy
: Context
.LongTy
;
20116 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
20117 assert(NumPositiveBits
<= BestWidth
&&
20118 "How could an initializer get larger than ULL?");
20119 BestType
= Context
.UnsignedLongLongTy
;
20121 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
20122 ? Context
.UnsignedLongLongTy
: Context
.LongLongTy
;
20126 // Loop over all of the enumerator constants, changing their types to match
20127 // the type of the enum if needed.
20128 for (auto *D
: Elements
) {
20129 auto *ECD
= cast_or_null
<EnumConstantDecl
>(D
);
20130 if (!ECD
) continue; // Already issued a diagnostic.
20132 // Standard C says the enumerators have int type, but we allow, as an
20133 // extension, the enumerators to be larger than int size. If each
20134 // enumerator value fits in an int, type it as an int, otherwise type it the
20135 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20136 // that X has type 'int', not 'unsigned'.
20138 // Determine whether the value fits into an int.
20139 llvm::APSInt InitVal
= ECD
->getInitVal();
20141 // If it fits into an integer type, force it. Otherwise force it to match
20142 // the enum decl type.
20146 if (!getLangOpts().CPlusPlus
&&
20147 !Enum
->isFixed() &&
20148 isRepresentableIntegerValue(Context
, InitVal
, Context
.IntTy
)) {
20149 NewTy
= Context
.IntTy
;
20150 NewWidth
= IntWidth
;
20152 } else if (ECD
->getType() == BestType
) {
20153 // Already the right type!
20154 if (getLangOpts().CPlusPlus
)
20155 // C++ [dcl.enum]p4: Following the closing brace of an
20156 // enum-specifier, each enumerator has the type of its
20158 ECD
->setType(EnumType
);
20162 NewWidth
= BestWidth
;
20163 NewSign
= BestType
->isSignedIntegerOrEnumerationType();
20166 // Adjust the APSInt value.
20167 InitVal
= InitVal
.extOrTrunc(NewWidth
);
20168 InitVal
.setIsSigned(NewSign
);
20169 ECD
->setInitVal(InitVal
);
20171 // Adjust the Expr initializer and type.
20172 if (ECD
->getInitExpr() &&
20173 !Context
.hasSameType(NewTy
, ECD
->getInitExpr()->getType()))
20174 ECD
->setInitExpr(ImplicitCastExpr::Create(
20175 Context
, NewTy
, CK_IntegralCast
, ECD
->getInitExpr(),
20176 /*base paths*/ nullptr, VK_PRValue
, FPOptionsOverride()));
20177 if (getLangOpts().CPlusPlus
)
20178 // C++ [dcl.enum]p4: Following the closing brace of an
20179 // enum-specifier, each enumerator has the type of its
20181 ECD
->setType(EnumType
);
20183 ECD
->setType(NewTy
);
20186 Enum
->completeDefinition(BestType
, BestPromotionType
,
20187 NumPositiveBits
, NumNegativeBits
);
20189 CheckForDuplicateEnumValues(*this, Elements
, Enum
, EnumType
);
20191 if (Enum
->isClosedFlag()) {
20192 for (Decl
*D
: Elements
) {
20193 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(D
);
20194 if (!ECD
) continue; // Already issued a diagnostic.
20196 llvm::APSInt InitVal
= ECD
->getInitVal();
20197 if (InitVal
!= 0 && !InitVal
.isPowerOf2() &&
20198 !IsValueInFlagEnum(Enum
, InitVal
, true))
20199 Diag(ECD
->getLocation(), diag::warn_flag_enum_constant_out_of_range
)
20204 // Now that the enum type is defined, ensure it's not been underaligned.
20205 if (Enum
->hasAttrs())
20206 CheckAlignasUnderalignment(Enum
);
20209 Decl
*Sema::ActOnFileScopeAsmDecl(Expr
*expr
,
20210 SourceLocation StartLoc
,
20211 SourceLocation EndLoc
) {
20212 StringLiteral
*AsmString
= cast
<StringLiteral
>(expr
);
20214 FileScopeAsmDecl
*New
= FileScopeAsmDecl::Create(Context
, CurContext
,
20215 AsmString
, StartLoc
,
20217 CurContext
->addDecl(New
);
20221 Decl
*Sema::ActOnTopLevelStmtDecl(Stmt
*Statement
) {
20222 auto *New
= TopLevelStmtDecl::Create(Context
, Statement
);
20223 Context
.getTranslationUnitDecl()->addDecl(New
);
20227 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo
* Name
,
20228 IdentifierInfo
* AliasName
,
20229 SourceLocation PragmaLoc
,
20230 SourceLocation NameLoc
,
20231 SourceLocation AliasNameLoc
) {
20232 NamedDecl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
,
20233 LookupOrdinaryName
);
20234 AttributeCommonInfo
Info(AliasName
, SourceRange(AliasNameLoc
),
20235 AttributeCommonInfo::Form::Pragma());
20236 AsmLabelAttr
*Attr
= AsmLabelAttr::CreateImplicit(
20237 Context
, AliasName
->getName(), /*IsLiteralLabel=*/true, Info
);
20239 // If a declaration that:
20240 // 1) declares a function or a variable
20241 // 2) has external linkage
20242 // already exists, add a label attribute to it.
20243 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
20244 if (isDeclExternC(PrevDecl
))
20245 PrevDecl
->addAttr(Attr
);
20247 Diag(PrevDecl
->getLocation(), diag::warn_redefine_extname_not_applied
)
20248 << /*Variable*/(isa
<FunctionDecl
>(PrevDecl
) ? 0 : 1) << PrevDecl
;
20249 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20251 (void)ExtnameUndeclaredIdentifiers
.insert(std::make_pair(Name
, Attr
));
20254 void Sema::ActOnPragmaWeakID(IdentifierInfo
* Name
,
20255 SourceLocation PragmaLoc
,
20256 SourceLocation NameLoc
) {
20257 Decl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
, LookupOrdinaryName
);
20260 PrevDecl
->addAttr(WeakAttr::CreateImplicit(Context
, PragmaLoc
));
20262 (void)WeakUndeclaredIdentifiers
[Name
].insert(WeakInfo(nullptr, NameLoc
));
20266 void Sema::ActOnPragmaWeakAlias(IdentifierInfo
* Name
,
20267 IdentifierInfo
* AliasName
,
20268 SourceLocation PragmaLoc
,
20269 SourceLocation NameLoc
,
20270 SourceLocation AliasNameLoc
) {
20271 Decl
*PrevDecl
= LookupSingleName(TUScope
, AliasName
, AliasNameLoc
,
20272 LookupOrdinaryName
);
20273 WeakInfo W
= WeakInfo(Name
, NameLoc
);
20275 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
20276 if (!PrevDecl
->hasAttr
<AliasAttr
>())
20277 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(PrevDecl
))
20278 DeclApplyPragmaWeak(TUScope
, ND
, W
);
20280 (void)WeakUndeclaredIdentifiers
[AliasName
].insert(W
);
20284 ObjCContainerDecl
*Sema::getObjCDeclContext() const {
20285 return (dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
));
20288 Sema::FunctionEmissionStatus
Sema::getEmissionStatus(const FunctionDecl
*FD
,
20290 assert(FD
&& "Expected non-null FunctionDecl");
20292 // SYCL functions can be template, so we check if they have appropriate
20293 // attribute prior to checking if it is a template.
20294 if (LangOpts
.SYCLIsDevice
&& FD
->hasAttr
<SYCLKernelAttr
>())
20295 return FunctionEmissionStatus::Emitted
;
20297 // Templates are emitted when they're instantiated.
20298 if (FD
->isDependentContext())
20299 return FunctionEmissionStatus::TemplateDiscarded
;
20301 // Check whether this function is an externally visible definition.
20302 auto IsEmittedForExternalSymbol
= [this, FD
]() {
20303 // We have to check the GVA linkage of the function's *definition* -- if we
20304 // only have a declaration, we don't know whether or not the function will
20305 // be emitted, because (say) the definition could include "inline".
20306 const FunctionDecl
*Def
= FD
->getDefinition();
20308 return Def
&& !isDiscardableGVALinkage(
20309 getASTContext().GetGVALinkageForFunction(Def
));
20312 if (LangOpts
.OpenMPIsTargetDevice
) {
20313 // In OpenMP device mode we will not emit host only functions, or functions
20314 // we don't need due to their linkage.
20315 std::optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
20316 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
20317 // DevTy may be changed later by
20318 // #pragma omp declare target to(*) device_type(*).
20319 // Therefore DevTy having no value does not imply host. The emission status
20320 // will be checked again at the end of compilation unit with Final = true.
20322 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_Host
)
20323 return FunctionEmissionStatus::OMPDiscarded
;
20324 // If we have an explicit value for the device type, or we are in a target
20325 // declare context, we need to emit all extern and used symbols.
20326 if (isInOpenMPDeclareTargetContext() || DevTy
)
20327 if (IsEmittedForExternalSymbol())
20328 return FunctionEmissionStatus::Emitted
;
20329 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20332 return FunctionEmissionStatus::OMPDiscarded
;
20333 } else if (LangOpts
.OpenMP
> 45) {
20334 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20335 // function. In 5.0, no_host was introduced which might cause a function to
20337 std::optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
20338 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
20340 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_NoHost
)
20341 return FunctionEmissionStatus::OMPDiscarded
;
20344 if (Final
&& LangOpts
.OpenMP
&& !LangOpts
.CUDA
)
20345 return FunctionEmissionStatus::Emitted
;
20347 if (LangOpts
.CUDA
) {
20348 // When compiling for device, host functions are never emitted. Similarly,
20349 // when compiling for host, device and global functions are never emitted.
20350 // (Technically, we do emit a host-side stub for global functions, but this
20351 // doesn't count for our purposes here.)
20352 Sema::CUDAFunctionTarget T
= IdentifyCUDATarget(FD
);
20353 if (LangOpts
.CUDAIsDevice
&& T
== Sema::CFT_Host
)
20354 return FunctionEmissionStatus::CUDADiscarded
;
20355 if (!LangOpts
.CUDAIsDevice
&&
20356 (T
== Sema::CFT_Device
|| T
== Sema::CFT_Global
))
20357 return FunctionEmissionStatus::CUDADiscarded
;
20359 if (IsEmittedForExternalSymbol())
20360 return FunctionEmissionStatus::Emitted
;
20363 // Otherwise, the function is known-emitted if it's in our set of
20364 // known-emitted functions.
20365 return FunctionEmissionStatus::Unknown
;
20368 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl
*Callee
) {
20369 // Host-side references to a __global__ function refer to the stub, so the
20370 // function itself is never emitted and therefore should not be marked.
20371 // If we have host fn calls kernel fn calls host+device, the HD function
20372 // does not get instantiated on the host. We model this by omitting at the
20373 // call to the kernel from the callgraph. This ensures that, when compiling
20374 // for host, only HD functions actually called from the host get marked as
20376 return LangOpts
.CUDA
&& !LangOpts
.CUDAIsDevice
&&
20377 IdentifyCUDATarget(Callee
) == CFT_Global
;