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/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
52 #include <unordered_map>
54 using namespace clang
;
57 Sema::DeclGroupPtrTy
Sema::ConvertDeclToDeclGroup(Decl
*Ptr
, Decl
*OwnedType
) {
59 Decl
*Group
[2] = { OwnedType
, Ptr
};
60 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context
, Group
, 2));
63 return DeclGroupPtrTy::make(DeclGroupRef(Ptr
));
68 class TypeNameValidatorCCC final
: public CorrectionCandidateCallback
{
70 TypeNameValidatorCCC(bool AllowInvalid
, bool WantClass
= false,
71 bool AllowTemplates
= false,
72 bool AllowNonTemplates
= true)
73 : AllowInvalidDecl(AllowInvalid
), WantClassName(WantClass
),
74 AllowTemplates(AllowTemplates
), AllowNonTemplates(AllowNonTemplates
) {
75 WantExpressionKeywords
= false;
76 WantCXXNamedCasts
= false;
77 WantRemainingKeywords
= false;
80 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
81 if (NamedDecl
*ND
= candidate
.getCorrectionDecl()) {
82 if (!AllowInvalidDecl
&& ND
->isInvalidDecl())
85 if (getAsTypeTemplateDecl(ND
))
86 return AllowTemplates
;
88 bool IsType
= isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
92 if (AllowNonTemplates
)
95 // An injected-class-name of a class template (specialization) is valid
96 // as a template or as a non-template.
98 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
99 if (!RD
|| !RD
->isInjectedClassName())
101 RD
= cast
<CXXRecordDecl
>(RD
->getDeclContext());
102 return RD
->getDescribedClassTemplate() ||
103 isa
<ClassTemplateSpecializationDecl
>(RD
);
109 return !WantClassName
&& candidate
.isKeyword();
112 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
113 return std::make_unique
<TypeNameValidatorCCC
>(*this);
117 bool AllowInvalidDecl
;
120 bool AllowNonTemplates
;
123 } // end anonymous namespace
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind
) const {
128 // FIXME: Take into account the current language when deciding whether a
129 // token kind is a valid type specifier
132 case tok::kw___int64
:
133 case tok::kw___int128
:
135 case tok::kw_unsigned
:
143 case tok::kw__Float16
:
144 case tok::kw___float128
:
145 case tok::kw___ibm128
:
146 case tok::kw_wchar_t
:
148 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
149 #include "clang/Basic/TransformTypeTraits.def"
150 case tok::kw___auto_type
:
153 case tok::annot_typename
:
154 case tok::kw_char16_t
:
155 case tok::kw_char32_t
:
157 case tok::annot_decltype
:
158 case tok::kw_decltype
:
159 return getLangOpts().CPlusPlus
;
161 case tok::kw_char8_t
:
162 return getLangOpts().Char8
;
172 enum class UnqualifiedTypeNameLookupResult
{
177 } // end anonymous namespace
179 /// Tries to perform unqualified lookup of the type decls in bases for
181 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
182 /// type decl, \a FoundType if only type decls are found.
183 static UnqualifiedTypeNameLookupResult
184 lookupUnqualifiedTypeNameInBase(Sema
&S
, const IdentifierInfo
&II
,
185 SourceLocation NameLoc
,
186 const CXXRecordDecl
*RD
) {
187 if (!RD
->hasDefinition())
188 return UnqualifiedTypeNameLookupResult::NotFound
;
189 // Look for type decls in base classes.
190 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
191 UnqualifiedTypeNameLookupResult::NotFound
;
192 for (const auto &Base
: RD
->bases()) {
193 const CXXRecordDecl
*BaseRD
= nullptr;
194 if (auto *BaseTT
= Base
.getType()->getAs
<TagType
>())
195 BaseRD
= BaseTT
->getAsCXXRecordDecl();
196 else if (auto *TST
= Base
.getType()->getAs
<TemplateSpecializationType
>()) {
197 // Look for type decls in dependent base classes that have known primary
199 if (!TST
|| !TST
->isDependentType())
201 auto *TD
= TST
->getTemplateName().getAsTemplateDecl();
204 if (auto *BasePrimaryTemplate
=
205 dyn_cast_or_null
<CXXRecordDecl
>(TD
->getTemplatedDecl())) {
206 if (BasePrimaryTemplate
->getCanonicalDecl() != RD
->getCanonicalDecl())
207 BaseRD
= BasePrimaryTemplate
;
208 else if (auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
)) {
209 if (const ClassTemplatePartialSpecializationDecl
*PS
=
210 CTD
->findPartialSpecialization(Base
.getType()))
211 if (PS
->getCanonicalDecl() != RD
->getCanonicalDecl())
217 for (NamedDecl
*ND
: BaseRD
->lookup(&II
)) {
218 if (!isa
<TypeDecl
>(ND
))
219 return UnqualifiedTypeNameLookupResult::FoundNonType
;
220 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
222 if (FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
) {
223 switch (lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, BaseRD
)) {
224 case UnqualifiedTypeNameLookupResult::FoundNonType
:
225 return UnqualifiedTypeNameLookupResult::FoundNonType
;
226 case UnqualifiedTypeNameLookupResult::FoundType
:
227 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
229 case UnqualifiedTypeNameLookupResult::NotFound
:
236 return FoundTypeDecl
;
239 static ParsedType
recoverFromTypeInKnownDependentBase(Sema
&S
,
240 const IdentifierInfo
&II
,
241 SourceLocation NameLoc
) {
242 // Lookup in the parent class template context, if any.
243 const CXXRecordDecl
*RD
= nullptr;
244 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
245 UnqualifiedTypeNameLookupResult::NotFound
;
246 for (DeclContext
*DC
= S
.CurContext
;
247 DC
&& FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
;
248 DC
= DC
->getParent()) {
249 // Look for type decls in dependent base classes that have known primary
251 RD
= dyn_cast
<CXXRecordDecl
>(DC
);
252 if (RD
&& RD
->getDescribedClassTemplate())
253 FoundTypeDecl
= lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, RD
);
255 if (FoundTypeDecl
!= UnqualifiedTypeNameLookupResult::FoundType
)
258 // We found some types in dependent base classes. Recover as if the user
259 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
260 // lookup during template instantiation.
261 S
.Diag(NameLoc
, diag::ext_found_in_dependent_base
) << &II
;
263 ASTContext
&Context
= S
.Context
;
264 auto *NNS
= NestedNameSpecifier::Create(Context
, nullptr, false,
265 cast
<Type
>(Context
.getRecordType(RD
)));
266 QualType T
= Context
.getDependentNameType(ETK_Typename
, NNS
, &II
);
269 SS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
271 TypeLocBuilder Builder
;
272 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
273 DepTL
.setNameLoc(NameLoc
);
274 DepTL
.setElaboratedKeywordLoc(SourceLocation());
275 DepTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
276 return S
.CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
279 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
280 static ParsedType
buildNamedType(Sema
&S
, const CXXScopeSpec
*SS
, QualType T
,
281 SourceLocation NameLoc
,
282 bool WantNontrivialTypeSourceInfo
= true) {
283 switch (T
->getTypeClass()) {
284 case Type::DeducedTemplateSpecialization
:
286 case Type::InjectedClassName
:
289 case Type::UnresolvedUsing
:
292 // These can never be qualified so an ElaboratedType node
293 // would carry no additional meaning.
294 case Type::ObjCInterface
:
295 case Type::ObjCTypeParam
:
296 case Type::TemplateTypeParm
:
297 return ParsedType::make(T
);
299 llvm_unreachable("Unexpected Type Class");
302 if (!SS
|| SS
->isEmpty())
303 return ParsedType::make(
304 S
.Context
.getElaboratedType(ETK_None
, nullptr, T
, nullptr));
306 QualType ElTy
= S
.getElaboratedType(ETK_None
, *SS
, T
);
307 if (!WantNontrivialTypeSourceInfo
)
308 return ParsedType::make(ElTy
);
310 TypeLocBuilder Builder
;
311 Builder
.pushTypeSpec(T
).setNameLoc(NameLoc
);
312 ElaboratedTypeLoc ElabTL
= Builder
.push
<ElaboratedTypeLoc
>(ElTy
);
313 ElabTL
.setElaboratedKeywordLoc(SourceLocation());
314 ElabTL
.setQualifierLoc(SS
->getWithLocInContext(S
.Context
));
315 return S
.CreateParsedType(ElTy
, Builder
.getTypeSourceInfo(S
.Context
, ElTy
));
318 /// If the identifier refers to a type name within this scope,
319 /// return the declaration of that type.
321 /// This routine performs ordinary name lookup of the identifier II
322 /// within the given scope, with optional C++ scope specifier SS, to
323 /// determine whether the name refers to a type. If so, returns an
324 /// opaque pointer (actually a QualType) corresponding to that
325 /// type. Otherwise, returns NULL.
326 ParsedType
Sema::getTypeName(const IdentifierInfo
&II
, SourceLocation NameLoc
,
327 Scope
*S
, CXXScopeSpec
*SS
,
328 bool isClassName
, bool HasTrailingDot
,
329 ParsedType ObjectTypePtr
,
330 bool IsCtorOrDtorName
,
331 bool WantNontrivialTypeSourceInfo
,
332 bool IsClassTemplateDeductionContext
,
333 IdentifierInfo
**CorrectedII
) {
334 // FIXME: Consider allowing this outside C++1z mode as an extension.
335 bool AllowDeducedTemplate
= IsClassTemplateDeductionContext
&&
336 getLangOpts().CPlusPlus17
&& !IsCtorOrDtorName
&&
337 !isClassName
&& !HasTrailingDot
;
339 // Determine where we will perform name lookup.
340 DeclContext
*LookupCtx
= nullptr;
342 QualType ObjectType
= ObjectTypePtr
.get();
343 if (ObjectType
->isRecordType())
344 LookupCtx
= computeDeclContext(ObjectType
);
345 } else if (SS
&& SS
->isNotEmpty()) {
346 LookupCtx
= computeDeclContext(*SS
, false);
349 if (isDependentScopeSpecifier(*SS
)) {
351 // A qualified-id that refers to a type and in which the
352 // nested-name-specifier depends on a template-parameter (14.6.2)
353 // shall be prefixed by the keyword typename to indicate that the
354 // qualified-id denotes a type, forming an
355 // elaborated-type-specifier (7.1.5.3).
357 // We therefore do not perform any name lookup if the result would
358 // refer to a member of an unknown specialization.
359 if (!isClassName
&& !IsCtorOrDtorName
)
362 // We know from the grammar that this name refers to a type,
363 // so build a dependent node to describe the type.
364 if (WantNontrivialTypeSourceInfo
)
365 return ActOnTypenameType(S
, SourceLocation(), *SS
, II
, NameLoc
).get();
367 NestedNameSpecifierLoc QualifierLoc
= SS
->getWithLocInContext(Context
);
368 QualType T
= CheckTypenameType(ETK_None
, SourceLocation(), QualifierLoc
,
370 return ParsedType::make(T
);
376 if (!LookupCtx
->isDependentContext() &&
377 RequireCompleteDeclContext(*SS
, LookupCtx
))
381 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
382 // lookup for class-names.
383 LookupNameKind Kind
= isClassName
? LookupNestedNameSpecifierName
:
385 LookupResult
Result(*this, &II
, NameLoc
, Kind
);
387 // Perform "qualified" name lookup into the declaration context we
388 // computed, which is either the type of the base of a member access
389 // expression or the declaration context associated with a prior
390 // nested-name-specifier.
391 LookupQualifiedName(Result
, LookupCtx
);
393 if (ObjectTypePtr
&& Result
.empty()) {
394 // C++ [basic.lookup.classref]p3:
395 // If the unqualified-id is ~type-name, the type-name is looked up
396 // in the context of the entire postfix-expression. If the type T of
397 // the object expression is of a class type C, the type-name is also
398 // looked up in the scope of class C. At least one of the lookups shall
399 // find a name that refers to (possibly cv-qualified) T.
400 LookupName(Result
, S
);
403 // Perform unqualified name lookup.
404 LookupName(Result
, S
);
406 // For unqualified lookup in a class template in MSVC mode, look into
407 // dependent base classes where the primary class template is known.
408 if (Result
.empty() && getLangOpts().MSVCCompat
&& (!SS
|| SS
->isEmpty())) {
409 if (ParsedType TypeInBase
=
410 recoverFromTypeInKnownDependentBase(*this, II
, NameLoc
))
415 NamedDecl
*IIDecl
= nullptr;
416 UsingShadowDecl
*FoundUsingShadow
= nullptr;
417 switch (Result
.getResultKind()) {
418 case LookupResult::NotFound
:
419 case LookupResult::NotFoundInCurrentInstantiation
:
421 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/true, isClassName
,
422 AllowDeducedTemplate
);
423 TypoCorrection Correction
= CorrectTypo(Result
.getLookupNameInfo(), Kind
,
424 S
, SS
, CCC
, CTK_ErrorRecovery
);
425 IdentifierInfo
*NewII
= Correction
.getCorrectionAsIdentifierInfo();
427 bool MemberOfUnknownSpecialization
;
428 UnqualifiedId TemplateName
;
429 TemplateName
.setIdentifier(NewII
, NameLoc
);
430 NestedNameSpecifier
*NNS
= Correction
.getCorrectionSpecifier();
431 CXXScopeSpec NewSS
, *NewSSPtr
= SS
;
433 NewSS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
436 if (Correction
&& (NNS
|| NewII
!= &II
) &&
437 // Ignore a correction to a template type as the to-be-corrected
438 // identifier is not a template (typo correction for template names
439 // is handled elsewhere).
440 !(getLangOpts().CPlusPlus
&& NewSSPtr
&&
441 isTemplateName(S
, *NewSSPtr
, false, TemplateName
, nullptr, false,
442 Template
, MemberOfUnknownSpecialization
))) {
443 ParsedType Ty
= getTypeName(*NewII
, NameLoc
, S
, NewSSPtr
,
444 isClassName
, HasTrailingDot
, ObjectTypePtr
,
446 WantNontrivialTypeSourceInfo
,
447 IsClassTemplateDeductionContext
);
449 diagnoseTypo(Correction
,
450 PDiag(diag::err_unknown_type_or_class_name_suggest
)
451 << Result
.getLookupName() << isClassName
);
453 SS
->MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
454 *CorrectedII
= NewII
;
459 // If typo correction failed or was not performed, fall through
461 case LookupResult::FoundOverloaded
:
462 case LookupResult::FoundUnresolvedValue
:
463 Result
.suppressDiagnostics();
466 case LookupResult::Ambiguous
:
467 // Recover from type-hiding ambiguities by hiding the type. We'll
468 // do the lookup again when looking for an object, and we can
469 // diagnose the error then. If we don't do this, then the error
470 // about hiding the type will be immediately followed by an error
471 // that only makes sense if the identifier was treated like a type.
472 if (Result
.getAmbiguityKind() == LookupResult::AmbiguousTagHiding
) {
473 Result
.suppressDiagnostics();
477 // Look to see if we have a type anywhere in the list of results.
478 for (LookupResult::iterator Res
= Result
.begin(), ResEnd
= Result
.end();
479 Res
!= ResEnd
; ++Res
) {
480 NamedDecl
*RealRes
= (*Res
)->getUnderlyingDecl();
481 if (isa
<TypeDecl
, ObjCInterfaceDecl
, UnresolvedUsingIfExistsDecl
>(
483 (AllowDeducedTemplate
&& getAsTypeTemplateDecl(RealRes
))) {
485 // Make the selection of the recovery decl deterministic.
486 RealRes
->getLocation() < IIDecl
->getLocation()) {
488 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Res
);
494 // None of the entities we found is a type, so there is no way
495 // to even assume that the result is a type. In this case, don't
496 // complain about the ambiguity. The parser will either try to
497 // perform this lookup again (e.g., as an object name), which
498 // will produce the ambiguity, or will complain that it expected
500 Result
.suppressDiagnostics();
504 // We found a type within the ambiguous lookup; diagnose the
505 // ambiguity and then return that type. This might be the right
506 // answer, or it might not be, but it suppresses any attempt to
507 // perform the name lookup again.
510 case LookupResult::Found
:
511 IIDecl
= Result
.getFoundDecl();
512 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Result
.begin());
516 assert(IIDecl
&& "Didn't find decl");
519 if (TypeDecl
*TD
= dyn_cast
<TypeDecl
>(IIDecl
)) {
520 // C++ [class.qual]p2: A lookup that would find the injected-class-name
521 // instead names the constructors of the class, except when naming a class.
522 // This is ill-formed when we're not actually forming a ctor or dtor name.
523 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(LookupCtx
);
524 auto *FoundRD
= dyn_cast
<CXXRecordDecl
>(TD
);
525 if (!isClassName
&& !IsCtorOrDtorName
&& LookupRD
&& FoundRD
&&
526 FoundRD
->isInjectedClassName() &&
527 declaresSameEntity(LookupRD
, cast
<Decl
>(FoundRD
->getParent())))
528 Diag(NameLoc
, diag::err_out_of_line_qualified_id_type_names_constructor
)
531 DiagnoseUseOfDecl(IIDecl
, NameLoc
);
533 T
= Context
.getTypeDeclType(TD
);
534 MarkAnyDeclReferenced(TD
->getLocation(), TD
, /*OdrUse=*/false);
535 } else if (ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(IIDecl
)) {
536 (void)DiagnoseUseOfDecl(IDecl
, NameLoc
);
538 T
= Context
.getObjCInterfaceType(IDecl
);
539 FoundUsingShadow
= nullptr; // FIXME: Target must be a TypeDecl.
540 } else if (auto *UD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(IIDecl
)) {
541 (void)DiagnoseUseOfDecl(UD
, NameLoc
);
542 // Recover with 'int'
543 return ParsedType::make(Context
.IntTy
);
544 } else if (AllowDeducedTemplate
) {
545 if (auto *TD
= getAsTypeTemplateDecl(IIDecl
)) {
546 assert(!FoundUsingShadow
|| FoundUsingShadow
->getTargetDecl() == TD
);
547 TemplateName Template
=
548 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
549 T
= Context
.getDeducedTemplateSpecializationType(Template
, QualType(),
551 // Don't wrap in a further UsingType.
552 FoundUsingShadow
= nullptr;
557 // If it's not plausibly a type, suppress diagnostics.
558 Result
.suppressDiagnostics();
562 if (FoundUsingShadow
)
563 T
= Context
.getUsingType(FoundUsingShadow
, T
);
565 return buildNamedType(*this, SS
, T
, NameLoc
, WantNontrivialTypeSourceInfo
);
568 // Builds a fake NNS for the given decl context.
569 static NestedNameSpecifier
*
570 synthesizeCurrentNestedNameSpecifier(ASTContext
&Context
, DeclContext
*DC
) {
571 for (;; DC
= DC
->getLookupParent()) {
572 DC
= DC
->getPrimaryContext();
573 auto *ND
= dyn_cast
<NamespaceDecl
>(DC
);
574 if (ND
&& !ND
->isInline() && !ND
->isAnonymousNamespace())
575 return NestedNameSpecifier::Create(Context
, nullptr, ND
);
576 else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
577 return NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
578 RD
->getTypeForDecl());
579 else if (isa
<TranslationUnitDecl
>(DC
))
580 return NestedNameSpecifier::GlobalSpecifier(Context
);
582 llvm_unreachable("something isn't in TU scope?");
585 /// Find the parent class with dependent bases of the innermost enclosing method
586 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
587 /// up allowing unqualified dependent type names at class-level, which MSVC
588 /// correctly rejects.
589 static const CXXRecordDecl
*
590 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext
*DC
) {
591 for (; DC
&& DC
->isDependentContext(); DC
= DC
->getLookupParent()) {
592 DC
= DC
->getPrimaryContext();
593 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
594 if (MD
->getParent()->hasAnyDependentBases())
595 return MD
->getParent();
600 ParsedType
Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo
&II
,
601 SourceLocation NameLoc
,
602 bool IsTemplateTypeArg
) {
603 assert(getLangOpts().MSVCCompat
&& "shouldn't be called in non-MSVC mode");
605 NestedNameSpecifier
*NNS
= nullptr;
606 if (IsTemplateTypeArg
&& getCurScope()->isTemplateParamScope()) {
607 // If we weren't able to parse a default template argument, delay lookup
608 // until instantiation time by making a non-dependent DependentTypeName. We
609 // pretend we saw a NestedNameSpecifier referring to the current scope, and
610 // lookup is retried.
611 // FIXME: This hurts our diagnostic quality, since we get errors like "no
612 // type named 'Foo' in 'current_namespace'" when the user didn't write any
614 NNS
= synthesizeCurrentNestedNameSpecifier(Context
, CurContext
);
615 Diag(NameLoc
, diag::ext_ms_delayed_template_argument
) << &II
;
616 } else if (const CXXRecordDecl
*RD
=
617 findRecordWithDependentBasesOfEnclosingMethod(CurContext
)) {
618 // Build a DependentNameType that will perform lookup into RD at
619 // instantiation time.
620 NNS
= NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
621 RD
->getTypeForDecl());
623 // Diagnose that this identifier was undeclared, and retry the lookup during
624 // template instantiation.
625 Diag(NameLoc
, diag::ext_undeclared_unqual_id_with_dependent_base
) << &II
628 // This is not a situation that we should recover from.
632 QualType T
= Context
.getDependentNameType(ETK_None
, NNS
, &II
);
634 // Build type location information. We synthesized the qualifier, so we have
635 // to build a fake NestedNameSpecifierLoc.
636 NestedNameSpecifierLocBuilder NNSLocBuilder
;
637 NNSLocBuilder
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
638 NestedNameSpecifierLoc QualifierLoc
= NNSLocBuilder
.getWithLocInContext(Context
);
640 TypeLocBuilder Builder
;
641 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
642 DepTL
.setNameLoc(NameLoc
);
643 DepTL
.setElaboratedKeywordLoc(SourceLocation());
644 DepTL
.setQualifierLoc(QualifierLoc
);
645 return CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
648 /// isTagName() - This method is called *for error recovery purposes only*
649 /// to determine if the specified name is a valid tag name ("struct foo"). If
650 /// so, this returns the TST for the tag corresponding to it (TST_enum,
651 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
652 /// cases in C where the user forgot to specify the tag.
653 DeclSpec::TST
Sema::isTagName(IdentifierInfo
&II
, Scope
*S
) {
654 // Do a tag name lookup in this scope.
655 LookupResult
R(*this, &II
, SourceLocation(), LookupTagName
);
656 LookupName(R
, S
, false);
657 R
.suppressDiagnostics();
658 if (R
.getResultKind() == LookupResult::Found
)
659 if (const TagDecl
*TD
= R
.getAsSingle
<TagDecl
>()) {
660 switch (TD
->getTagKind()) {
661 case TTK_Struct
: return DeclSpec::TST_struct
;
662 case TTK_Interface
: return DeclSpec::TST_interface
;
663 case TTK_Union
: return DeclSpec::TST_union
;
664 case TTK_Class
: return DeclSpec::TST_class
;
665 case TTK_Enum
: return DeclSpec::TST_enum
;
669 return DeclSpec::TST_unspecified
;
672 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
673 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
674 /// then downgrade the missing typename error to a warning.
675 /// This is needed for MSVC compatibility; Example:
677 /// template<class T> class A {
679 /// typedef int TYPE;
681 /// template<class T> class B : public A<T> {
683 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
686 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec
*SS
, Scope
*S
) {
687 if (CurContext
->isRecord()) {
688 if (SS
->getScopeRep()->getKind() == NestedNameSpecifier::Super
)
691 const Type
*Ty
= SS
->getScopeRep()->getAsType();
693 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(CurContext
);
694 for (const auto &Base
: RD
->bases())
695 if (Ty
&& Context
.hasSameUnqualifiedType(QualType(Ty
, 1), Base
.getType()))
697 return S
->isFunctionPrototypeScope();
699 return CurContext
->isFunctionOrMethod() || S
->isFunctionPrototypeScope();
702 void Sema::DiagnoseUnknownTypeName(IdentifierInfo
*&II
,
703 SourceLocation IILoc
,
706 ParsedType
&SuggestedType
,
707 bool IsTemplateName
) {
708 // Don't report typename errors for editor placeholders.
709 if (II
->isEditorPlaceholder())
711 // We don't have anything to suggest (yet).
712 SuggestedType
= nullptr;
714 // There may have been a typo in the name of the type. Look up typo
715 // results, in case we have something that we can suggest.
716 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
717 /*AllowTemplates=*/IsTemplateName
,
718 /*AllowNonTemplates=*/!IsTemplateName
);
719 if (TypoCorrection Corrected
=
720 CorrectTypo(DeclarationNameInfo(II
, IILoc
), LookupOrdinaryName
, S
, SS
,
721 CCC
, CTK_ErrorRecovery
)) {
722 // FIXME: Support error recovery for the template-name case.
723 bool CanRecover
= !IsTemplateName
;
724 if (Corrected
.isKeyword()) {
725 // We corrected to a keyword.
726 diagnoseTypo(Corrected
,
727 PDiag(IsTemplateName
? diag::err_no_template_suggest
728 : diag::err_unknown_typename_suggest
)
730 II
= Corrected
.getCorrectionAsIdentifierInfo();
732 // We found a similarly-named type or interface; suggest that.
733 if (!SS
|| !SS
->isSet()) {
734 diagnoseTypo(Corrected
,
735 PDiag(IsTemplateName
? diag::err_no_template_suggest
736 : diag::err_unknown_typename_suggest
)
738 } else if (DeclContext
*DC
= computeDeclContext(*SS
, false)) {
739 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
740 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
741 II
->getName().equals(CorrectedStr
);
742 diagnoseTypo(Corrected
,
744 ? diag::err_no_member_template_suggest
745 : diag::err_unknown_nested_typename_suggest
)
746 << II
<< DC
<< DroppedSpecifier
<< SS
->getRange(),
749 llvm_unreachable("could not have corrected a typo here");
756 if (Corrected
.getCorrectionSpecifier())
757 tmpSS
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
759 // FIXME: Support class template argument deduction here.
761 getTypeName(*Corrected
.getCorrectionAsIdentifierInfo(), IILoc
, S
,
762 tmpSS
.isSet() ? &tmpSS
: SS
, false, false, nullptr,
763 /*IsCtorOrDtorName=*/false,
764 /*WantNontrivialTypeSourceInfo=*/true);
769 if (getLangOpts().CPlusPlus
&& !IsTemplateName
) {
770 // See if II is a class template that the user forgot to pass arguments to.
772 Name
.setIdentifier(II
, IILoc
);
773 CXXScopeSpec EmptySS
;
774 TemplateTy TemplateResult
;
775 bool MemberOfUnknownSpecialization
;
776 if (isTemplateName(S
, SS
? *SS
: EmptySS
, /*hasTemplateKeyword=*/false,
777 Name
, nullptr, true, TemplateResult
,
778 MemberOfUnknownSpecialization
) == TNK_Type_template
) {
779 diagnoseMissingTemplateArguments(TemplateResult
.get(), IILoc
);
784 // FIXME: Should we move the logic that tries to recover from a missing tag
785 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
787 if (!SS
|| (!SS
->isSet() && !SS
->isInvalid()))
788 Diag(IILoc
, IsTemplateName
? diag::err_no_template
789 : diag::err_unknown_typename
)
791 else if (DeclContext
*DC
= computeDeclContext(*SS
, false))
792 Diag(IILoc
, IsTemplateName
? diag::err_no_member_template
793 : diag::err_typename_nested_not_found
)
794 << II
<< DC
<< SS
->getRange();
795 else if (SS
->isValid() && SS
->getScopeRep()->containsErrors()) {
797 ActOnTypenameType(S
, SourceLocation(), *SS
, *II
, IILoc
).get();
798 } else if (isDependentScopeSpecifier(*SS
)) {
799 unsigned DiagID
= diag::err_typename_missing
;
800 if (getLangOpts().MSVCCompat
&& isMicrosoftMissingTypename(SS
, S
))
801 DiagID
= diag::ext_typename_missing
;
803 Diag(SS
->getRange().getBegin(), DiagID
)
804 << SS
->getScopeRep() << II
->getName()
805 << SourceRange(SS
->getRange().getBegin(), IILoc
)
806 << FixItHint::CreateInsertion(SS
->getRange().getBegin(), "typename ");
807 SuggestedType
= ActOnTypenameType(S
, SourceLocation(),
808 *SS
, *II
, IILoc
).get();
810 assert(SS
&& SS
->isInvalid() &&
811 "Invalid scope specifier has already been diagnosed");
815 /// Determine whether the given result set contains either a type name
817 static bool isResultTypeOrTemplate(LookupResult
&R
, const Token
&NextToken
) {
818 bool CheckTemplate
= R
.getSema().getLangOpts().CPlusPlus
&&
819 NextToken
.is(tok::less
);
821 for (LookupResult::iterator I
= R
.begin(), IEnd
= R
.end(); I
!= IEnd
; ++I
) {
822 if (isa
<TypeDecl
>(*I
) || isa
<ObjCInterfaceDecl
>(*I
))
825 if (CheckTemplate
&& isa
<TemplateDecl
>(*I
))
832 static bool isTagTypeWithMissingTag(Sema
&SemaRef
, LookupResult
&Result
,
833 Scope
*S
, CXXScopeSpec
&SS
,
834 IdentifierInfo
*&Name
,
835 SourceLocation NameLoc
) {
836 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupTagName
);
837 SemaRef
.LookupParsedName(R
, S
, &SS
);
838 if (TagDecl
*Tag
= R
.getAsSingle
<TagDecl
>()) {
839 StringRef FixItTagName
;
840 switch (Tag
->getTagKind()) {
842 FixItTagName
= "class ";
846 FixItTagName
= "enum ";
850 FixItTagName
= "struct ";
854 FixItTagName
= "__interface ";
858 FixItTagName
= "union ";
862 StringRef TagName
= FixItTagName
.drop_back();
863 SemaRef
.Diag(NameLoc
, diag::err_use_of_tag_name_without_tag
)
864 << Name
<< TagName
<< SemaRef
.getLangOpts().CPlusPlus
865 << FixItHint::CreateInsertion(NameLoc
, FixItTagName
);
867 for (LookupResult::iterator I
= Result
.begin(), IEnd
= Result
.end();
869 SemaRef
.Diag((*I
)->getLocation(), diag::note_decl_hiding_tag_type
)
872 // Replace lookup results with just the tag decl.
873 Result
.clear(Sema::LookupTagName
);
874 SemaRef
.LookupParsedName(Result
, S
, &SS
);
881 Sema::NameClassification
Sema::ClassifyName(Scope
*S
, CXXScopeSpec
&SS
,
882 IdentifierInfo
*&Name
,
883 SourceLocation NameLoc
,
884 const Token
&NextToken
,
885 CorrectionCandidateCallback
*CCC
) {
886 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
887 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
889 assert(NextToken
.isNot(tok::coloncolon
) &&
890 "parse nested name specifiers before calling ClassifyName");
891 if (getLangOpts().CPlusPlus
&& SS
.isSet() &&
892 isCurrentClassName(*Name
, S
, &SS
)) {
893 // Per [class.qual]p2, this names the constructors of SS, not the
894 // injected-class-name. We don't have a classification for that.
895 // There's not much point caching this result, since the parser
896 // will reject it later.
897 return NameClassification::Unknown();
900 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
901 LookupParsedName(Result
, S
, &SS
, !CurMethod
);
904 return NameClassification::Error();
906 // For unqualified lookup in a class template in MSVC mode, look into
907 // dependent base classes where the primary class template is known.
908 if (Result
.empty() && SS
.isEmpty() && getLangOpts().MSVCCompat
) {
909 if (ParsedType TypeInBase
=
910 recoverFromTypeInKnownDependentBase(*this, *Name
, NameLoc
))
914 // Perform lookup for Objective-C instance variables (including automatically
915 // synthesized instance variables), if we're in an Objective-C method.
916 // FIXME: This lookup really, really needs to be folded in to the normal
917 // unqualified lookup mechanism.
918 if (SS
.isEmpty() && CurMethod
&& !isResultTypeOrTemplate(Result
, NextToken
)) {
919 DeclResult Ivar
= LookupIvarInObjCMethod(Result
, S
, Name
);
920 if (Ivar
.isInvalid())
921 return NameClassification::Error();
923 return NameClassification::NonType(cast
<NamedDecl
>(Ivar
.get()));
925 // We defer builtin creation until after ivar lookup inside ObjC methods.
927 LookupBuiltin(Result
);
930 bool SecondTry
= false;
931 bool IsFilteredTemplateName
= false;
934 switch (Result
.getResultKind()) {
935 case LookupResult::NotFound
:
936 // If an unqualified-id is followed by a '(', then we have a function
938 if (SS
.isEmpty() && NextToken
.is(tok::l_paren
)) {
939 // In C++, this is an ADL-only call.
941 if (getLangOpts().CPlusPlus
)
942 return NameClassification::UndeclaredNonType();
945 // If the expression that precedes the parenthesized argument list in a
946 // function call consists solely of an identifier, and if no
947 // declaration is visible for this identifier, the identifier is
948 // implicitly declared exactly as if, in the innermost block containing
949 // the function call, the declaration
951 // extern int identifier ();
955 // We also allow this in C99 as an extension. However, this is not
956 // allowed in all language modes as functions without prototypes may not
958 if (getLangOpts().implicitFunctionsAllowed()) {
959 if (NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *Name
, S
))
960 return NameClassification::NonType(D
);
964 if (getLangOpts().CPlusPlus20
&& SS
.isEmpty() && NextToken
.is(tok::less
)) {
965 // In C++20 onwards, this could be an ADL-only call to a function
966 // template, and we're required to assume that this is a template name.
968 // FIXME: Find a way to still do typo correction in this case.
969 TemplateName Template
=
970 Context
.getAssumedTemplateName(NameInfo
.getName());
971 return NameClassification::UndeclaredTemplate(Template
);
974 // In C, we first see whether there is a tag type by the same name, in
975 // which case it's likely that the user just forgot to write "enum",
976 // "struct", or "union".
977 if (!getLangOpts().CPlusPlus
&& !SecondTry
&&
978 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
982 // Perform typo correction to determine if there is another name that is
983 // close to this name.
984 if (!SecondTry
&& CCC
) {
986 if (TypoCorrection Corrected
=
987 CorrectTypo(Result
.getLookupNameInfo(), Result
.getLookupKind(), S
,
988 &SS
, *CCC
, CTK_ErrorRecovery
)) {
989 unsigned UnqualifiedDiag
= diag::err_undeclared_var_use_suggest
;
990 unsigned QualifiedDiag
= diag::err_no_member_suggest
;
992 NamedDecl
*FirstDecl
= Corrected
.getFoundDecl();
993 NamedDecl
*UnderlyingFirstDecl
= Corrected
.getCorrectionDecl();
994 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
995 UnderlyingFirstDecl
&& isa
<TemplateDecl
>(UnderlyingFirstDecl
)) {
996 UnqualifiedDiag
= diag::err_no_template_suggest
;
997 QualifiedDiag
= diag::err_no_member_template_suggest
;
998 } else if (UnderlyingFirstDecl
&&
999 (isa
<TypeDecl
>(UnderlyingFirstDecl
) ||
1000 isa
<ObjCInterfaceDecl
>(UnderlyingFirstDecl
) ||
1001 isa
<ObjCCompatibleAliasDecl
>(UnderlyingFirstDecl
))) {
1002 UnqualifiedDiag
= diag::err_unknown_typename_suggest
;
1003 QualifiedDiag
= diag::err_unknown_nested_typename_suggest
;
1007 diagnoseTypo(Corrected
, PDiag(UnqualifiedDiag
) << Name
);
1008 } else {// FIXME: is this even reachable? Test it.
1009 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
1010 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
1011 Name
->getName().equals(CorrectedStr
);
1012 diagnoseTypo(Corrected
, PDiag(QualifiedDiag
)
1013 << Name
<< computeDeclContext(SS
, false)
1014 << DroppedSpecifier
<< SS
.getRange());
1017 // Update the name, so that the caller has the new name.
1018 Name
= Corrected
.getCorrectionAsIdentifierInfo();
1020 // Typo correction corrected to a keyword.
1021 if (Corrected
.isKeyword())
1024 // Also update the LookupResult...
1025 // FIXME: This should probably go away at some point
1027 Result
.setLookupName(Corrected
.getCorrection());
1029 Result
.addDecl(FirstDecl
);
1031 // If we found an Objective-C instance variable, let
1032 // LookupInObjCMethod build the appropriate expression to
1033 // reference the ivar.
1034 // FIXME: This is a gross hack.
1035 if (ObjCIvarDecl
*Ivar
= Result
.getAsSingle
<ObjCIvarDecl
>()) {
1037 LookupIvarInObjCMethod(Result
, S
, Ivar
->getIdentifier());
1039 return NameClassification::Error();
1041 return NameClassification::NonType(Ivar
);
1048 // We failed to correct; just fall through and let the parser deal with it.
1049 Result
.suppressDiagnostics();
1050 return NameClassification::Unknown();
1052 case LookupResult::NotFoundInCurrentInstantiation
: {
1053 // We performed name lookup into the current instantiation, and there were
1054 // dependent bases, so we treat this result the same way as any other
1055 // dependent nested-name-specifier.
1057 // C++ [temp.res]p2:
1058 // A name used in a template declaration or definition and that is
1059 // dependent on a template-parameter is assumed not to name a type
1060 // unless the applicable name lookup finds a type name or the name is
1061 // qualified by the keyword typename.
1063 // FIXME: If the next token is '<', we might want to ask the parser to
1064 // perform some heroics to see if we actually have a
1065 // template-argument-list, which would indicate a missing 'template'
1067 return NameClassification::DependentNonType();
1070 case LookupResult::Found
:
1071 case LookupResult::FoundOverloaded
:
1072 case LookupResult::FoundUnresolvedValue
:
1075 case LookupResult::Ambiguous
:
1076 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1077 hasAnyAcceptableTemplateNames(Result
, /*AllowFunctionTemplates=*/true,
1078 /*AllowDependent=*/false)) {
1079 // C++ [temp.local]p3:
1080 // A lookup that finds an injected-class-name (10.2) can result in an
1081 // ambiguity in certain cases (for example, if it is found in more than
1082 // one base class). If all of the injected-class-names that are found
1083 // refer to specializations of the same class template, and if the name
1084 // is followed by a template-argument-list, the reference refers to the
1085 // class template itself and not a specialization thereof, and is not
1088 // This filtering can make an ambiguous result into an unambiguous one,
1089 // so try again after filtering out template names.
1090 FilterAcceptableTemplateNames(Result
);
1091 if (!Result
.isAmbiguous()) {
1092 IsFilteredTemplateName
= true;
1097 // Diagnose the ambiguity and return an error.
1098 return NameClassification::Error();
1101 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1102 (IsFilteredTemplateName
||
1103 hasAnyAcceptableTemplateNames(
1104 Result
, /*AllowFunctionTemplates=*/true,
1105 /*AllowDependent=*/false,
1106 /*AllowNonTemplateFunctions*/ SS
.isEmpty() &&
1107 getLangOpts().CPlusPlus20
))) {
1108 // C++ [temp.names]p3:
1109 // After name lookup (3.4) finds that a name is a template-name or that
1110 // an operator-function-id or a literal- operator-id refers to a set of
1111 // overloaded functions any member of which is a function template if
1112 // this is followed by a <, the < is always taken as the delimiter of a
1113 // template-argument-list and never as the less-than operator.
1114 // C++2a [temp.names]p2:
1115 // A name is also considered to refer to a template if it is an
1116 // unqualified-id followed by a < and name lookup finds either one
1117 // or more functions or finds nothing.
1118 if (!IsFilteredTemplateName
)
1119 FilterAcceptableTemplateNames(Result
);
1121 bool IsFunctionTemplate
;
1123 TemplateName Template
;
1124 if (Result
.end() - Result
.begin() > 1) {
1125 IsFunctionTemplate
= true;
1126 Template
= Context
.getOverloadedTemplateName(Result
.begin(),
1128 } else if (!Result
.empty()) {
1129 auto *TD
= cast
<TemplateDecl
>(getAsTemplateNameDecl(
1130 *Result
.begin(), /*AllowFunctionTemplates=*/true,
1131 /*AllowDependent=*/false));
1132 IsFunctionTemplate
= isa
<FunctionTemplateDecl
>(TD
);
1133 IsVarTemplate
= isa
<VarTemplateDecl
>(TD
);
1135 UsingShadowDecl
*FoundUsingShadow
=
1136 dyn_cast
<UsingShadowDecl
>(*Result
.begin());
1137 assert(!FoundUsingShadow
||
1138 TD
== cast
<TemplateDecl
>(FoundUsingShadow
->getTargetDecl()));
1140 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
1141 if (SS
.isNotEmpty())
1142 Template
= Context
.getQualifiedTemplateName(SS
.getScopeRep(),
1143 /*TemplateKeyword=*/false,
1146 // All results were non-template functions. This is a function template
1148 IsFunctionTemplate
= true;
1149 Template
= Context
.getAssumedTemplateName(NameInfo
.getName());
1152 if (IsFunctionTemplate
) {
1153 // Function templates always go through overload resolution, at which
1154 // point we'll perform the various checks (e.g., accessibility) we need
1155 // to based on which function we selected.
1156 Result
.suppressDiagnostics();
1158 return NameClassification::FunctionTemplate(Template
);
1161 return IsVarTemplate
? NameClassification::VarTemplate(Template
)
1162 : NameClassification::TypeTemplate(Template
);
1165 auto BuildTypeFor
= [&](TypeDecl
*Type
, NamedDecl
*Found
) {
1166 QualType T
= Context
.getTypeDeclType(Type
);
1167 if (const auto *USD
= dyn_cast
<UsingShadowDecl
>(Found
))
1168 T
= Context
.getUsingType(USD
, T
);
1169 return buildNamedType(*this, &SS
, T
, NameLoc
);
1172 NamedDecl
*FirstDecl
= (*Result
.begin())->getUnderlyingDecl();
1173 if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(FirstDecl
)) {
1174 DiagnoseUseOfDecl(Type
, NameLoc
);
1175 MarkAnyDeclReferenced(Type
->getLocation(), Type
, /*OdrUse=*/false);
1176 return BuildTypeFor(Type
, *Result
.begin());
1179 ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(FirstDecl
);
1181 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1182 if (ObjCCompatibleAliasDecl
*Alias
=
1183 dyn_cast
<ObjCCompatibleAliasDecl
>(FirstDecl
))
1184 Class
= Alias
->getClassInterface();
1188 DiagnoseUseOfDecl(Class
, NameLoc
);
1190 if (NextToken
.is(tok::period
)) {
1191 // Interface. <something> is parsed as a property reference expression.
1192 // Just return "unknown" as a fall-through for now.
1193 Result
.suppressDiagnostics();
1194 return NameClassification::Unknown();
1197 QualType T
= Context
.getObjCInterfaceType(Class
);
1198 return ParsedType::make(T
);
1201 if (isa
<ConceptDecl
>(FirstDecl
))
1202 return NameClassification::Concept(
1203 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1205 if (auto *EmptyD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(FirstDecl
)) {
1206 (void)DiagnoseUseOfDecl(EmptyD
, NameLoc
);
1207 return NameClassification::Error();
1210 // We can have a type template here if we're classifying a template argument.
1211 if (isa
<TemplateDecl
>(FirstDecl
) && !isa
<FunctionTemplateDecl
>(FirstDecl
) &&
1212 !isa
<VarTemplateDecl
>(FirstDecl
))
1213 return NameClassification::TypeTemplate(
1214 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1216 // Check for a tag type hidden by a non-type decl in a few cases where it
1217 // seems likely a type is wanted instead of the non-type that was found.
1218 bool NextIsOp
= NextToken
.isOneOf(tok::amp
, tok::star
);
1219 if ((NextToken
.is(tok::identifier
) ||
1221 FirstDecl
->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1222 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
1223 TypeDecl
*Type
= Result
.getAsSingle
<TypeDecl
>();
1224 DiagnoseUseOfDecl(Type
, NameLoc
);
1225 return BuildTypeFor(Type
, *Result
.begin());
1228 // If we already know which single declaration is referenced, just annotate
1229 // that declaration directly. Defer resolving even non-overloaded class
1230 // member accesses, as we need to defer certain access checks until we know
1232 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1233 if (Result
.isSingleResult() && !ADL
&& !FirstDecl
->isCXXClassMember())
1234 return NameClassification::NonType(Result
.getRepresentativeDecl());
1236 // Otherwise, this is an overload set that we will need to resolve later.
1237 Result
.suppressDiagnostics();
1238 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1239 Context
, Result
.getNamingClass(), SS
.getWithLocInContext(Context
),
1240 Result
.getLookupNameInfo(), ADL
, Result
.isOverloadedResult(),
1241 Result
.begin(), Result
.end()));
1245 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo
*Name
,
1246 SourceLocation NameLoc
) {
1247 assert(getLangOpts().CPlusPlus
&& "ADL-only call in C?");
1249 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
1250 return BuildDeclarationNameExpr(SS
, Result
, /*ADL=*/true);
1254 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec
&SS
,
1255 IdentifierInfo
*Name
,
1256 SourceLocation NameLoc
,
1257 bool IsAddressOfOperand
) {
1258 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
1259 return ActOnDependentIdExpression(SS
, /*TemplateKWLoc=*/SourceLocation(),
1260 NameInfo
, IsAddressOfOperand
,
1261 /*TemplateArgs=*/nullptr);
1264 ExprResult
Sema::ActOnNameClassifiedAsNonType(Scope
*S
, const CXXScopeSpec
&SS
,
1266 SourceLocation NameLoc
,
1267 const Token
&NextToken
) {
1268 if (getCurMethodDecl() && SS
.isEmpty())
1269 if (auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(Found
->getUnderlyingDecl()))
1270 return BuildIvarRefExpr(S
, NameLoc
, Ivar
);
1272 // Reconstruct the lookup result.
1273 LookupResult
Result(*this, Found
->getDeclName(), NameLoc
, LookupOrdinaryName
);
1274 Result
.addDecl(Found
);
1275 Result
.resolveKind();
1277 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1278 return BuildDeclarationNameExpr(SS
, Result
, ADL
);
1281 ExprResult
Sema::ActOnNameClassifiedAsOverloadSet(Scope
*S
, Expr
*E
) {
1282 // For an implicit class member access, transform the result into a member
1283 // access expression if necessary.
1284 auto *ULE
= cast
<UnresolvedLookupExpr
>(E
);
1285 if ((*ULE
->decls_begin())->isCXXClassMember()) {
1287 SS
.Adopt(ULE
->getQualifierLoc());
1289 // Reconstruct the lookup result.
1290 LookupResult
Result(*this, ULE
->getName(), ULE
->getNameLoc(),
1291 LookupOrdinaryName
);
1292 Result
.setNamingClass(ULE
->getNamingClass());
1293 for (auto I
= ULE
->decls_begin(), E
= ULE
->decls_end(); I
!= E
; ++I
)
1294 Result
.addDecl(*I
, I
.getAccess());
1295 Result
.resolveKind();
1296 return BuildPossibleImplicitMemberExpr(SS
, SourceLocation(), Result
,
1300 // Otherwise, this is already in the form we needed, and no further checks
1305 Sema::TemplateNameKindForDiagnostics
1306 Sema::getTemplateNameKindForDiagnostics(TemplateName Name
) {
1307 auto *TD
= Name
.getAsTemplateDecl();
1309 return TemplateNameKindForDiagnostics::DependentTemplate
;
1310 if (isa
<ClassTemplateDecl
>(TD
))
1311 return TemplateNameKindForDiagnostics::ClassTemplate
;
1312 if (isa
<FunctionTemplateDecl
>(TD
))
1313 return TemplateNameKindForDiagnostics::FunctionTemplate
;
1314 if (isa
<VarTemplateDecl
>(TD
))
1315 return TemplateNameKindForDiagnostics::VarTemplate
;
1316 if (isa
<TypeAliasTemplateDecl
>(TD
))
1317 return TemplateNameKindForDiagnostics::AliasTemplate
;
1318 if (isa
<TemplateTemplateParmDecl
>(TD
))
1319 return TemplateNameKindForDiagnostics::TemplateTemplateParam
;
1320 if (isa
<ConceptDecl
>(TD
))
1321 return TemplateNameKindForDiagnostics::Concept
;
1322 return TemplateNameKindForDiagnostics::DependentTemplate
;
1325 void Sema::PushDeclContext(Scope
*S
, DeclContext
*DC
) {
1326 assert(DC
->getLexicalParent() == CurContext
&&
1327 "The next DeclContext should be lexically contained in the current one.");
1332 void Sema::PopDeclContext() {
1333 assert(CurContext
&& "DeclContext imbalance!");
1335 CurContext
= CurContext
->getLexicalParent();
1336 assert(CurContext
&& "Popped translation unit!");
1339 Sema::SkippedDefinitionContext
Sema::ActOnTagStartSkippedDefinition(Scope
*S
,
1341 // Unlike PushDeclContext, the context to which we return is not necessarily
1342 // the containing DC of TD, because the new context will be some pre-existing
1343 // TagDecl definition instead of a fresh one.
1344 auto Result
= static_cast<SkippedDefinitionContext
>(CurContext
);
1345 CurContext
= cast
<TagDecl
>(D
)->getDefinition();
1346 assert(CurContext
&& "skipping definition of undefined tag");
1347 // Start lookups from the parent of the current context; we don't want to look
1348 // into the pre-existing complete definition.
1349 S
->setEntity(CurContext
->getLookupParent());
1353 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context
) {
1354 CurContext
= static_cast<decltype(CurContext
)>(Context
);
1357 /// EnterDeclaratorContext - Used when we must lookup names in the context
1358 /// of a declarator's nested name specifier.
1360 void Sema::EnterDeclaratorContext(Scope
*S
, DeclContext
*DC
) {
1361 // C++0x [basic.lookup.unqual]p13:
1362 // A name used in the definition of a static data member of class
1363 // X (after the qualified-id of the static member) is looked up as
1364 // if the name was used in a member function of X.
1365 // C++0x [basic.lookup.unqual]p14:
1366 // If a variable member of a namespace is defined outside of the
1367 // scope of its namespace then any name used in the definition of
1368 // the variable member (after the declarator-id) is looked up as
1369 // if the definition of the variable member occurred in its
1371 // Both of these imply that we should push a scope whose context
1372 // is the semantic context of the declaration. We can't use
1373 // PushDeclContext here because that context is not necessarily
1374 // lexically contained in the current context. Fortunately,
1375 // the containing scope should have the appropriate information.
1377 assert(!S
->getEntity() && "scope already has entity");
1380 Scope
*Ancestor
= S
->getParent();
1381 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1382 assert(Ancestor
->getEntity() == CurContext
&& "ancestor context mismatch");
1388 if (S
->getParent()->isTemplateParamScope()) {
1389 // Also set the corresponding entities for all immediately-enclosing
1390 // template parameter scopes.
1391 EnterTemplatedContext(S
->getParent(), DC
);
1395 void Sema::ExitDeclaratorContext(Scope
*S
) {
1396 assert(S
->getEntity() == CurContext
&& "Context imbalance!");
1398 // Switch back to the lexical context. The safety of this is
1399 // enforced by an assert in EnterDeclaratorContext.
1400 Scope
*Ancestor
= S
->getParent();
1401 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1402 CurContext
= Ancestor
->getEntity();
1404 // We don't need to do anything with the scope, which is going to
1408 void Sema::EnterTemplatedContext(Scope
*S
, DeclContext
*DC
) {
1409 assert(S
->isTemplateParamScope() &&
1410 "expected to be initializing a template parameter scope");
1412 // C++20 [temp.local]p7:
1413 // In the definition of a member of a class template that appears outside
1414 // of the class template definition, the name of a member of the class
1415 // template hides the name of a template-parameter of any enclosing class
1416 // templates (but not a template-parameter of the member if the member is a
1417 // class or function template).
1418 // C++20 [temp.local]p9:
1419 // In the definition of a class template or in the definition of a member
1420 // of such a template that appears outside of the template definition, for
1421 // each non-dependent base class (13.8.2.1), if the name of the base class
1422 // or the name of a member of the base class is the same as the name of a
1423 // template-parameter, the base class name or member name hides the
1424 // template-parameter name (6.4.10).
1426 // This means that a template parameter scope should be searched immediately
1427 // after searching the DeclContext for which it is a template parameter
1428 // scope. For example, for
1429 // template<typename T> template<typename U> template<typename V>
1430 // void N::A<T>::B<U>::f(...)
1431 // we search V then B<U> (and base classes) then U then A<T> (and base
1432 // classes) then T then N then ::.
1433 unsigned ScopeDepth
= getTemplateDepth(S
);
1434 for (; S
&& S
->isTemplateParamScope(); S
= S
->getParent(), --ScopeDepth
) {
1435 DeclContext
*SearchDCAfterScope
= DC
;
1436 for (; DC
; DC
= DC
->getLookupParent()) {
1437 if (const TemplateParameterList
*TPL
=
1438 cast
<Decl
>(DC
)->getDescribedTemplateParams()) {
1439 unsigned DCDepth
= TPL
->getDepth() + 1;
1440 if (DCDepth
> ScopeDepth
)
1442 if (ScopeDepth
== DCDepth
)
1443 SearchDCAfterScope
= DC
= DC
->getLookupParent();
1447 S
->setLookupEntity(SearchDCAfterScope
);
1451 void Sema::ActOnReenterFunctionContext(Scope
* S
, Decl
*D
) {
1452 // We assume that the caller has already called
1453 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1454 FunctionDecl
*FD
= D
->getAsFunction();
1458 // Same implementation as PushDeclContext, but enters the context
1459 // from the lexical parent, rather than the top-level class.
1460 assert(CurContext
== FD
->getLexicalParent() &&
1461 "The next DeclContext should be lexically contained in the current one.");
1463 S
->setEntity(CurContext
);
1465 for (unsigned P
= 0, NumParams
= FD
->getNumParams(); P
< NumParams
; ++P
) {
1466 ParmVarDecl
*Param
= FD
->getParamDecl(P
);
1467 // If the parameter has an identifier, then add it to the scope
1468 if (Param
->getIdentifier()) {
1470 IdResolver
.AddDecl(Param
);
1475 void Sema::ActOnExitFunctionContext() {
1476 // Same implementation as PopDeclContext, but returns to the lexical parent,
1477 // rather than the top-level class.
1478 assert(CurContext
&& "DeclContext imbalance!");
1479 CurContext
= CurContext
->getLexicalParent();
1480 assert(CurContext
&& "Popped translation unit!");
1483 /// Determine whether overloading is allowed for a new function
1484 /// declaration considering prior declarations of the same name.
1486 /// This routine determines whether overloading is possible, not
1487 /// whether a new declaration actually overloads a previous one.
1488 /// It will return true in C++ (where overloads are alway permitted)
1489 /// or, as a C extension, when either the new declaration or a
1490 /// previous one is declared with the 'overloadable' attribute.
1491 static bool AllowOverloadingOfFunction(const LookupResult
&Previous
,
1492 ASTContext
&Context
,
1493 const FunctionDecl
*New
) {
1494 if (Context
.getLangOpts().CPlusPlus
|| New
->hasAttr
<OverloadableAttr
>())
1497 // Multiversion function declarations are not overloads in the
1498 // usual sense of that term, but lookup will report that an
1499 // overload set was found if more than one multiversion function
1500 // declaration is present for the same name. It is therefore
1501 // inadequate to assume that some prior declaration(s) had
1502 // the overloadable attribute; checking is required. Since one
1503 // declaration is permitted to omit the attribute, it is necessary
1504 // to check at least two; hence the 'any_of' check below. Note that
1505 // the overloadable attribute is implicitly added to declarations
1506 // that were required to have it but did not.
1507 if (Previous
.getResultKind() == LookupResult::FoundOverloaded
) {
1508 return llvm::any_of(Previous
, [](const NamedDecl
*ND
) {
1509 return ND
->hasAttr
<OverloadableAttr
>();
1511 } else if (Previous
.getResultKind() == LookupResult::Found
)
1512 return Previous
.getFoundDecl()->hasAttr
<OverloadableAttr
>();
1517 /// Add this decl to the scope shadowed decl chains.
1518 void Sema::PushOnScopeChains(NamedDecl
*D
, Scope
*S
, bool AddToContext
) {
1519 // Move up the scope chain until we find the nearest enclosing
1520 // non-transparent context. The declaration will be introduced into this
1522 while (S
->getEntity() && S
->getEntity()->isTransparentContext())
1525 // Add scoped declarations into their context, so that they can be
1526 // found later. Declarations without a context won't be inserted
1527 // into any context.
1529 CurContext
->addDecl(D
);
1531 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1532 // are function-local declarations.
1533 if (getLangOpts().CPlusPlus
&& D
->isOutOfLine() && !S
->getFnParent())
1536 // Template instantiations should also not be pushed into scope.
1537 if (isa
<FunctionDecl
>(D
) &&
1538 cast
<FunctionDecl
>(D
)->isFunctionTemplateSpecialization())
1541 // If this replaces anything in the current scope,
1542 IdentifierResolver::iterator I
= IdResolver
.begin(D
->getDeclName()),
1543 IEnd
= IdResolver
.end();
1544 for (; I
!= IEnd
; ++I
) {
1545 if (S
->isDeclScope(*I
) && D
->declarationReplaces(*I
)) {
1547 IdResolver
.RemoveDecl(*I
);
1549 // Should only need to replace one decl.
1556 if (isa
<LabelDecl
>(D
) && !cast
<LabelDecl
>(D
)->isGnuLocal()) {
1557 // Implicitly-generated labels may end up getting generated in an order that
1558 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1559 // the label at the appropriate place in the identifier chain.
1560 for (I
= IdResolver
.begin(D
->getDeclName()); I
!= IEnd
; ++I
) {
1561 DeclContext
*IDC
= (*I
)->getLexicalDeclContext()->getRedeclContext();
1562 if (IDC
== CurContext
) {
1563 if (!S
->isDeclScope(*I
))
1565 } else if (IDC
->Encloses(CurContext
))
1569 IdResolver
.InsertDeclAfter(I
, D
);
1571 IdResolver
.AddDecl(D
);
1573 warnOnReservedIdentifier(D
);
1576 bool Sema::isDeclInScope(NamedDecl
*D
, DeclContext
*Ctx
, Scope
*S
,
1577 bool AllowInlineNamespace
) {
1578 return IdResolver
.isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
);
1581 Scope
*Sema::getScopeForDeclContext(Scope
*S
, DeclContext
*DC
) {
1582 DeclContext
*TargetDC
= DC
->getPrimaryContext();
1584 if (DeclContext
*ScopeDC
= S
->getEntity())
1585 if (ScopeDC
->getPrimaryContext() == TargetDC
)
1587 } while ((S
= S
->getParent()));
1592 static bool isOutOfScopePreviousDeclaration(NamedDecl
*,
1596 /// Filters out lookup results that don't fall within the given scope
1597 /// as determined by isDeclInScope.
1598 void Sema::FilterLookupForScope(LookupResult
&R
, DeclContext
*Ctx
, Scope
*S
,
1599 bool ConsiderLinkage
,
1600 bool AllowInlineNamespace
) {
1601 LookupResult::Filter F
= R
.makeFilter();
1602 while (F
.hasNext()) {
1603 NamedDecl
*D
= F
.next();
1605 if (isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
))
1608 if (ConsiderLinkage
&& isOutOfScopePreviousDeclaration(D
, Ctx
, Context
))
1617 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1618 /// have compatible owning modules.
1619 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl
*New
, NamedDecl
*Old
) {
1620 // [module.interface]p7:
1621 // A declaration is attached to a module as follows:
1622 // - If the declaration is a non-dependent friend declaration that nominates a
1623 // function with a declarator-id that is a qualified-id or template-id or that
1624 // nominates a class other than with an elaborated-type-specifier with neither
1625 // a nested-name-specifier nor a simple-template-id, it is attached to the
1626 // module to which the friend is attached ([basic.link]).
1627 if (New
->getFriendObjectKind() &&
1628 Old
->getOwningModuleForLinkage() != New
->getOwningModuleForLinkage()) {
1629 New
->setLocalOwningModule(Old
->getOwningModule());
1630 makeMergedDefinitionVisible(New
);
1634 Module
*NewM
= New
->getOwningModule();
1635 Module
*OldM
= Old
->getOwningModule();
1637 if (NewM
&& NewM
->isPrivateModule())
1638 NewM
= NewM
->Parent
;
1639 if (OldM
&& OldM
->isPrivateModule())
1640 OldM
= OldM
->Parent
;
1645 // Partitions are part of the module, but a partition could import another
1646 // module, so verify that the PMIs agree.
1647 if (NewM
&& OldM
&& (NewM
->isModulePartition() || OldM
->isModulePartition()))
1648 return NewM
->getPrimaryModuleInterfaceName() ==
1649 OldM
->getPrimaryModuleInterfaceName();
1651 bool NewIsModuleInterface
= NewM
&& NewM
->isModulePurview();
1652 bool OldIsModuleInterface
= OldM
&& OldM
->isModulePurview();
1653 if (NewIsModuleInterface
|| OldIsModuleInterface
) {
1654 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1655 // if a declaration of D [...] appears in the purview of a module, all
1656 // other such declarations shall appear in the purview of the same module
1657 Diag(New
->getLocation(), diag::err_mismatched_owning_module
)
1659 << NewIsModuleInterface
1660 << (NewIsModuleInterface
? NewM
->getFullModuleName() : "")
1661 << OldIsModuleInterface
1662 << (OldIsModuleInterface
? OldM
->getFullModuleName() : "");
1663 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1664 New
->setInvalidDecl();
1671 // [module.interface]p6:
1672 // A redeclaration of an entity X is implicitly exported if X was introduced by
1673 // an exported declaration; otherwise it shall not be exported.
1674 bool Sema::CheckRedeclarationExported(NamedDecl
*New
, NamedDecl
*Old
) {
1675 // [module.interface]p1:
1676 // An export-declaration shall inhabit a namespace scope.
1678 // So it is meaningless to talk about redeclaration which is not at namespace
1680 if (!New
->getLexicalDeclContext()
1681 ->getNonTransparentContext()
1682 ->isFileContext() ||
1683 !Old
->getLexicalDeclContext()
1684 ->getNonTransparentContext()
1688 bool IsNewExported
= New
->isInExportDeclContext();
1689 bool IsOldExported
= Old
->isInExportDeclContext();
1691 // It should be irrevelant if both of them are not exported.
1692 if (!IsNewExported
&& !IsOldExported
)
1698 assert(IsNewExported
);
1700 auto Lk
= Old
->getFormalLinkage();
1702 if (Lk
== Linkage::InternalLinkage
)
1704 else if (Lk
== Linkage::ModuleLinkage
)
1706 Diag(New
->getLocation(), diag::err_redeclaration_non_exported
) << New
<< S
;
1707 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1711 // A wrapper function for checking the semantic restrictions of
1712 // a redeclaration within a module.
1713 bool Sema::CheckRedeclarationInModule(NamedDecl
*New
, NamedDecl
*Old
) {
1714 if (CheckRedeclarationModuleOwnership(New
, Old
))
1717 if (CheckRedeclarationExported(New
, Old
))
1723 // Check the redefinition in C++20 Modules.
1725 // [basic.def.odr]p14:
1726 // For any definable item D with definitions in multiple translation units,
1727 // - if D is a non-inline non-templated function or variable, or
1728 // - if the definitions in different translation units do not satisfy the
1729 // following requirements,
1730 // the program is ill-formed; a diagnostic is required only if the definable
1731 // item is attached to a named module and a prior definition is reachable at
1732 // the point where a later definition occurs.
1733 // - Each such definition shall not be attached to a named module
1735 // - Each such definition shall consist of the same sequence of tokens, ...
1738 // Return true if the redefinition is not allowed. Return false otherwise.
1739 bool Sema::IsRedefinitionInModule(const NamedDecl
*New
,
1740 const NamedDecl
*Old
) const {
1741 assert(getASTContext().isSameEntity(New
, Old
) &&
1742 "New and Old are not the same definition, we should diagnostic it "
1743 "immediately instead of checking it.");
1744 assert(const_cast<Sema
*>(this)->isReachable(New
) &&
1745 const_cast<Sema
*>(this)->isReachable(Old
) &&
1746 "We shouldn't see unreachable definitions here.");
1748 Module
*NewM
= New
->getOwningModule();
1749 Module
*OldM
= Old
->getOwningModule();
1751 // We only checks for named modules here. The header like modules is skipped.
1752 // FIXME: This is not right if we import the header like modules in the module
1755 // For example, assuming "header.h" provides definition for `D`.
1759 // import "header.h"; // or #include "header.h" but import it by clang modules
1764 // import "header.h"; // or uses clang modules.
1767 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1768 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1769 // reject it. But the current implementation couldn't detect the case since we
1770 // don't record the information about the importee modules.
1772 // But this might not be painful in practice. Since the design of C++20 Named
1773 // Modules suggests us to use headers in global module fragment instead of
1775 if (NewM
&& NewM
->isHeaderLikeModule())
1777 if (OldM
&& OldM
->isHeaderLikeModule())
1783 // [basic.def.odr]p14.3
1784 // Each such definition shall not be attached to a named module
1786 if ((NewM
&& NewM
->isModulePurview()) || (OldM
&& OldM
->isModulePurview()))
1789 // Then New and Old lives in the same TU if their share one same module unit.
1791 NewM
= NewM
->getTopLevelModule();
1793 OldM
= OldM
->getTopLevelModule();
1794 return OldM
== NewM
;
1797 static bool isUsingDecl(NamedDecl
*D
) {
1798 return isa
<UsingShadowDecl
>(D
) ||
1799 isa
<UnresolvedUsingTypenameDecl
>(D
) ||
1800 isa
<UnresolvedUsingValueDecl
>(D
);
1803 /// Removes using shadow declarations from the lookup results.
1804 static void RemoveUsingDecls(LookupResult
&R
) {
1805 LookupResult::Filter F
= R
.makeFilter();
1807 if (isUsingDecl(F
.next()))
1813 /// Check for this common pattern:
1816 /// S(const S&); // DO NOT IMPLEMENT
1817 /// void operator=(const S&); // DO NOT IMPLEMENT
1820 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl
*D
) {
1821 // FIXME: Should check for private access too but access is set after we get
1823 if (D
->doesThisDeclarationHaveABody())
1826 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(D
))
1827 return CD
->isCopyConstructor();
1828 return D
->isCopyAssignmentOperator();
1831 // We need this to handle
1834 // void *foo() { return 0; }
1837 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1838 // for example. If 'A', foo will have external linkage. If we have '*A',
1839 // foo will have no linkage. Since we can't know until we get to the end
1840 // of the typedef, this function finds out if D might have non-external linkage.
1841 // Callers should verify at the end of the TU if it D has external linkage or
1843 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl
*D
) {
1844 const DeclContext
*DC
= D
->getDeclContext();
1845 while (!DC
->isTranslationUnit()) {
1846 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(DC
)){
1847 if (!RD
->hasNameForLinkage())
1850 DC
= DC
->getParent();
1853 return !D
->isExternallyVisible();
1856 // FIXME: This needs to be refactored; some other isInMainFile users want
1858 static bool isMainFileLoc(const Sema
&S
, SourceLocation Loc
) {
1859 if (S
.TUKind
!= TU_Complete
|| S
.getLangOpts().IsHeaderFile
)
1861 return S
.SourceMgr
.isInMainFile(Loc
);
1864 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl
*D
) const {
1867 if (D
->isInvalidDecl() || D
->isUsed() || D
->hasAttr
<UnusedAttr
>())
1870 // Ignore all entities declared within templates, and out-of-line definitions
1871 // of members of class templates.
1872 if (D
->getDeclContext()->isDependentContext() ||
1873 D
->getLexicalDeclContext()->isDependentContext())
1876 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1877 if (FD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1879 // A non-out-of-line declaration of a member specialization was implicitly
1880 // instantiated; it's the out-of-line declaration that we're interested in.
1881 if (FD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1882 FD
->getMemberSpecializationInfo() && !FD
->isOutOfLine())
1885 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
1886 if (MD
->isVirtual() || IsDisallowedCopyOrAssign(MD
))
1889 // 'static inline' functions are defined in headers; don't warn.
1890 if (FD
->isInlined() && !isMainFileLoc(*this, FD
->getLocation()))
1894 if (FD
->doesThisDeclarationHaveABody() &&
1895 Context
.DeclMustBeEmitted(FD
))
1897 } else if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1898 // Constants and utility variables are defined in headers with internal
1899 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1901 if (!isMainFileLoc(*this, VD
->getLocation()))
1904 if (Context
.DeclMustBeEmitted(VD
))
1907 if (VD
->isStaticDataMember() &&
1908 VD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1910 if (VD
->isStaticDataMember() &&
1911 VD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1912 VD
->getMemberSpecializationInfo() && !VD
->isOutOfLine())
1915 if (VD
->isInline() && !isMainFileLoc(*this, VD
->getLocation()))
1921 // Only warn for unused decls internal to the translation unit.
1922 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1923 // for inline functions defined in the main source file, for instance.
1924 return mightHaveNonExternalLinkage(D
);
1927 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl
*D
) {
1931 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1932 const FunctionDecl
*First
= FD
->getFirstDecl();
1933 if (FD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1934 return; // First should already be in the vector.
1937 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1938 const VarDecl
*First
= VD
->getFirstDecl();
1939 if (VD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1940 return; // First should already be in the vector.
1943 if (ShouldWarnIfUnusedFileScopedDecl(D
))
1944 UnusedFileScopedDecls
.push_back(D
);
1947 static bool ShouldDiagnoseUnusedDecl(const NamedDecl
*D
) {
1948 if (D
->isInvalidDecl())
1951 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
)) {
1952 // For a decomposition declaration, warn if none of the bindings are
1953 // referenced, instead of if the variable itself is referenced (which
1954 // it is, by the bindings' expressions).
1955 for (auto *BD
: DD
->bindings())
1956 if (BD
->isReferenced())
1958 } else if (!D
->getDeclName()) {
1960 } else if (D
->isReferenced() || D
->isUsed()) {
1964 if (D
->hasAttr
<UnusedAttr
>() || D
->hasAttr
<ObjCPreciseLifetimeAttr
>())
1967 if (isa
<LabelDecl
>(D
))
1970 // Except for labels, we only care about unused decls that are local to
1972 bool WithinFunction
= D
->getDeclContext()->isFunctionOrMethod();
1973 if (const auto *R
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext()))
1974 // For dependent types, the diagnostic is deferred.
1976 WithinFunction
|| (R
->isLocalClass() && !R
->isDependentType());
1977 if (!WithinFunction
)
1980 if (isa
<TypedefNameDecl
>(D
))
1983 // White-list anything that isn't a local variable.
1984 if (!isa
<VarDecl
>(D
) || isa
<ParmVarDecl
>(D
) || isa
<ImplicitParamDecl
>(D
))
1987 // Types of valid local variables should be complete, so this should succeed.
1988 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1990 const Expr
*Init
= VD
->getInit();
1991 if (const auto *Cleanups
= dyn_cast_or_null
<ExprWithCleanups
>(Init
))
1992 Init
= Cleanups
->getSubExpr();
1994 const auto *Ty
= VD
->getType().getTypePtr();
1996 // Only look at the outermost level of typedef.
1997 if (const TypedefType
*TT
= Ty
->getAs
<TypedefType
>()) {
1998 // Allow anything marked with __attribute__((unused)).
1999 if (TT
->getDecl()->hasAttr
<UnusedAttr
>())
2003 // Warn for reference variables whose initializtion performs lifetime
2005 if (const auto *MTE
= dyn_cast_or_null
<MaterializeTemporaryExpr
>(Init
)) {
2006 if (MTE
->getExtendingDecl()) {
2007 Ty
= VD
->getType().getNonReferenceType().getTypePtr();
2008 Init
= MTE
->getSubExpr()->IgnoreImplicitAsWritten();
2012 // If we failed to complete the type for some reason, or if the type is
2013 // dependent, don't diagnose the variable.
2014 if (Ty
->isIncompleteType() || Ty
->isDependentType())
2017 // Look at the element type to ensure that the warning behaviour is
2018 // consistent for both scalars and arrays.
2019 Ty
= Ty
->getBaseElementTypeUnsafe();
2021 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2022 const TagDecl
*Tag
= TT
->getDecl();
2023 if (Tag
->hasAttr
<UnusedAttr
>())
2026 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2027 if (!RD
->hasTrivialDestructor() && !RD
->hasAttr
<WarnUnusedAttr
>())
2031 const CXXConstructExpr
*Construct
=
2032 dyn_cast
<CXXConstructExpr
>(Init
);
2033 if (Construct
&& !Construct
->isElidable()) {
2034 CXXConstructorDecl
*CD
= Construct
->getConstructor();
2035 if (!CD
->isTrivial() && !RD
->hasAttr
<WarnUnusedAttr
>() &&
2036 (VD
->getInit()->isValueDependent() || !VD
->evaluateValue()))
2040 // Suppress the warning if we don't know how this is constructed, and
2041 // it could possibly be non-trivial constructor.
2042 if (Init
->isTypeDependent()) {
2043 for (const CXXConstructorDecl
*Ctor
: RD
->ctors())
2044 if (!Ctor
->isTrivial())
2048 // Suppress the warning if the constructor is unresolved because
2049 // its arguments are dependent.
2050 if (isa
<CXXUnresolvedConstructExpr
>(Init
))
2056 // TODO: __attribute__((unused)) templates?
2062 static void GenerateFixForUnusedDecl(const NamedDecl
*D
, ASTContext
&Ctx
,
2064 if (isa
<LabelDecl
>(D
)) {
2065 SourceLocation AfterColon
= Lexer::findLocationAfterToken(
2066 D
->getEndLoc(), tok::colon
, Ctx
.getSourceManager(), Ctx
.getLangOpts(),
2068 if (AfterColon
.isInvalid())
2070 Hint
= FixItHint::CreateRemoval(
2071 CharSourceRange::getCharRange(D
->getBeginLoc(), AfterColon
));
2075 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl
*D
) {
2076 if (D
->getTypeForDecl()->isDependentType())
2079 for (auto *TmpD
: D
->decls()) {
2080 if (const auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
2081 DiagnoseUnusedDecl(T
);
2082 else if(const auto *R
= dyn_cast
<RecordDecl
>(TmpD
))
2083 DiagnoseUnusedNestedTypedefs(R
);
2087 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2088 /// unless they are marked attr(unused).
2089 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
) {
2090 if (!ShouldDiagnoseUnusedDecl(D
))
2093 if (auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
2094 // typedefs can be referenced later on, so the diagnostics are emitted
2095 // at end-of-translation-unit.
2096 UnusedLocalTypedefNameCandidates
.insert(TD
);
2101 GenerateFixForUnusedDecl(D
, Context
, Hint
);
2104 if (isa
<VarDecl
>(D
) && cast
<VarDecl
>(D
)->isExceptionVariable())
2105 DiagID
= diag::warn_unused_exception_param
;
2106 else if (isa
<LabelDecl
>(D
))
2107 DiagID
= diag::warn_unused_label
;
2109 DiagID
= diag::warn_unused_variable
;
2111 Diag(D
->getLocation(), DiagID
) << D
<< Hint
;
2114 void Sema::DiagnoseUnusedButSetDecl(const VarDecl
*VD
) {
2115 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2116 // it's not really unused.
2117 if (!VD
->isReferenced() || !VD
->getDeclName() || VD
->hasAttr
<UnusedAttr
>() ||
2118 VD
->hasAttr
<CleanupAttr
>())
2121 const auto *Ty
= VD
->getType().getTypePtr()->getBaseElementTypeUnsafe();
2123 if (Ty
->isReferenceType() || Ty
->isDependentType())
2126 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2127 const TagDecl
*Tag
= TT
->getDecl();
2128 if (Tag
->hasAttr
<UnusedAttr
>())
2130 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2131 // mimic gcc's behavior.
2132 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2133 if (!RD
->hasAttr
<WarnUnusedAttr
>())
2138 // Don't warn about __block Objective-C pointer variables, as they might
2139 // be assigned in the block but not used elsewhere for the purpose of lifetime
2141 if (VD
->hasAttr
<BlocksAttr
>() && Ty
->isObjCObjectPointerType())
2144 // Don't warn about Objective-C pointer variables with precise lifetime
2145 // semantics; they can be used to ensure ARC releases the object at a known
2146 // time, which may mean assignment but no other references.
2147 if (VD
->hasAttr
<ObjCPreciseLifetimeAttr
>() && Ty
->isObjCObjectPointerType())
2150 auto iter
= RefsMinusAssignments
.find(VD
);
2151 if (iter
== RefsMinusAssignments
.end())
2154 assert(iter
->getSecond() >= 0 &&
2155 "Found a negative number of references to a VarDecl");
2156 if (iter
->getSecond() != 0)
2158 unsigned DiagID
= isa
<ParmVarDecl
>(VD
) ? diag::warn_unused_but_set_parameter
2159 : diag::warn_unused_but_set_variable
;
2160 Diag(VD
->getLocation(), DiagID
) << VD
;
2163 static void CheckPoppedLabel(LabelDecl
*L
, Sema
&S
) {
2164 // Verify that we have no forward references left. If so, there was a goto
2165 // or address of a label taken, but no definition of it. Label fwd
2166 // definitions are indicated with a null substmt which is also not a resolved
2167 // MS inline assembly label name.
2168 bool Diagnose
= false;
2169 if (L
->isMSAsmLabel())
2170 Diagnose
= !L
->isResolvedMSAsmLabel();
2172 Diagnose
= L
->getStmt() == nullptr;
2174 S
.Diag(L
->getLocation(), diag::err_undeclared_label_use
) << L
;
2177 void Sema::ActOnPopScope(SourceLocation Loc
, Scope
*S
) {
2180 if (S
->decl_empty()) return;
2181 assert((S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
)) &&
2182 "Scope shouldn't contain decls!");
2184 for (auto *TmpD
: S
->decls()) {
2185 assert(TmpD
&& "This decl didn't get pushed??");
2187 assert(isa
<NamedDecl
>(TmpD
) && "Decl isn't NamedDecl?");
2188 NamedDecl
*D
= cast
<NamedDecl
>(TmpD
);
2190 // Diagnose unused variables in this scope.
2191 if (!S
->hasUnrecoverableErrorOccurred()) {
2192 DiagnoseUnusedDecl(D
);
2193 if (const auto *RD
= dyn_cast
<RecordDecl
>(D
))
2194 DiagnoseUnusedNestedTypedefs(RD
);
2195 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2196 DiagnoseUnusedButSetDecl(VD
);
2197 RefsMinusAssignments
.erase(VD
);
2201 if (!D
->getDeclName()) continue;
2203 // If this was a forward reference to a label, verify it was defined.
2204 if (LabelDecl
*LD
= dyn_cast
<LabelDecl
>(D
))
2205 CheckPoppedLabel(LD
, *this);
2207 // Remove this name from our lexical scope, and warn on it if we haven't
2209 IdResolver
.RemoveDecl(D
);
2210 auto ShadowI
= ShadowingDecls
.find(D
);
2211 if (ShadowI
!= ShadowingDecls
.end()) {
2212 if (const auto *FD
= dyn_cast
<FieldDecl
>(ShadowI
->second
)) {
2213 Diag(D
->getLocation(), diag::warn_ctor_parm_shadows_field
)
2214 << D
<< FD
<< FD
->getParent();
2215 Diag(FD
->getLocation(), diag::note_previous_declaration
);
2217 ShadowingDecls
.erase(ShadowI
);
2222 /// Look for an Objective-C class in the translation unit.
2224 /// \param Id The name of the Objective-C class we're looking for. If
2225 /// typo-correction fixes this name, the Id will be updated
2226 /// to the fixed name.
2228 /// \param IdLoc The location of the name in the translation unit.
2230 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2231 /// if there is no class with the given name.
2233 /// \returns The declaration of the named Objective-C class, or NULL if the
2234 /// class could not be found.
2235 ObjCInterfaceDecl
*Sema::getObjCInterfaceDecl(IdentifierInfo
*&Id
,
2236 SourceLocation IdLoc
,
2237 bool DoTypoCorrection
) {
2238 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2239 // creation from this context.
2240 NamedDecl
*IDecl
= LookupSingleName(TUScope
, Id
, IdLoc
, LookupOrdinaryName
);
2242 if (!IDecl
&& DoTypoCorrection
) {
2243 // Perform typo correction at the given location, but only if we
2244 // find an Objective-C class name.
2245 DeclFilterCCC
<ObjCInterfaceDecl
> CCC
{};
2246 if (TypoCorrection C
=
2247 CorrectTypo(DeclarationNameInfo(Id
, IdLoc
), LookupOrdinaryName
,
2248 TUScope
, nullptr, CCC
, CTK_ErrorRecovery
)) {
2249 diagnoseTypo(C
, PDiag(diag::err_undef_interface_suggest
) << Id
);
2250 IDecl
= C
.getCorrectionDeclAs
<ObjCInterfaceDecl
>();
2251 Id
= IDecl
->getIdentifier();
2254 ObjCInterfaceDecl
*Def
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IDecl
);
2255 // This routine must always return a class definition, if any.
2256 if (Def
&& Def
->getDefinition())
2257 Def
= Def
->getDefinition();
2261 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2262 /// from S, where a non-field would be declared. This routine copes
2263 /// with the difference between C and C++ scoping rules in structs and
2264 /// unions. For example, the following code is well-formed in C but
2265 /// ill-formed in C++:
2271 /// void test_S6() {
2276 /// For the declaration of BAR, this routine will return a different
2277 /// scope. The scope S will be the scope of the unnamed enumeration
2278 /// within S6. In C++, this routine will return the scope associated
2279 /// with S6, because the enumeration's scope is a transparent
2280 /// context but structures can contain non-field names. In C, this
2281 /// routine will return the translation unit scope, since the
2282 /// enumeration's scope is a transparent context and structures cannot
2283 /// contain non-field names.
2284 Scope
*Sema::getNonFieldDeclScope(Scope
*S
) {
2285 while (((S
->getFlags() & Scope::DeclScope
) == 0) ||
2286 (S
->getEntity() && S
->getEntity()->isTransparentContext()) ||
2287 (S
->isClassScope() && !getLangOpts().CPlusPlus
))
2292 static StringRef
getHeaderName(Builtin::Context
&BuiltinInfo
, unsigned ID
,
2293 ASTContext::GetBuiltinTypeError Error
) {
2295 case ASTContext::GE_None
:
2297 case ASTContext::GE_Missing_type
:
2298 return BuiltinInfo
.getHeaderName(ID
);
2299 case ASTContext::GE_Missing_stdio
:
2301 case ASTContext::GE_Missing_setjmp
:
2303 case ASTContext::GE_Missing_ucontext
:
2304 return "ucontext.h";
2306 llvm_unreachable("unhandled error kind");
2309 FunctionDecl
*Sema::CreateBuiltin(IdentifierInfo
*II
, QualType Type
,
2310 unsigned ID
, SourceLocation Loc
) {
2311 DeclContext
*Parent
= Context
.getTranslationUnitDecl();
2313 if (getLangOpts().CPlusPlus
) {
2314 LinkageSpecDecl
*CLinkageDecl
= LinkageSpecDecl::Create(
2315 Context
, Parent
, Loc
, Loc
, LinkageSpecDecl::lang_c
, false);
2316 CLinkageDecl
->setImplicit();
2317 Parent
->addDecl(CLinkageDecl
);
2318 Parent
= CLinkageDecl
;
2321 FunctionDecl
*New
= FunctionDecl::Create(Context
, Parent
, Loc
, Loc
, II
, Type
,
2322 /*TInfo=*/nullptr, SC_Extern
,
2323 getCurFPFeatures().isFPConstrained(),
2324 false, Type
->isFunctionProtoType());
2326 New
->addAttr(BuiltinAttr::CreateImplicit(Context
, ID
));
2328 // Create Decl objects for each parameter, adding them to the
2330 if (const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(Type
)) {
2331 SmallVector
<ParmVarDecl
*, 16> Params
;
2332 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
2333 ParmVarDecl
*parm
= ParmVarDecl::Create(
2334 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
2335 FT
->getParamType(i
), /*TInfo=*/nullptr, SC_None
, nullptr);
2336 parm
->setScopeInfo(0, i
);
2337 Params
.push_back(parm
);
2339 New
->setParams(Params
);
2342 AddKnownFunctionAttributes(New
);
2346 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2347 /// file scope. lazily create a decl for it. ForRedeclaration is true
2348 /// if we're creating this built-in in anticipation of redeclaring the
2350 NamedDecl
*Sema::LazilyCreateBuiltin(IdentifierInfo
*II
, unsigned ID
,
2351 Scope
*S
, bool ForRedeclaration
,
2352 SourceLocation Loc
) {
2353 LookupNecessaryTypesForBuiltin(S
, ID
);
2355 ASTContext::GetBuiltinTypeError Error
;
2356 QualType R
= Context
.GetBuiltinType(ID
, Error
);
2358 if (!ForRedeclaration
)
2361 // If we have a builtin without an associated type we should not emit a
2362 // warning when we were not able to find a type for it.
2363 if (Error
== ASTContext::GE_Missing_type
||
2364 Context
.BuiltinInfo
.allowTypeMismatch(ID
))
2367 // If we could not find a type for setjmp it is because the jmp_buf type was
2368 // not defined prior to the setjmp declaration.
2369 if (Error
== ASTContext::GE_Missing_setjmp
) {
2370 Diag(Loc
, diag::warn_implicit_decl_no_jmp_buf
)
2371 << Context
.BuiltinInfo
.getName(ID
);
2375 // Generally, we emit a warning that the declaration requires the
2376 // appropriate header.
2377 Diag(Loc
, diag::warn_implicit_decl_requires_sysheader
)
2378 << getHeaderName(Context
.BuiltinInfo
, ID
, Error
)
2379 << Context
.BuiltinInfo
.getName(ID
);
2383 if (!ForRedeclaration
&&
2384 (Context
.BuiltinInfo
.isPredefinedLibFunction(ID
) ||
2385 Context
.BuiltinInfo
.isHeaderDependentFunction(ID
))) {
2386 Diag(Loc
, LangOpts
.C99
? diag::ext_implicit_lib_function_decl_c99
2387 : diag::ext_implicit_lib_function_decl
)
2388 << Context
.BuiltinInfo
.getName(ID
) << R
;
2389 if (const char *Header
= Context
.BuiltinInfo
.getHeaderName(ID
))
2390 Diag(Loc
, diag::note_include_header_or_declare
)
2391 << Header
<< Context
.BuiltinInfo
.getName(ID
);
2397 FunctionDecl
*New
= CreateBuiltin(II
, R
, ID
, Loc
);
2398 RegisterLocallyScopedExternCDecl(New
, S
);
2400 // TUScope is the translation-unit scope to insert this function into.
2401 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2402 // relate Scopes to DeclContexts, and probably eliminate CurContext
2403 // entirely, but we're not there yet.
2404 DeclContext
*SavedContext
= CurContext
;
2405 CurContext
= New
->getDeclContext();
2406 PushOnScopeChains(New
, TUScope
);
2407 CurContext
= SavedContext
;
2411 /// Typedef declarations don't have linkage, but they still denote the same
2412 /// entity if their types are the same.
2413 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2415 static void filterNonConflictingPreviousTypedefDecls(Sema
&S
,
2416 TypedefNameDecl
*Decl
,
2417 LookupResult
&Previous
) {
2418 // This is only interesting when modules are enabled.
2419 if (!S
.getLangOpts().Modules
&& !S
.getLangOpts().ModulesLocalVisibility
)
2422 // Empty sets are uninteresting.
2423 if (Previous
.empty())
2426 LookupResult::Filter Filter
= Previous
.makeFilter();
2427 while (Filter
.hasNext()) {
2428 NamedDecl
*Old
= Filter
.next();
2430 // Non-hidden declarations are never ignored.
2431 if (S
.isVisible(Old
))
2434 // Declarations of the same entity are not ignored, even if they have
2435 // different linkages.
2436 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2437 if (S
.Context
.hasSameType(OldTD
->getUnderlyingType(),
2438 Decl
->getUnderlyingType()))
2441 // If both declarations give a tag declaration a typedef name for linkage
2442 // purposes, then they declare the same entity.
2443 if (OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2444 Decl
->getAnonDeclWithTypedefName())
2454 bool Sema::isIncompatibleTypedef(TypeDecl
*Old
, TypedefNameDecl
*New
) {
2456 if (TypedefNameDecl
*OldTypedef
= dyn_cast
<TypedefNameDecl
>(Old
))
2457 OldType
= OldTypedef
->getUnderlyingType();
2459 OldType
= Context
.getTypeDeclType(Old
);
2460 QualType NewType
= New
->getUnderlyingType();
2462 if (NewType
->isVariablyModifiedType()) {
2463 // Must not redefine a typedef with a variably-modified type.
2464 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2465 Diag(New
->getLocation(), diag::err_redefinition_variably_modified_typedef
)
2467 if (Old
->getLocation().isValid())
2468 notePreviousDefinition(Old
, New
->getLocation());
2469 New
->setInvalidDecl();
2473 if (OldType
!= NewType
&&
2474 !OldType
->isDependentType() &&
2475 !NewType
->isDependentType() &&
2476 !Context
.hasSameType(OldType
, NewType
)) {
2477 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2478 Diag(New
->getLocation(), diag::err_redefinition_different_typedef
)
2479 << Kind
<< NewType
<< OldType
;
2480 if (Old
->getLocation().isValid())
2481 notePreviousDefinition(Old
, New
->getLocation());
2482 New
->setInvalidDecl();
2488 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2489 /// same name and scope as a previous declaration 'Old'. Figure out
2490 /// how to resolve this situation, merging decls or emitting
2491 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2493 void Sema::MergeTypedefNameDecl(Scope
*S
, TypedefNameDecl
*New
,
2494 LookupResult
&OldDecls
) {
2495 // If the new decl is known invalid already, don't bother doing any
2497 if (New
->isInvalidDecl()) return;
2499 // Allow multiple definitions for ObjC built-in typedefs.
2500 // FIXME: Verify the underlying types are equivalent!
2501 if (getLangOpts().ObjC
) {
2502 const IdentifierInfo
*TypeID
= New
->getIdentifier();
2503 switch (TypeID
->getLength()) {
2507 if (!TypeID
->isStr("id"))
2509 QualType T
= New
->getUnderlyingType();
2510 if (!T
->isPointerType())
2512 if (!T
->isVoidPointerType()) {
2513 QualType PT
= T
->castAs
<PointerType
>()->getPointeeType();
2514 if (!PT
->isStructureType())
2517 Context
.setObjCIdRedefinitionType(T
);
2518 // Install the built-in type for 'id', ignoring the current definition.
2519 New
->setTypeForDecl(Context
.getObjCIdType().getTypePtr());
2523 if (!TypeID
->isStr("Class"))
2525 Context
.setObjCClassRedefinitionType(New
->getUnderlyingType());
2526 // Install the built-in type for 'Class', ignoring the current definition.
2527 New
->setTypeForDecl(Context
.getObjCClassType().getTypePtr());
2530 if (!TypeID
->isStr("SEL"))
2532 Context
.setObjCSelRedefinitionType(New
->getUnderlyingType());
2533 // Install the built-in type for 'SEL', ignoring the current definition.
2534 New
->setTypeForDecl(Context
.getObjCSelType().getTypePtr());
2537 // Fall through - the typedef name was not a builtin type.
2540 // Verify the old decl was also a type.
2541 TypeDecl
*Old
= OldDecls
.getAsSingle
<TypeDecl
>();
2543 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
2544 << New
->getDeclName();
2546 NamedDecl
*OldD
= OldDecls
.getRepresentativeDecl();
2547 if (OldD
->getLocation().isValid())
2548 notePreviousDefinition(OldD
, New
->getLocation());
2550 return New
->setInvalidDecl();
2553 // If the old declaration is invalid, just give up here.
2554 if (Old
->isInvalidDecl())
2555 return New
->setInvalidDecl();
2557 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2558 auto *OldTag
= OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2559 auto *NewTag
= New
->getAnonDeclWithTypedefName();
2560 NamedDecl
*Hidden
= nullptr;
2561 if (OldTag
&& NewTag
&&
2562 OldTag
->getCanonicalDecl() != NewTag
->getCanonicalDecl() &&
2563 !hasVisibleDefinition(OldTag
, &Hidden
)) {
2564 // There is a definition of this tag, but it is not visible. Use it
2565 // instead of our tag.
2566 New
->setTypeForDecl(OldTD
->getTypeForDecl());
2567 if (OldTD
->isModed())
2568 New
->setModedTypeSourceInfo(OldTD
->getTypeSourceInfo(),
2569 OldTD
->getUnderlyingType());
2571 New
->setTypeSourceInfo(OldTD
->getTypeSourceInfo());
2573 // Make the old tag definition visible.
2574 makeMergedDefinitionVisible(Hidden
);
2576 // If this was an unscoped enumeration, yank all of its enumerators
2577 // out of the scope.
2578 if (isa
<EnumDecl
>(NewTag
)) {
2579 Scope
*EnumScope
= getNonFieldDeclScope(S
);
2580 for (auto *D
: NewTag
->decls()) {
2581 auto *ED
= cast
<EnumConstantDecl
>(D
);
2582 assert(EnumScope
->isDeclScope(ED
));
2583 EnumScope
->RemoveDecl(ED
);
2584 IdResolver
.RemoveDecl(ED
);
2585 ED
->getLexicalDeclContext()->removeDecl(ED
);
2591 // If the typedef types are not identical, reject them in all languages and
2592 // with any extensions enabled.
2593 if (isIncompatibleTypedef(Old
, New
))
2596 // The types match. Link up the redeclaration chain and merge attributes if
2597 // the old declaration was a typedef.
2598 if (TypedefNameDecl
*Typedef
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2599 New
->setPreviousDecl(Typedef
);
2600 mergeDeclAttributes(New
, Old
);
2603 if (getLangOpts().MicrosoftExt
)
2606 if (getLangOpts().CPlusPlus
) {
2607 // C++ [dcl.typedef]p2:
2608 // In a given non-class scope, a typedef specifier can be used to
2609 // redefine the name of any type declared in that scope to refer
2610 // to the type to which it already refers.
2611 if (!isa
<CXXRecordDecl
>(CurContext
))
2614 // C++0x [dcl.typedef]p4:
2615 // In a given class scope, a typedef specifier can be used to redefine
2616 // any class-name declared in that scope that is not also a typedef-name
2617 // to refer to the type to which it already refers.
2619 // This wording came in via DR424, which was a correction to the
2620 // wording in DR56, which accidentally banned code like:
2623 // typedef struct A { } A;
2626 // in the C++03 standard. We implement the C++0x semantics, which
2627 // allow the above but disallow
2634 // since that was the intent of DR56.
2635 if (!isa
<TypedefNameDecl
>(Old
))
2638 Diag(New
->getLocation(), diag::err_redefinition
)
2639 << New
->getDeclName();
2640 notePreviousDefinition(Old
, New
->getLocation());
2641 return New
->setInvalidDecl();
2644 // Modules always permit redefinition of typedefs, as does C11.
2645 if (getLangOpts().Modules
|| getLangOpts().C11
)
2648 // If we have a redefinition of a typedef in C, emit a warning. This warning
2649 // is normally mapped to an error, but can be controlled with
2650 // -Wtypedef-redefinition. If either the original or the redefinition is
2651 // in a system header, don't emit this for compatibility with GCC.
2652 if (getDiagnostics().getSuppressSystemWarnings() &&
2653 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2654 (Old
->isImplicit() ||
2655 Context
.getSourceManager().isInSystemHeader(Old
->getLocation()) ||
2656 Context
.getSourceManager().isInSystemHeader(New
->getLocation())))
2659 Diag(New
->getLocation(), diag::ext_redefinition_of_typedef
)
2660 << New
->getDeclName();
2661 notePreviousDefinition(Old
, New
->getLocation());
2664 /// DeclhasAttr - returns true if decl Declaration already has the target
2666 static bool DeclHasAttr(const Decl
*D
, const Attr
*A
) {
2667 const OwnershipAttr
*OA
= dyn_cast
<OwnershipAttr
>(A
);
2668 const AnnotateAttr
*Ann
= dyn_cast
<AnnotateAttr
>(A
);
2669 for (const auto *i
: D
->attrs())
2670 if (i
->getKind() == A
->getKind()) {
2672 if (Ann
->getAnnotation() == cast
<AnnotateAttr
>(i
)->getAnnotation())
2676 // FIXME: Don't hardcode this check
2677 if (OA
&& isa
<OwnershipAttr
>(i
))
2678 return OA
->getOwnKind() == cast
<OwnershipAttr
>(i
)->getOwnKind();
2685 static bool isAttributeTargetADefinition(Decl
*D
) {
2686 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
2687 return VD
->isThisDeclarationADefinition();
2688 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
2689 return TD
->isCompleteDefinition() || TD
->isBeingDefined();
2693 /// Merge alignment attributes from \p Old to \p New, taking into account the
2694 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2696 /// \return \c true if any attributes were added to \p New.
2697 static bool mergeAlignedAttrs(Sema
&S
, NamedDecl
*New
, Decl
*Old
) {
2698 // Look for alignas attributes on Old, and pick out whichever attribute
2699 // specifies the strictest alignment requirement.
2700 AlignedAttr
*OldAlignasAttr
= nullptr;
2701 AlignedAttr
*OldStrictestAlignAttr
= nullptr;
2702 unsigned OldAlign
= 0;
2703 for (auto *I
: Old
->specific_attrs
<AlignedAttr
>()) {
2704 // FIXME: We have no way of representing inherited dependent alignments
2706 // template<int A, int B> struct alignas(A) X;
2707 // template<int A, int B> struct alignas(B) X {};
2708 // For now, we just ignore any alignas attributes which are not on the
2709 // definition in such a case.
2710 if (I
->isAlignmentDependent())
2716 unsigned Align
= I
->getAlignment(S
.Context
);
2717 if (Align
> OldAlign
) {
2719 OldStrictestAlignAttr
= I
;
2723 // Look for alignas attributes on New.
2724 AlignedAttr
*NewAlignasAttr
= nullptr;
2725 unsigned NewAlign
= 0;
2726 for (auto *I
: New
->specific_attrs
<AlignedAttr
>()) {
2727 if (I
->isAlignmentDependent())
2733 unsigned Align
= I
->getAlignment(S
.Context
);
2734 if (Align
> NewAlign
)
2738 if (OldAlignasAttr
&& NewAlignasAttr
&& OldAlign
!= NewAlign
) {
2739 // Both declarations have 'alignas' attributes. We require them to match.
2740 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2741 // fall short. (If two declarations both have alignas, they must both match
2742 // every definition, and so must match each other if there is a definition.)
2744 // If either declaration only contains 'alignas(0)' specifiers, then it
2745 // specifies the natural alignment for the type.
2746 if (OldAlign
== 0 || NewAlign
== 0) {
2748 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(New
))
2751 Ty
= S
.Context
.getTagDeclType(cast
<TagDecl
>(New
));
2754 OldAlign
= S
.Context
.getTypeAlign(Ty
);
2756 NewAlign
= S
.Context
.getTypeAlign(Ty
);
2759 if (OldAlign
!= NewAlign
) {
2760 S
.Diag(NewAlignasAttr
->getLocation(), diag::err_alignas_mismatch
)
2761 << (unsigned)S
.Context
.toCharUnitsFromBits(OldAlign
).getQuantity()
2762 << (unsigned)S
.Context
.toCharUnitsFromBits(NewAlign
).getQuantity();
2763 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_previous_declaration
);
2767 if (OldAlignasAttr
&& !NewAlignasAttr
&& isAttributeTargetADefinition(New
)) {
2768 // C++11 [dcl.align]p6:
2769 // if any declaration of an entity has an alignment-specifier,
2770 // every defining declaration of that entity shall specify an
2771 // equivalent alignment.
2773 // If the definition of an object does not have an alignment
2774 // specifier, any other declaration of that object shall also
2775 // have no alignment specifier.
2776 S
.Diag(New
->getLocation(), diag::err_alignas_missing_on_definition
)
2778 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_alignas_on_declaration
)
2782 bool AnyAdded
= false;
2784 // Ensure we have an attribute representing the strictest alignment.
2785 if (OldAlign
> NewAlign
) {
2786 AlignedAttr
*Clone
= OldStrictestAlignAttr
->clone(S
.Context
);
2787 Clone
->setInherited(true);
2788 New
->addAttr(Clone
);
2792 // Ensure we have an alignas attribute if the old declaration had one.
2793 if (OldAlignasAttr
&& !NewAlignasAttr
&&
2794 !(AnyAdded
&& OldStrictestAlignAttr
->isAlignas())) {
2795 AlignedAttr
*Clone
= OldAlignasAttr
->clone(S
.Context
);
2796 Clone
->setInherited(true);
2797 New
->addAttr(Clone
);
2804 #define WANT_DECL_MERGE_LOGIC
2805 #include "clang/Sema/AttrParsedAttrImpl.inc"
2806 #undef WANT_DECL_MERGE_LOGIC
2808 static bool mergeDeclAttribute(Sema
&S
, NamedDecl
*D
,
2809 const InheritableAttr
*Attr
,
2810 Sema::AvailabilityMergeKind AMK
) {
2811 // Diagnose any mutual exclusions between the attribute that we want to add
2812 // and attributes that already exist on the declaration.
2813 if (!DiagnoseMutualExclusions(S
, D
, Attr
))
2816 // This function copies an attribute Attr from a previous declaration to the
2817 // new declaration D if the new declaration doesn't itself have that attribute
2818 // yet or if that attribute allows duplicates.
2819 // If you're adding a new attribute that requires logic different from
2820 // "use explicit attribute on decl if present, else use attribute from
2821 // previous decl", for example if the attribute needs to be consistent
2822 // between redeclarations, you need to call a custom merge function here.
2823 InheritableAttr
*NewAttr
= nullptr;
2824 if (const auto *AA
= dyn_cast
<AvailabilityAttr
>(Attr
))
2825 NewAttr
= S
.mergeAvailabilityAttr(
2826 D
, *AA
, AA
->getPlatform(), AA
->isImplicit(), AA
->getIntroduced(),
2827 AA
->getDeprecated(), AA
->getObsoleted(), AA
->getUnavailable(),
2828 AA
->getMessage(), AA
->getStrict(), AA
->getReplacement(), AMK
,
2830 else if (const auto *VA
= dyn_cast
<VisibilityAttr
>(Attr
))
2831 NewAttr
= S
.mergeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2832 else if (const auto *VA
= dyn_cast
<TypeVisibilityAttr
>(Attr
))
2833 NewAttr
= S
.mergeTypeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2834 else if (const auto *ImportA
= dyn_cast
<DLLImportAttr
>(Attr
))
2835 NewAttr
= S
.mergeDLLImportAttr(D
, *ImportA
);
2836 else if (const auto *ExportA
= dyn_cast
<DLLExportAttr
>(Attr
))
2837 NewAttr
= S
.mergeDLLExportAttr(D
, *ExportA
);
2838 else if (const auto *EA
= dyn_cast
<ErrorAttr
>(Attr
))
2839 NewAttr
= S
.mergeErrorAttr(D
, *EA
, EA
->getUserDiagnostic());
2840 else if (const auto *FA
= dyn_cast
<FormatAttr
>(Attr
))
2841 NewAttr
= S
.mergeFormatAttr(D
, *FA
, FA
->getType(), FA
->getFormatIdx(),
2843 else if (const auto *SA
= dyn_cast
<SectionAttr
>(Attr
))
2844 NewAttr
= S
.mergeSectionAttr(D
, *SA
, SA
->getName());
2845 else if (const auto *CSA
= dyn_cast
<CodeSegAttr
>(Attr
))
2846 NewAttr
= S
.mergeCodeSegAttr(D
, *CSA
, CSA
->getName());
2847 else if (const auto *IA
= dyn_cast
<MSInheritanceAttr
>(Attr
))
2848 NewAttr
= S
.mergeMSInheritanceAttr(D
, *IA
, IA
->getBestCase(),
2849 IA
->getInheritanceModel());
2850 else if (const auto *AA
= dyn_cast
<AlwaysInlineAttr
>(Attr
))
2851 NewAttr
= S
.mergeAlwaysInlineAttr(D
, *AA
,
2852 &S
.Context
.Idents
.get(AA
->getSpelling()));
2853 else if (S
.getLangOpts().CUDA
&& isa
<FunctionDecl
>(D
) &&
2854 (isa
<CUDAHostAttr
>(Attr
) || isa
<CUDADeviceAttr
>(Attr
) ||
2855 isa
<CUDAGlobalAttr
>(Attr
))) {
2856 // CUDA target attributes are part of function signature for
2857 // overloading purposes and must not be merged.
2859 } else if (const auto *MA
= dyn_cast
<MinSizeAttr
>(Attr
))
2860 NewAttr
= S
.mergeMinSizeAttr(D
, *MA
);
2861 else if (const auto *SNA
= dyn_cast
<SwiftNameAttr
>(Attr
))
2862 NewAttr
= S
.mergeSwiftNameAttr(D
, *SNA
, SNA
->getName());
2863 else if (const auto *OA
= dyn_cast
<OptimizeNoneAttr
>(Attr
))
2864 NewAttr
= S
.mergeOptimizeNoneAttr(D
, *OA
);
2865 else if (const auto *InternalLinkageA
= dyn_cast
<InternalLinkageAttr
>(Attr
))
2866 NewAttr
= S
.mergeInternalLinkageAttr(D
, *InternalLinkageA
);
2867 else if (isa
<AlignedAttr
>(Attr
))
2868 // AlignedAttrs are handled separately, because we need to handle all
2869 // such attributes on a declaration at the same time.
2871 else if ((isa
<DeprecatedAttr
>(Attr
) || isa
<UnavailableAttr
>(Attr
)) &&
2872 (AMK
== Sema::AMK_Override
||
2873 AMK
== Sema::AMK_ProtocolImplementation
||
2874 AMK
== Sema::AMK_OptionalProtocolImplementation
))
2876 else if (const auto *UA
= dyn_cast
<UuidAttr
>(Attr
))
2877 NewAttr
= S
.mergeUuidAttr(D
, *UA
, UA
->getGuid(), UA
->getGuidDecl());
2878 else if (const auto *IMA
= dyn_cast
<WebAssemblyImportModuleAttr
>(Attr
))
2879 NewAttr
= S
.mergeImportModuleAttr(D
, *IMA
);
2880 else if (const auto *INA
= dyn_cast
<WebAssemblyImportNameAttr
>(Attr
))
2881 NewAttr
= S
.mergeImportNameAttr(D
, *INA
);
2882 else if (const auto *TCBA
= dyn_cast
<EnforceTCBAttr
>(Attr
))
2883 NewAttr
= S
.mergeEnforceTCBAttr(D
, *TCBA
);
2884 else if (const auto *TCBLA
= dyn_cast
<EnforceTCBLeafAttr
>(Attr
))
2885 NewAttr
= S
.mergeEnforceTCBLeafAttr(D
, *TCBLA
);
2886 else if (const auto *BTFA
= dyn_cast
<BTFDeclTagAttr
>(Attr
))
2887 NewAttr
= S
.mergeBTFDeclTagAttr(D
, *BTFA
);
2888 else if (const auto *NT
= dyn_cast
<HLSLNumThreadsAttr
>(Attr
))
2890 S
.mergeHLSLNumThreadsAttr(D
, *NT
, NT
->getX(), NT
->getY(), NT
->getZ());
2891 else if (const auto *SA
= dyn_cast
<HLSLShaderAttr
>(Attr
))
2892 NewAttr
= S
.mergeHLSLShaderAttr(D
, *SA
, SA
->getType());
2893 else if (Attr
->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D
, Attr
))
2894 NewAttr
= cast
<InheritableAttr
>(Attr
->clone(S
.Context
));
2897 NewAttr
->setInherited(true);
2898 D
->addAttr(NewAttr
);
2899 if (isa
<MSInheritanceAttr
>(NewAttr
))
2900 S
.Consumer
.AssignInheritanceModel(cast
<CXXRecordDecl
>(D
));
2907 static const NamedDecl
*getDefinition(const Decl
*D
) {
2908 if (const TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
2909 return TD
->getDefinition();
2910 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2911 const VarDecl
*Def
= VD
->getDefinition();
2914 return VD
->getActingDefinition();
2916 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
2917 const FunctionDecl
*Def
= nullptr;
2918 if (FD
->isDefined(Def
, true))
2924 static bool hasAttribute(const Decl
*D
, attr::Kind Kind
) {
2925 for (const auto *Attribute
: D
->attrs())
2926 if (Attribute
->getKind() == Kind
)
2931 /// checkNewAttributesAfterDef - If we already have a definition, check that
2932 /// there are no new attributes in this declaration.
2933 static void checkNewAttributesAfterDef(Sema
&S
, Decl
*New
, const Decl
*Old
) {
2934 if (!New
->hasAttrs())
2937 const NamedDecl
*Def
= getDefinition(Old
);
2938 if (!Def
|| Def
== New
)
2941 AttrVec
&NewAttributes
= New
->getAttrs();
2942 for (unsigned I
= 0, E
= NewAttributes
.size(); I
!= E
;) {
2943 const Attr
*NewAttribute
= NewAttributes
[I
];
2945 if (isa
<AliasAttr
>(NewAttribute
) || isa
<IFuncAttr
>(NewAttribute
)) {
2946 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(New
)) {
2947 Sema::SkipBodyInfo SkipBody
;
2948 S
.CheckForFunctionRedefinition(FD
, cast
<FunctionDecl
>(Def
), &SkipBody
);
2950 // If we're skipping this definition, drop the "alias" attribute.
2951 if (SkipBody
.ShouldSkip
) {
2952 NewAttributes
.erase(NewAttributes
.begin() + I
);
2957 VarDecl
*VD
= cast
<VarDecl
>(New
);
2958 unsigned Diag
= cast
<VarDecl
>(Def
)->isThisDeclarationADefinition() ==
2959 VarDecl::TentativeDefinition
2960 ? diag::err_alias_after_tentative
2961 : diag::err_redefinition
;
2962 S
.Diag(VD
->getLocation(), Diag
) << VD
->getDeclName();
2963 if (Diag
== diag::err_redefinition
)
2964 S
.notePreviousDefinition(Def
, VD
->getLocation());
2966 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
2967 VD
->setInvalidDecl();
2973 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(Def
)) {
2974 // Tentative definitions are only interesting for the alias check above.
2975 if (VD
->isThisDeclarationADefinition() != VarDecl::Definition
) {
2981 if (hasAttribute(Def
, NewAttribute
->getKind())) {
2983 continue; // regular attr merging will take care of validating this.
2986 if (isa
<C11NoReturnAttr
>(NewAttribute
)) {
2987 // C's _Noreturn is allowed to be added to a function after it is defined.
2990 } else if (isa
<UuidAttr
>(NewAttribute
)) {
2991 // msvc will allow a subsequent definition to add an uuid to a class
2994 } else if (const AlignedAttr
*AA
= dyn_cast
<AlignedAttr
>(NewAttribute
)) {
2995 if (AA
->isAlignas()) {
2996 // C++11 [dcl.align]p6:
2997 // if any declaration of an entity has an alignment-specifier,
2998 // every defining declaration of that entity shall specify an
2999 // equivalent alignment.
3001 // If the definition of an object does not have an alignment
3002 // specifier, any other declaration of that object shall also
3003 // have no alignment specifier.
3004 S
.Diag(Def
->getLocation(), diag::err_alignas_missing_on_definition
)
3006 S
.Diag(NewAttribute
->getLocation(), diag::note_alignas_on_declaration
)
3008 NewAttributes
.erase(NewAttributes
.begin() + I
);
3012 } else if (isa
<LoaderUninitializedAttr
>(NewAttribute
)) {
3013 // If there is a C definition followed by a redeclaration with this
3014 // attribute then there are two different definitions. In C++, prefer the
3015 // standard diagnostics.
3016 if (!S
.getLangOpts().CPlusPlus
) {
3017 S
.Diag(NewAttribute
->getLocation(),
3018 diag::err_loader_uninitialized_redeclaration
);
3019 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3020 NewAttributes
.erase(NewAttributes
.begin() + I
);
3024 } else if (isa
<SelectAnyAttr
>(NewAttribute
) &&
3025 cast
<VarDecl
>(New
)->isInline() &&
3026 !cast
<VarDecl
>(New
)->isInlineSpecified()) {
3027 // Don't warn about applying selectany to implicitly inline variables.
3028 // Older compilers and language modes would require the use of selectany
3029 // to make such variables inline, and it would have no effect if we
3033 } else if (isa
<OMPDeclareVariantAttr
>(NewAttribute
)) {
3034 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3035 // declarations after definitions.
3040 S
.Diag(NewAttribute
->getLocation(),
3041 diag::warn_attribute_precede_definition
);
3042 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3043 NewAttributes
.erase(NewAttributes
.begin() + I
);
3048 static void diagnoseMissingConstinit(Sema
&S
, const VarDecl
*InitDecl
,
3049 const ConstInitAttr
*CIAttr
,
3050 bool AttrBeforeInit
) {
3051 SourceLocation InsertLoc
= InitDecl
->getInnerLocStart();
3053 // Figure out a good way to write this specifier on the old declaration.
3054 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3055 // enough of the attribute list spelling information to extract that without
3057 std::string SuitableSpelling
;
3058 if (S
.getLangOpts().CPlusPlus20
)
3059 SuitableSpelling
= std::string(
3060 S
.PP
.getLastMacroWithSpelling(InsertLoc
, {tok::kw_constinit
}));
3061 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3062 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3063 InsertLoc
, {tok::l_square
, tok::l_square
,
3064 S
.PP
.getIdentifierInfo("clang"), tok::coloncolon
,
3065 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3066 tok::r_square
, tok::r_square
}));
3067 if (SuitableSpelling
.empty())
3068 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3069 InsertLoc
, {tok::kw___attribute
, tok::l_paren
, tok::r_paren
,
3070 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3071 tok::r_paren
, tok::r_paren
}));
3072 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus20
)
3073 SuitableSpelling
= "constinit";
3074 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3075 SuitableSpelling
= "[[clang::require_constant_initialization]]";
3076 if (SuitableSpelling
.empty())
3077 SuitableSpelling
= "__attribute__((require_constant_initialization))";
3078 SuitableSpelling
+= " ";
3080 if (AttrBeforeInit
) {
3081 // extern constinit int a;
3082 // int a = 0; // error (missing 'constinit'), accepted as extension
3083 assert(CIAttr
->isConstinit() && "should not diagnose this for attribute");
3084 S
.Diag(InitDecl
->getLocation(), diag::ext_constinit_missing
)
3085 << InitDecl
<< FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3086 S
.Diag(CIAttr
->getLocation(), diag::note_constinit_specified_here
);
3089 // constinit extern int a; // error (missing 'constinit')
3090 S
.Diag(CIAttr
->getLocation(),
3091 CIAttr
->isConstinit() ? diag::err_constinit_added_too_late
3092 : diag::warn_require_const_init_added_too_late
)
3093 << FixItHint::CreateRemoval(SourceRange(CIAttr
->getLocation()));
3094 S
.Diag(InitDecl
->getLocation(), diag::note_constinit_missing_here
)
3095 << CIAttr
->isConstinit()
3096 << FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3100 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3101 void Sema::mergeDeclAttributes(NamedDecl
*New
, Decl
*Old
,
3102 AvailabilityMergeKind AMK
) {
3103 if (UsedAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<UsedAttr
>()) {
3104 UsedAttr
*NewAttr
= OldAttr
->clone(Context
);
3105 NewAttr
->setInherited(true);
3106 New
->addAttr(NewAttr
);
3108 if (RetainAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<RetainAttr
>()) {
3109 RetainAttr
*NewAttr
= OldAttr
->clone(Context
);
3110 NewAttr
->setInherited(true);
3111 New
->addAttr(NewAttr
);
3114 if (!Old
->hasAttrs() && !New
->hasAttrs())
3117 // [dcl.constinit]p1:
3118 // If the [constinit] specifier is applied to any declaration of a
3119 // variable, it shall be applied to the initializing declaration.
3120 const auto *OldConstInit
= Old
->getAttr
<ConstInitAttr
>();
3121 const auto *NewConstInit
= New
->getAttr
<ConstInitAttr
>();
3122 if (bool(OldConstInit
) != bool(NewConstInit
)) {
3123 const auto *OldVD
= cast
<VarDecl
>(Old
);
3124 auto *NewVD
= cast
<VarDecl
>(New
);
3126 // Find the initializing declaration. Note that we might not have linked
3127 // the new declaration into the redeclaration chain yet.
3128 const VarDecl
*InitDecl
= OldVD
->getInitializingDeclaration();
3130 (NewVD
->hasInit() || NewVD
->isThisDeclarationADefinition()))
3133 if (InitDecl
== NewVD
) {
3134 // This is the initializing declaration. If it would inherit 'constinit',
3135 // that's ill-formed. (Note that we do not apply this to the attribute
3137 if (OldConstInit
&& OldConstInit
->isConstinit())
3138 diagnoseMissingConstinit(*this, NewVD
, OldConstInit
,
3139 /*AttrBeforeInit=*/true);
3140 } else if (NewConstInit
) {
3141 // This is the first time we've been told that this declaration should
3142 // have a constant initializer. If we already saw the initializing
3143 // declaration, this is too late.
3144 if (InitDecl
&& InitDecl
!= NewVD
) {
3145 diagnoseMissingConstinit(*this, InitDecl
, NewConstInit
,
3146 /*AttrBeforeInit=*/false);
3147 NewVD
->dropAttr
<ConstInitAttr
>();
3152 // Attributes declared post-definition are currently ignored.
3153 checkNewAttributesAfterDef(*this, New
, Old
);
3155 if (AsmLabelAttr
*NewA
= New
->getAttr
<AsmLabelAttr
>()) {
3156 if (AsmLabelAttr
*OldA
= Old
->getAttr
<AsmLabelAttr
>()) {
3157 if (!OldA
->isEquivalent(NewA
)) {
3158 // This redeclaration changes __asm__ label.
3159 Diag(New
->getLocation(), diag::err_different_asm_label
);
3160 Diag(OldA
->getLocation(), diag::note_previous_declaration
);
3162 } else if (Old
->isUsed()) {
3163 // This redeclaration adds an __asm__ label to a declaration that has
3164 // already been ODR-used.
3165 Diag(New
->getLocation(), diag::err_late_asm_label_name
)
3166 << isa
<FunctionDecl
>(Old
) << New
->getAttr
<AsmLabelAttr
>()->getRange();
3170 // Re-declaration cannot add abi_tag's.
3171 if (const auto *NewAbiTagAttr
= New
->getAttr
<AbiTagAttr
>()) {
3172 if (const auto *OldAbiTagAttr
= Old
->getAttr
<AbiTagAttr
>()) {
3173 for (const auto &NewTag
: NewAbiTagAttr
->tags()) {
3174 if (!llvm::is_contained(OldAbiTagAttr
->tags(), NewTag
)) {
3175 Diag(NewAbiTagAttr
->getLocation(),
3176 diag::err_new_abi_tag_on_redeclaration
)
3178 Diag(OldAbiTagAttr
->getLocation(), diag::note_previous_declaration
);
3182 Diag(NewAbiTagAttr
->getLocation(), diag::err_abi_tag_on_redeclaration
);
3183 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3187 // This redeclaration adds a section attribute.
3188 if (New
->hasAttr
<SectionAttr
>() && !Old
->hasAttr
<SectionAttr
>()) {
3189 if (auto *VD
= dyn_cast
<VarDecl
>(New
)) {
3190 if (VD
->isThisDeclarationADefinition() == VarDecl::DeclarationOnly
) {
3191 Diag(New
->getLocation(), diag::warn_attribute_section_on_redeclaration
);
3192 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3197 // Redeclaration adds code-seg attribute.
3198 const auto *NewCSA
= New
->getAttr
<CodeSegAttr
>();
3199 if (NewCSA
&& !Old
->hasAttr
<CodeSegAttr
>() &&
3200 !NewCSA
->isImplicit() && isa
<CXXMethodDecl
>(New
)) {
3201 Diag(New
->getLocation(), diag::warn_mismatched_section
)
3203 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3206 if (!Old
->hasAttrs())
3209 bool foundAny
= New
->hasAttrs();
3211 // Ensure that any moving of objects within the allocated map is done before
3213 if (!foundAny
) New
->setAttrs(AttrVec());
3215 for (auto *I
: Old
->specific_attrs
<InheritableAttr
>()) {
3216 // Ignore deprecated/unavailable/availability attributes if requested.
3217 AvailabilityMergeKind LocalAMK
= AMK_None
;
3218 if (isa
<DeprecatedAttr
>(I
) ||
3219 isa
<UnavailableAttr
>(I
) ||
3220 isa
<AvailabilityAttr
>(I
)) {
3225 case AMK_Redeclaration
:
3227 case AMK_ProtocolImplementation
:
3228 case AMK_OptionalProtocolImplementation
:
3235 if (isa
<UsedAttr
>(I
) || isa
<RetainAttr
>(I
))
3238 if (mergeDeclAttribute(*this, New
, I
, LocalAMK
))
3242 if (mergeAlignedAttrs(*this, New
, Old
))
3245 if (!foundAny
) New
->dropAttrs();
3248 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3250 static void mergeParamDeclAttributes(ParmVarDecl
*newDecl
,
3251 const ParmVarDecl
*oldDecl
,
3253 // C++11 [dcl.attr.depend]p2:
3254 // The first declaration of a function shall specify the
3255 // carries_dependency attribute for its declarator-id if any declaration
3256 // of the function specifies the carries_dependency attribute.
3257 const CarriesDependencyAttr
*CDA
= newDecl
->getAttr
<CarriesDependencyAttr
>();
3258 if (CDA
&& !oldDecl
->hasAttr
<CarriesDependencyAttr
>()) {
3259 S
.Diag(CDA
->getLocation(),
3260 diag::err_carries_dependency_missing_on_first_decl
) << 1/*Param*/;
3261 // Find the first declaration of the parameter.
3262 // FIXME: Should we build redeclaration chains for function parameters?
3263 const FunctionDecl
*FirstFD
=
3264 cast
<FunctionDecl
>(oldDecl
->getDeclContext())->getFirstDecl();
3265 const ParmVarDecl
*FirstVD
=
3266 FirstFD
->getParamDecl(oldDecl
->getFunctionScopeIndex());
3267 S
.Diag(FirstVD
->getLocation(),
3268 diag::note_carries_dependency_missing_first_decl
) << 1/*Param*/;
3271 if (!oldDecl
->hasAttrs())
3274 bool foundAny
= newDecl
->hasAttrs();
3276 // Ensure that any moving of objects within the allocated map is
3277 // done before we process them.
3278 if (!foundAny
) newDecl
->setAttrs(AttrVec());
3280 for (const auto *I
: oldDecl
->specific_attrs
<InheritableParamAttr
>()) {
3281 if (!DeclHasAttr(newDecl
, I
)) {
3282 InheritableAttr
*newAttr
=
3283 cast
<InheritableParamAttr
>(I
->clone(S
.Context
));
3284 newAttr
->setInherited(true);
3285 newDecl
->addAttr(newAttr
);
3290 if (!foundAny
) newDecl
->dropAttrs();
3293 static bool EquivalentArrayTypes(QualType Old
, QualType New
,
3294 const ASTContext
&Ctx
) {
3296 auto NoSizeInfo
= [&Ctx
](QualType Ty
) {
3297 if (Ty
->isIncompleteArrayType() || Ty
->isPointerType())
3299 if (const auto *VAT
= Ctx
.getAsVariableArrayType(Ty
))
3300 return VAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
;
3304 // `type[]` is equivalent to `type *` and `type[*]`.
3305 if (NoSizeInfo(Old
) && NoSizeInfo(New
))
3308 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3309 if (Old
->isVariableArrayType() && New
->isVariableArrayType()) {
3310 const auto *OldVAT
= Ctx
.getAsVariableArrayType(Old
);
3311 const auto *NewVAT
= Ctx
.getAsVariableArrayType(New
);
3312 if ((OldVAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
) ^
3313 (NewVAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
))
3318 // Only compare size, ignore Size modifiers and CVR.
3319 if (Old
->isConstantArrayType() && New
->isConstantArrayType()) {
3320 return Ctx
.getAsConstantArrayType(Old
)->getSize() ==
3321 Ctx
.getAsConstantArrayType(New
)->getSize();
3324 // Don't try to compare dependent sized array
3325 if (Old
->isDependentSizedArrayType() && New
->isDependentSizedArrayType()) {
3332 static void mergeParamDeclTypes(ParmVarDecl
*NewParam
,
3333 const ParmVarDecl
*OldParam
,
3335 if (auto Oldnullability
= OldParam
->getType()->getNullability(S
.Context
)) {
3336 if (auto Newnullability
= NewParam
->getType()->getNullability(S
.Context
)) {
3337 if (*Oldnullability
!= *Newnullability
) {
3338 S
.Diag(NewParam
->getLocation(), diag::warn_mismatched_nullability_attr
)
3339 << DiagNullabilityKind(
3341 ((NewParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3343 << DiagNullabilityKind(
3345 ((OldParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3347 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration
);
3350 QualType NewT
= NewParam
->getType();
3351 NewT
= S
.Context
.getAttributedType(
3352 AttributedType::getNullabilityAttrKind(*Oldnullability
),
3354 NewParam
->setType(NewT
);
3357 const auto *OldParamDT
= dyn_cast
<DecayedType
>(OldParam
->getType());
3358 const auto *NewParamDT
= dyn_cast
<DecayedType
>(NewParam
->getType());
3359 if (OldParamDT
&& NewParamDT
&&
3360 OldParamDT
->getPointeeType() == NewParamDT
->getPointeeType()) {
3361 QualType OldParamOT
= OldParamDT
->getOriginalType();
3362 QualType NewParamOT
= NewParamDT
->getOriginalType();
3363 if (!EquivalentArrayTypes(OldParamOT
, NewParamOT
, S
.getASTContext())) {
3364 S
.Diag(NewParam
->getLocation(), diag::warn_inconsistent_array_form
)
3365 << NewParam
<< NewParamOT
;
3366 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration_as
)
3374 /// Used in MergeFunctionDecl to keep track of function parameters in
3376 struct GNUCompatibleParamWarning
{
3377 ParmVarDecl
*OldParm
;
3378 ParmVarDecl
*NewParm
;
3379 QualType PromotedType
;
3382 } // end anonymous namespace
3384 // Determine whether the previous declaration was a definition, implicit
3385 // declaration, or a declaration.
3386 template <typename T
>
3387 static std::pair
<diag::kind
, SourceLocation
>
3388 getNoteDiagForInvalidRedeclaration(const T
*Old
, const T
*New
) {
3389 diag::kind PrevDiag
;
3390 SourceLocation OldLocation
= Old
->getLocation();
3391 if (Old
->isThisDeclarationADefinition())
3392 PrevDiag
= diag::note_previous_definition
;
3393 else if (Old
->isImplicit()) {
3394 PrevDiag
= diag::note_previous_implicit_declaration
;
3395 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Old
)) {
3396 if (FD
->getBuiltinID())
3397 PrevDiag
= diag::note_previous_builtin_declaration
;
3399 if (OldLocation
.isInvalid())
3400 OldLocation
= New
->getLocation();
3402 PrevDiag
= diag::note_previous_declaration
;
3403 return std::make_pair(PrevDiag
, OldLocation
);
3406 /// canRedefineFunction - checks if a function can be redefined. Currently,
3407 /// only extern inline functions can be redefined, and even then only in
3409 static bool canRedefineFunction(const FunctionDecl
*FD
,
3410 const LangOptions
& LangOpts
) {
3411 return ((FD
->hasAttr
<GNUInlineAttr
>() || LangOpts
.GNUInline
) &&
3412 !LangOpts
.CPlusPlus
&&
3413 FD
->isInlineSpecified() &&
3414 FD
->getStorageClass() == SC_Extern
);
3417 const AttributedType
*Sema::getCallingConvAttributedType(QualType T
) const {
3418 const AttributedType
*AT
= T
->getAs
<AttributedType
>();
3419 while (AT
&& !AT
->isCallingConv())
3420 AT
= AT
->getModifiedType()->getAs
<AttributedType
>();
3424 template <typename T
>
3425 static bool haveIncompatibleLanguageLinkages(const T
*Old
, const T
*New
) {
3426 const DeclContext
*DC
= Old
->getDeclContext();
3430 LanguageLinkage OldLinkage
= Old
->getLanguageLinkage();
3431 if (OldLinkage
== CXXLanguageLinkage
&& New
->isInExternCContext())
3433 if (OldLinkage
== CLanguageLinkage
&& New
->isInExternCXXContext())
3438 template<typename T
> static bool isExternC(T
*D
) { return D
->isExternC(); }
3439 static bool isExternC(VarTemplateDecl
*) { return false; }
3440 static bool isExternC(FunctionTemplateDecl
*) { return false; }
3442 /// Check whether a redeclaration of an entity introduced by a
3443 /// using-declaration is valid, given that we know it's not an overload
3444 /// (nor a hidden tag declaration).
3445 template<typename ExpectedDecl
>
3446 static bool checkUsingShadowRedecl(Sema
&S
, UsingShadowDecl
*OldS
,
3447 ExpectedDecl
*New
) {
3448 // C++11 [basic.scope.declarative]p4:
3449 // Given a set of declarations in a single declarative region, each of
3450 // which specifies the same unqualified name,
3451 // -- they shall all refer to the same entity, or all refer to functions
3452 // and function templates; or
3453 // -- exactly one declaration shall declare a class name or enumeration
3454 // name that is not a typedef name and the other declarations shall all
3455 // refer to the same variable or enumerator, or all refer to functions
3456 // and function templates; in this case the class name or enumeration
3457 // name is hidden (3.3.10).
3459 // C++11 [namespace.udecl]p14:
3460 // If a function declaration in namespace scope or block scope has the
3461 // same name and the same parameter-type-list as a function introduced
3462 // by a using-declaration, and the declarations do not declare the same
3463 // function, the program is ill-formed.
3465 auto *Old
= dyn_cast
<ExpectedDecl
>(OldS
->getTargetDecl());
3467 !Old
->getDeclContext()->getRedeclContext()->Equals(
3468 New
->getDeclContext()->getRedeclContext()) &&
3469 !(isExternC(Old
) && isExternC(New
)))
3473 S
.Diag(New
->getLocation(), diag::err_using_decl_conflict_reverse
);
3474 S
.Diag(OldS
->getTargetDecl()->getLocation(), diag::note_using_decl_target
);
3475 S
.Diag(OldS
->getIntroducer()->getLocation(), diag::note_using_decl
) << 0;
3481 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl
*A
,
3482 const FunctionDecl
*B
) {
3483 assert(A
->getNumParams() == B
->getNumParams());
3485 auto AttrEq
= [](const ParmVarDecl
*A
, const ParmVarDecl
*B
) {
3486 const auto *AttrA
= A
->getAttr
<PassObjectSizeAttr
>();
3487 const auto *AttrB
= B
->getAttr
<PassObjectSizeAttr
>();
3490 return AttrA
&& AttrB
&& AttrA
->getType() == AttrB
->getType() &&
3491 AttrA
->isDynamic() == AttrB
->isDynamic();
3494 return std::equal(A
->param_begin(), A
->param_end(), B
->param_begin(), AttrEq
);
3497 /// If necessary, adjust the semantic declaration context for a qualified
3498 /// declaration to name the correct inline namespace within the qualifier.
3499 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl
*NewD
,
3500 DeclaratorDecl
*OldD
) {
3501 // The only case where we need to update the DeclContext is when
3502 // redeclaration lookup for a qualified name finds a declaration
3503 // in an inline namespace within the context named by the qualifier:
3505 // inline namespace N { int f(); }
3506 // int ::f(); // Sema DC needs adjusting from :: to N::.
3508 // For unqualified declarations, the semantic context *can* change
3509 // along the redeclaration chain (for local extern declarations,
3510 // extern "C" declarations, and friend declarations in particular).
3511 if (!NewD
->getQualifier())
3514 // NewD is probably already in the right context.
3515 auto *NamedDC
= NewD
->getDeclContext()->getRedeclContext();
3516 auto *SemaDC
= OldD
->getDeclContext()->getRedeclContext();
3517 if (NamedDC
->Equals(SemaDC
))
3520 assert((NamedDC
->InEnclosingNamespaceSetOf(SemaDC
) ||
3521 NewD
->isInvalidDecl() || OldD
->isInvalidDecl()) &&
3522 "unexpected context for redeclaration");
3524 auto *LexDC
= NewD
->getLexicalDeclContext();
3525 auto FixSemaDC
= [=](NamedDecl
*D
) {
3528 D
->setDeclContext(SemaDC
);
3529 D
->setLexicalDeclContext(LexDC
);
3533 if (auto *FD
= dyn_cast
<FunctionDecl
>(NewD
))
3534 FixSemaDC(FD
->getDescribedFunctionTemplate());
3535 else if (auto *VD
= dyn_cast
<VarDecl
>(NewD
))
3536 FixSemaDC(VD
->getDescribedVarTemplate());
3539 /// MergeFunctionDecl - We just parsed a function 'New' from
3540 /// declarator D which has the same name and scope as a previous
3541 /// declaration 'Old'. Figure out how to resolve this situation,
3542 /// merging decls or emitting diagnostics as appropriate.
3544 /// In C++, New and Old must be declarations that are not
3545 /// overloaded. Use IsOverload to determine whether New and Old are
3546 /// overloaded, and to select the Old declaration that New should be
3549 /// Returns true if there was an error, false otherwise.
3550 bool Sema::MergeFunctionDecl(FunctionDecl
*New
, NamedDecl
*&OldD
, Scope
*S
,
3551 bool MergeTypeWithOld
, bool NewDeclIsDefn
) {
3552 // Verify the old decl was also a function.
3553 FunctionDecl
*Old
= OldD
->getAsFunction();
3555 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(OldD
)) {
3556 if (New
->getFriendObjectKind()) {
3557 Diag(New
->getLocation(), diag::err_using_decl_friend
);
3558 Diag(Shadow
->getTargetDecl()->getLocation(),
3559 diag::note_using_decl_target
);
3560 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
3565 // Check whether the two declarations might declare the same function or
3566 // function template.
3567 if (FunctionTemplateDecl
*NewTemplate
=
3568 New
->getDescribedFunctionTemplate()) {
3569 if (checkUsingShadowRedecl
<FunctionTemplateDecl
>(*this, Shadow
,
3572 OldD
= Old
= cast
<FunctionTemplateDecl
>(Shadow
->getTargetDecl())
3575 if (checkUsingShadowRedecl
<FunctionDecl
>(*this, Shadow
, New
))
3577 OldD
= Old
= cast
<FunctionDecl
>(Shadow
->getTargetDecl());
3580 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
3581 << New
->getDeclName();
3582 notePreviousDefinition(OldD
, New
->getLocation());
3587 // If the old declaration was found in an inline namespace and the new
3588 // declaration was qualified, update the DeclContext to match.
3589 adjustDeclContextForDeclaratorDecl(New
, Old
);
3591 // If the old declaration is invalid, just give up here.
3592 if (Old
->isInvalidDecl())
3595 // Disallow redeclaration of some builtins.
3596 if (!getASTContext().canBuiltinBeRedeclared(Old
)) {
3597 Diag(New
->getLocation(), diag::err_builtin_redeclare
) << Old
->getDeclName();
3598 Diag(Old
->getLocation(), diag::note_previous_builtin_declaration
)
3599 << Old
<< Old
->getType();
3603 diag::kind PrevDiag
;
3604 SourceLocation OldLocation
;
3605 std::tie(PrevDiag
, OldLocation
) =
3606 getNoteDiagForInvalidRedeclaration(Old
, New
);
3608 // Don't complain about this if we're in GNU89 mode and the old function
3609 // is an extern inline function.
3610 // Don't complain about specializations. They are not supposed to have
3612 if (!isa
<CXXMethodDecl
>(New
) && !isa
<CXXMethodDecl
>(Old
) &&
3613 New
->getStorageClass() == SC_Static
&&
3614 Old
->hasExternalFormalLinkage() &&
3615 !New
->getTemplateSpecializationInfo() &&
3616 !canRedefineFunction(Old
, getLangOpts())) {
3617 if (getLangOpts().MicrosoftExt
) {
3618 Diag(New
->getLocation(), diag::ext_static_non_static
) << New
;
3619 Diag(OldLocation
, PrevDiag
);
3621 Diag(New
->getLocation(), diag::err_static_non_static
) << New
;
3622 Diag(OldLocation
, PrevDiag
);
3627 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
3628 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
3629 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
3631 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3632 New
->dropAttr
<InternalLinkageAttr
>();
3635 if (auto *EA
= New
->getAttr
<ErrorAttr
>()) {
3636 if (!Old
->hasAttr
<ErrorAttr
>()) {
3637 Diag(EA
->getLocation(), diag::err_attribute_missing_on_first_decl
) << EA
;
3638 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3639 New
->dropAttr
<ErrorAttr
>();
3643 if (CheckRedeclarationInModule(New
, Old
))
3646 if (!getLangOpts().CPlusPlus
) {
3647 bool OldOvl
= Old
->hasAttr
<OverloadableAttr
>();
3648 if (OldOvl
!= New
->hasAttr
<OverloadableAttr
>() && !Old
->isImplicit()) {
3649 Diag(New
->getLocation(), diag::err_attribute_overloadable_mismatch
)
3652 // Try our best to find a decl that actually has the overloadable
3653 // attribute for the note. In most cases (e.g. programs with only one
3654 // broken declaration/definition), this won't matter.
3656 // FIXME: We could do this if we juggled some extra state in
3657 // OverloadableAttr, rather than just removing it.
3658 const Decl
*DiagOld
= Old
;
3660 auto OldIter
= llvm::find_if(Old
->redecls(), [](const Decl
*D
) {
3661 const auto *A
= D
->getAttr
<OverloadableAttr
>();
3662 return A
&& !A
->isImplicit();
3664 // If we've implicitly added *all* of the overloadable attrs to this
3665 // chain, emitting a "previous redecl" note is pointless.
3666 DiagOld
= OldIter
== Old
->redecls_end() ? nullptr : *OldIter
;
3670 Diag(DiagOld
->getLocation(),
3671 diag::note_attribute_overloadable_prev_overload
)
3675 New
->addAttr(OverloadableAttr::CreateImplicit(Context
));
3677 New
->dropAttr
<OverloadableAttr
>();
3681 // If a function is first declared with a calling convention, but is later
3682 // declared or defined without one, all following decls assume the calling
3683 // convention of the first.
3685 // It's OK if a function is first declared without a calling convention,
3686 // but is later declared or defined with the default calling convention.
3688 // To test if either decl has an explicit calling convention, we look for
3689 // AttributedType sugar nodes on the type as written. If they are missing or
3690 // were canonicalized away, we assume the calling convention was implicit.
3692 // Note also that we DO NOT return at this point, because we still have
3693 // other tests to run.
3694 QualType OldQType
= Context
.getCanonicalType(Old
->getType());
3695 QualType NewQType
= Context
.getCanonicalType(New
->getType());
3696 const FunctionType
*OldType
= cast
<FunctionType
>(OldQType
);
3697 const FunctionType
*NewType
= cast
<FunctionType
>(NewQType
);
3698 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
3699 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
3700 bool RequiresAdjustment
= false;
3702 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC()) {
3703 FunctionDecl
*First
= Old
->getFirstDecl();
3704 const FunctionType
*FT
=
3705 First
->getType().getCanonicalType()->castAs
<FunctionType
>();
3706 FunctionType::ExtInfo FI
= FT
->getExtInfo();
3707 bool NewCCExplicit
= getCallingConvAttributedType(New
->getType());
3708 if (!NewCCExplicit
) {
3709 // Inherit the CC from the previous declaration if it was specified
3710 // there but not here.
3711 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3712 RequiresAdjustment
= true;
3713 } else if (Old
->getBuiltinID()) {
3714 // Builtin attribute isn't propagated to the new one yet at this point,
3715 // so we check if the old one is a builtin.
3717 // Calling Conventions on a Builtin aren't really useful and setting a
3718 // default calling convention and cdecl'ing some builtin redeclarations is
3719 // common, so warn and ignore the calling convention on the redeclaration.
3720 Diag(New
->getLocation(), diag::warn_cconv_unsupported
)
3721 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3722 << (int)CallingConventionIgnoredReason::BuiltinFunction
;
3723 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3724 RequiresAdjustment
= true;
3726 // Calling conventions aren't compatible, so complain.
3727 bool FirstCCExplicit
= getCallingConvAttributedType(First
->getType());
3728 Diag(New
->getLocation(), diag::err_cconv_change
)
3729 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3731 << (!FirstCCExplicit
? "" :
3732 FunctionType::getNameForCallConv(FI
.getCC()));
3734 // Put the note on the first decl, since it is the one that matters.
3735 Diag(First
->getLocation(), diag::note_previous_declaration
);
3740 // FIXME: diagnose the other way around?
3741 if (OldTypeInfo
.getNoReturn() && !NewTypeInfo
.getNoReturn()) {
3742 NewTypeInfo
= NewTypeInfo
.withNoReturn(true);
3743 RequiresAdjustment
= true;
3746 // Merge regparm attribute.
3747 if (OldTypeInfo
.getHasRegParm() != NewTypeInfo
.getHasRegParm() ||
3748 OldTypeInfo
.getRegParm() != NewTypeInfo
.getRegParm()) {
3749 if (NewTypeInfo
.getHasRegParm()) {
3750 Diag(New
->getLocation(), diag::err_regparm_mismatch
)
3751 << NewType
->getRegParmType()
3752 << OldType
->getRegParmType();
3753 Diag(OldLocation
, diag::note_previous_declaration
);
3757 NewTypeInfo
= NewTypeInfo
.withRegParm(OldTypeInfo
.getRegParm());
3758 RequiresAdjustment
= true;
3761 // Merge ns_returns_retained attribute.
3762 if (OldTypeInfo
.getProducesResult() != NewTypeInfo
.getProducesResult()) {
3763 if (NewTypeInfo
.getProducesResult()) {
3764 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
)
3765 << "'ns_returns_retained'";
3766 Diag(OldLocation
, diag::note_previous_declaration
);
3770 NewTypeInfo
= NewTypeInfo
.withProducesResult(true);
3771 RequiresAdjustment
= true;
3774 if (OldTypeInfo
.getNoCallerSavedRegs() !=
3775 NewTypeInfo
.getNoCallerSavedRegs()) {
3776 if (NewTypeInfo
.getNoCallerSavedRegs()) {
3777 AnyX86NoCallerSavedRegistersAttr
*Attr
=
3778 New
->getAttr
<AnyX86NoCallerSavedRegistersAttr
>();
3779 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
) << Attr
;
3780 Diag(OldLocation
, diag::note_previous_declaration
);
3784 NewTypeInfo
= NewTypeInfo
.withNoCallerSavedRegs(true);
3785 RequiresAdjustment
= true;
3788 if (RequiresAdjustment
) {
3789 const FunctionType
*AdjustedType
= New
->getType()->getAs
<FunctionType
>();
3790 AdjustedType
= Context
.adjustFunctionType(AdjustedType
, NewTypeInfo
);
3791 New
->setType(QualType(AdjustedType
, 0));
3792 NewQType
= Context
.getCanonicalType(New
->getType());
3795 // If this redeclaration makes the function inline, we may need to add it to
3796 // UndefinedButUsed.
3797 if (!Old
->isInlined() && New
->isInlined() &&
3798 !New
->hasAttr
<GNUInlineAttr
>() &&
3799 !getLangOpts().GNUInline
&&
3800 Old
->isUsed(false) &&
3801 !Old
->isDefined() && !New
->isThisDeclarationADefinition())
3802 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
3805 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3807 if (New
->hasAttr
<GNUInlineAttr
>() &&
3808 Old
->isInlined() && !Old
->hasAttr
<GNUInlineAttr
>()) {
3809 UndefinedButUsed
.erase(Old
->getCanonicalDecl());
3812 // If pass_object_size params don't match up perfectly, this isn't a valid
3814 if (Old
->getNumParams() > 0 && Old
->getNumParams() == New
->getNumParams() &&
3815 !hasIdenticalPassObjectSizeAttrs(Old
, New
)) {
3816 Diag(New
->getLocation(), diag::err_different_pass_object_size_params
)
3817 << New
->getDeclName();
3818 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3822 if (getLangOpts().CPlusPlus
) {
3823 // C++1z [over.load]p2
3824 // Certain function declarations cannot be overloaded:
3825 // -- Function declarations that differ only in the return type,
3826 // the exception specification, or both cannot be overloaded.
3828 // Check the exception specifications match. This may recompute the type of
3829 // both Old and New if it resolved exception specifications, so grab the
3830 // types again after this. Because this updates the type, we do this before
3831 // any of the other checks below, which may update the "de facto" NewQType
3832 // but do not necessarily update the type of New.
3833 if (CheckEquivalentExceptionSpec(Old
, New
))
3835 OldQType
= Context
.getCanonicalType(Old
->getType());
3836 NewQType
= Context
.getCanonicalType(New
->getType());
3838 // Go back to the type source info to compare the declared return types,
3839 // per C++1y [dcl.type.auto]p13:
3840 // Redeclarations or specializations of a function or function template
3841 // with a declared return type that uses a placeholder type shall also
3842 // use that placeholder, not a deduced type.
3843 QualType OldDeclaredReturnType
= Old
->getDeclaredReturnType();
3844 QualType NewDeclaredReturnType
= New
->getDeclaredReturnType();
3845 if (!Context
.hasSameType(OldDeclaredReturnType
, NewDeclaredReturnType
) &&
3846 canFullyTypeCheckRedeclaration(New
, Old
, NewDeclaredReturnType
,
3847 OldDeclaredReturnType
)) {
3849 if (NewDeclaredReturnType
->isObjCObjectPointerType() &&
3850 OldDeclaredReturnType
->isObjCObjectPointerType())
3851 // FIXME: This does the wrong thing for a deduced return type.
3852 ResQT
= Context
.mergeObjCGCQualifiers(NewQType
, OldQType
);
3853 if (ResQT
.isNull()) {
3854 if (New
->isCXXClassMember() && New
->isOutOfLine())
3855 Diag(New
->getLocation(), diag::err_member_def_does_not_match_ret_type
)
3856 << New
<< New
->getReturnTypeSourceRange();
3858 Diag(New
->getLocation(), diag::err_ovl_diff_return_type
)
3859 << New
->getReturnTypeSourceRange();
3860 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType()
3861 << Old
->getReturnTypeSourceRange();
3868 QualType OldReturnType
= OldType
->getReturnType();
3869 QualType NewReturnType
= cast
<FunctionType
>(NewQType
)->getReturnType();
3870 if (OldReturnType
!= NewReturnType
) {
3871 // If this function has a deduced return type and has already been
3872 // defined, copy the deduced value from the old declaration.
3873 AutoType
*OldAT
= Old
->getReturnType()->getContainedAutoType();
3874 if (OldAT
&& OldAT
->isDeduced()) {
3875 QualType DT
= OldAT
->getDeducedType();
3877 New
->setType(SubstAutoTypeDependent(New
->getType()));
3878 NewQType
= Context
.getCanonicalType(SubstAutoTypeDependent(NewQType
));
3880 New
->setType(SubstAutoType(New
->getType(), DT
));
3881 NewQType
= Context
.getCanonicalType(SubstAutoType(NewQType
, DT
));
3886 const CXXMethodDecl
*OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
3887 CXXMethodDecl
*NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
3888 if (OldMethod
&& NewMethod
) {
3889 // Preserve triviality.
3890 NewMethod
->setTrivial(OldMethod
->isTrivial());
3892 // MSVC allows explicit template specialization at class scope:
3893 // 2 CXXMethodDecls referring to the same function will be injected.
3894 // We don't want a redeclaration error.
3895 bool IsClassScopeExplicitSpecialization
=
3896 OldMethod
->isFunctionTemplateSpecialization() &&
3897 NewMethod
->isFunctionTemplateSpecialization();
3898 bool isFriend
= NewMethod
->getFriendObjectKind();
3900 if (!isFriend
&& NewMethod
->getLexicalDeclContext()->isRecord() &&
3901 !IsClassScopeExplicitSpecialization
) {
3902 // -- Member function declarations with the same name and the
3903 // same parameter types cannot be overloaded if any of them
3904 // is a static member function declaration.
3905 if (OldMethod
->isStatic() != NewMethod
->isStatic()) {
3906 Diag(New
->getLocation(), diag::err_ovl_static_nonstatic_member
);
3907 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3911 // C++ [class.mem]p1:
3912 // [...] A member shall not be declared twice in the
3913 // member-specification, except that a nested class or member
3914 // class template can be declared and then later defined.
3915 if (!inTemplateInstantiation()) {
3917 if (isa
<CXXConstructorDecl
>(OldMethod
))
3918 NewDiag
= diag::err_constructor_redeclared
;
3919 else if (isa
<CXXDestructorDecl
>(NewMethod
))
3920 NewDiag
= diag::err_destructor_redeclared
;
3921 else if (isa
<CXXConversionDecl
>(NewMethod
))
3922 NewDiag
= diag::err_conv_function_redeclared
;
3924 NewDiag
= diag::err_member_redeclared
;
3926 Diag(New
->getLocation(), NewDiag
);
3928 Diag(New
->getLocation(), diag::err_member_redeclared_in_instantiation
)
3929 << New
<< New
->getType();
3931 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3934 // Complain if this is an explicit declaration of a special
3935 // member that was initially declared implicitly.
3937 // As an exception, it's okay to befriend such methods in order
3938 // to permit the implicit constructor/destructor/operator calls.
3939 } else if (OldMethod
->isImplicit()) {
3941 NewMethod
->setImplicit();
3943 Diag(NewMethod
->getLocation(),
3944 diag::err_definition_of_implicitly_declared_member
)
3945 << New
<< getSpecialMember(OldMethod
);
3948 } else if (OldMethod
->getFirstDecl()->isExplicitlyDefaulted() && !isFriend
) {
3949 Diag(NewMethod
->getLocation(),
3950 diag::err_definition_of_explicitly_defaulted_member
)
3951 << getSpecialMember(OldMethod
);
3956 // C++11 [dcl.attr.noreturn]p1:
3957 // The first declaration of a function shall specify the noreturn
3958 // attribute if any declaration of that function specifies the noreturn
3960 if (const auto *NRA
= New
->getAttr
<CXX11NoReturnAttr
>())
3961 if (!Old
->hasAttr
<CXX11NoReturnAttr
>()) {
3962 Diag(NRA
->getLocation(), diag::err_attribute_missing_on_first_decl
)
3964 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3967 // C++11 [dcl.attr.depend]p2:
3968 // The first declaration of a function shall specify the
3969 // carries_dependency attribute for its declarator-id if any declaration
3970 // of the function specifies the carries_dependency attribute.
3971 const CarriesDependencyAttr
*CDA
= New
->getAttr
<CarriesDependencyAttr
>();
3972 if (CDA
&& !Old
->hasAttr
<CarriesDependencyAttr
>()) {
3973 Diag(CDA
->getLocation(),
3974 diag::err_carries_dependency_missing_on_first_decl
) << 0/*Function*/;
3975 Diag(Old
->getFirstDecl()->getLocation(),
3976 diag::note_carries_dependency_missing_first_decl
) << 0/*Function*/;
3980 // All declarations for a function shall agree exactly in both the
3981 // return type and the parameter-type-list.
3982 // We also want to respect all the extended bits except noreturn.
3984 // noreturn should now match unless the old type info didn't have it.
3985 QualType OldQTypeForComparison
= OldQType
;
3986 if (!OldTypeInfo
.getNoReturn() && NewTypeInfo
.getNoReturn()) {
3987 auto *OldType
= OldQType
->castAs
<FunctionProtoType
>();
3988 const FunctionType
*OldTypeForComparison
3989 = Context
.adjustFunctionType(OldType
, OldTypeInfo
.withNoReturn(true));
3990 OldQTypeForComparison
= QualType(OldTypeForComparison
, 0);
3991 assert(OldQTypeForComparison
.isCanonical());
3994 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
3995 // As a special case, retain the language linkage from previous
3996 // declarations of a friend function as an extension.
3998 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3999 // and is useful because there's otherwise no way to specify language
4000 // linkage within class scope.
4002 // Check cautiously as the friend object kind isn't yet complete.
4003 if (New
->getFriendObjectKind() != Decl::FOK_None
) {
4004 Diag(New
->getLocation(), diag::ext_retained_language_linkage
) << New
;
4005 Diag(OldLocation
, PrevDiag
);
4007 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4008 Diag(OldLocation
, PrevDiag
);
4013 // If the function types are compatible, merge the declarations. Ignore the
4014 // exception specifier because it was already checked above in
4015 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4016 // about incompatible types under -fms-compatibility.
4017 if (Context
.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison
,
4019 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4021 // If the types are imprecise (due to dependent constructs in friends or
4022 // local extern declarations), it's OK if they differ. We'll check again
4023 // during instantiation.
4024 if (!canFullyTypeCheckRedeclaration(New
, Old
, NewQType
, OldQType
))
4027 // Fall through for conflicting redeclarations and redefinitions.
4030 // C: Function types need to be compatible, not identical. This handles
4031 // duplicate function decls like "void f(int); void f(enum X);" properly.
4032 if (!getLangOpts().CPlusPlus
) {
4033 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4034 // type is specified by a function definition that contains a (possibly
4035 // empty) identifier list, both shall agree in the number of parameters
4036 // and the type of each parameter shall be compatible with the type that
4037 // results from the application of default argument promotions to the
4038 // type of the corresponding identifier. ...
4039 // This cannot be handled by ASTContext::typesAreCompatible() because that
4040 // doesn't know whether the function type is for a definition or not when
4041 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4042 // we need to cover here is that the number of arguments agree as the
4043 // default argument promotion rules were already checked by
4044 // ASTContext::typesAreCompatible().
4045 if (Old
->hasPrototype() && !New
->hasWrittenPrototype() && NewDeclIsDefn
&&
4046 Old
->getNumParams() != New
->getNumParams() && !Old
->isImplicit()) {
4047 if (Old
->hasInheritedPrototype())
4048 Old
= Old
->getCanonicalDecl();
4049 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
;
4050 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
4054 // If we are merging two functions where only one of them has a prototype,
4055 // we may have enough information to decide to issue a diagnostic that the
4056 // function without a protoype will change behavior in C2x. This handles
4058 // void i(); void i(int j);
4059 // void i(int j); void i();
4060 // void i(); void i(int j) {}
4061 // See ActOnFinishFunctionBody() for other cases of the behavior change
4062 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4063 // type without a prototype.
4064 if (New
->hasWrittenPrototype() != Old
->hasWrittenPrototype() &&
4065 !New
->isImplicit() && !Old
->isImplicit()) {
4066 const FunctionDecl
*WithProto
, *WithoutProto
;
4067 if (New
->hasWrittenPrototype()) {
4075 if (WithProto
->getNumParams() != 0) {
4076 if (WithoutProto
->getBuiltinID() == 0 && !WithoutProto
->isImplicit()) {
4077 // The one without the prototype will be changing behavior in C2x, so
4078 // warn about that one so long as it's a user-visible declaration.
4079 bool IsWithoutProtoADef
= false, IsWithProtoADef
= false;
4080 if (WithoutProto
== New
)
4081 IsWithoutProtoADef
= NewDeclIsDefn
;
4083 IsWithProtoADef
= NewDeclIsDefn
;
4084 Diag(WithoutProto
->getLocation(),
4085 diag::warn_non_prototype_changes_behavior
)
4086 << IsWithoutProtoADef
<< (WithoutProto
->getNumParams() ? 0 : 1)
4087 << (WithoutProto
== Old
) << IsWithProtoADef
;
4089 // The reason the one without the prototype will be changing behavior
4090 // is because of the one with the prototype, so note that so long as
4091 // it's a user-visible declaration. There is one exception to this:
4092 // when the new declaration is a definition without a prototype, the
4093 // old declaration with a prototype is not the cause of the issue,
4094 // and that does not need to be noted because the one with a
4095 // prototype will not change behavior in C2x.
4096 if (WithProto
->getBuiltinID() == 0 && !WithProto
->isImplicit() &&
4097 !IsWithoutProtoADef
)
4098 Diag(WithProto
->getLocation(), diag::note_conflicting_prototype
);
4103 if (Context
.typesAreCompatible(OldQType
, NewQType
)) {
4104 const FunctionType
*OldFuncType
= OldQType
->getAs
<FunctionType
>();
4105 const FunctionType
*NewFuncType
= NewQType
->getAs
<FunctionType
>();
4106 const FunctionProtoType
*OldProto
= nullptr;
4107 if (MergeTypeWithOld
&& isa
<FunctionNoProtoType
>(NewFuncType
) &&
4108 (OldProto
= dyn_cast
<FunctionProtoType
>(OldFuncType
))) {
4109 // The old declaration provided a function prototype, but the
4110 // new declaration does not. Merge in the prototype.
4111 assert(!OldProto
->hasExceptionSpec() && "Exception spec in C");
4112 NewQType
= Context
.getFunctionType(NewFuncType
->getReturnType(),
4113 OldProto
->getParamTypes(),
4114 OldProto
->getExtProtoInfo());
4115 New
->setType(NewQType
);
4116 New
->setHasInheritedPrototype();
4118 // Synthesize parameters with the same types.
4119 SmallVector
<ParmVarDecl
*, 16> Params
;
4120 for (const auto &ParamType
: OldProto
->param_types()) {
4121 ParmVarDecl
*Param
= ParmVarDecl::Create(
4122 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
4123 ParamType
, /*TInfo=*/nullptr, SC_None
, nullptr);
4124 Param
->setScopeInfo(0, Params
.size());
4125 Param
->setImplicit();
4126 Params
.push_back(Param
);
4129 New
->setParams(Params
);
4132 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4136 // Check if the function types are compatible when pointer size address
4137 // spaces are ignored.
4138 if (Context
.hasSameFunctionTypeIgnoringPtrSizes(OldQType
, NewQType
))
4141 // GNU C permits a K&R definition to follow a prototype declaration
4142 // if the declared types of the parameters in the K&R definition
4143 // match the types in the prototype declaration, even when the
4144 // promoted types of the parameters from the K&R definition differ
4145 // from the types in the prototype. GCC then keeps the types from
4148 // If a variadic prototype is followed by a non-variadic K&R definition,
4149 // the K&R definition becomes variadic. This is sort of an edge case, but
4150 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4152 if (!getLangOpts().CPlusPlus
&&
4153 Old
->hasPrototype() && !New
->hasPrototype() &&
4154 New
->getType()->getAs
<FunctionProtoType
>() &&
4155 Old
->getNumParams() == New
->getNumParams()) {
4156 SmallVector
<QualType
, 16> ArgTypes
;
4157 SmallVector
<GNUCompatibleParamWarning
, 16> Warnings
;
4158 const FunctionProtoType
*OldProto
4159 = Old
->getType()->getAs
<FunctionProtoType
>();
4160 const FunctionProtoType
*NewProto
4161 = New
->getType()->getAs
<FunctionProtoType
>();
4163 // Determine whether this is the GNU C extension.
4164 QualType MergedReturn
= Context
.mergeTypes(OldProto
->getReturnType(),
4165 NewProto
->getReturnType());
4166 bool LooseCompatible
= !MergedReturn
.isNull();
4167 for (unsigned Idx
= 0, End
= Old
->getNumParams();
4168 LooseCompatible
&& Idx
!= End
; ++Idx
) {
4169 ParmVarDecl
*OldParm
= Old
->getParamDecl(Idx
);
4170 ParmVarDecl
*NewParm
= New
->getParamDecl(Idx
);
4171 if (Context
.typesAreCompatible(OldParm
->getType(),
4172 NewProto
->getParamType(Idx
))) {
4173 ArgTypes
.push_back(NewParm
->getType());
4174 } else if (Context
.typesAreCompatible(OldParm
->getType(),
4176 /*CompareUnqualified=*/true)) {
4177 GNUCompatibleParamWarning Warn
= { OldParm
, NewParm
,
4178 NewProto
->getParamType(Idx
) };
4179 Warnings
.push_back(Warn
);
4180 ArgTypes
.push_back(NewParm
->getType());
4182 LooseCompatible
= false;
4185 if (LooseCompatible
) {
4186 for (unsigned Warn
= 0; Warn
< Warnings
.size(); ++Warn
) {
4187 Diag(Warnings
[Warn
].NewParm
->getLocation(),
4188 diag::ext_param_promoted_not_compatible_with_prototype
)
4189 << Warnings
[Warn
].PromotedType
4190 << Warnings
[Warn
].OldParm
->getType();
4191 if (Warnings
[Warn
].OldParm
->getLocation().isValid())
4192 Diag(Warnings
[Warn
].OldParm
->getLocation(),
4193 diag::note_previous_declaration
);
4196 if (MergeTypeWithOld
)
4197 New
->setType(Context
.getFunctionType(MergedReturn
, ArgTypes
,
4198 OldProto
->getExtProtoInfo()));
4199 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4202 // Fall through to diagnose conflicting types.
4205 // A function that has already been declared has been redeclared or
4206 // defined with a different type; show an appropriate diagnostic.
4208 // If the previous declaration was an implicitly-generated builtin
4209 // declaration, then at the very least we should use a specialized note.
4211 if (Old
->isImplicit() && (BuiltinID
= Old
->getBuiltinID())) {
4212 // If it's actually a library-defined builtin function like 'malloc'
4213 // or 'printf', just warn about the incompatible redeclaration.
4214 if (Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
)) {
4215 Diag(New
->getLocation(), diag::warn_redecl_library_builtin
) << New
;
4216 Diag(OldLocation
, diag::note_previous_builtin_declaration
)
4217 << Old
<< Old
->getType();
4221 PrevDiag
= diag::note_previous_builtin_declaration
;
4224 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
->getDeclName();
4225 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4229 /// Completes the merge of two function declarations that are
4230 /// known to be compatible.
4232 /// This routine handles the merging of attributes and other
4233 /// properties of function declarations from the old declaration to
4234 /// the new declaration, once we know that New is in fact a
4235 /// redeclaration of Old.
4238 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl
*New
, FunctionDecl
*Old
,
4239 Scope
*S
, bool MergeTypeWithOld
) {
4240 // Merge the attributes
4241 mergeDeclAttributes(New
, Old
);
4243 // Merge "pure" flag.
4247 // Merge "used" flag.
4248 if (Old
->getMostRecentDecl()->isUsed(false))
4251 // Merge attributes from the parameters. These can mismatch with K&R
4253 if (New
->getNumParams() == Old
->getNumParams())
4254 for (unsigned i
= 0, e
= New
->getNumParams(); i
!= e
; ++i
) {
4255 ParmVarDecl
*NewParam
= New
->getParamDecl(i
);
4256 ParmVarDecl
*OldParam
= Old
->getParamDecl(i
);
4257 mergeParamDeclAttributes(NewParam
, OldParam
, *this);
4258 mergeParamDeclTypes(NewParam
, OldParam
, *this);
4261 if (getLangOpts().CPlusPlus
)
4262 return MergeCXXFunctionDecl(New
, Old
, S
);
4264 // Merge the function types so the we get the composite types for the return
4265 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4267 QualType Merged
= Context
.mergeTypes(Old
->getType(), New
->getType());
4268 if (!Merged
.isNull() && MergeTypeWithOld
)
4269 New
->setType(Merged
);
4274 void Sema::mergeObjCMethodDecls(ObjCMethodDecl
*newMethod
,
4275 ObjCMethodDecl
*oldMethod
) {
4276 // Merge the attributes, including deprecated/unavailable
4277 AvailabilityMergeKind MergeKind
=
4278 isa
<ObjCProtocolDecl
>(oldMethod
->getDeclContext())
4279 ? (oldMethod
->isOptional() ? AMK_OptionalProtocolImplementation
4280 : AMK_ProtocolImplementation
)
4281 : isa
<ObjCImplDecl
>(newMethod
->getDeclContext()) ? AMK_Redeclaration
4284 mergeDeclAttributes(newMethod
, oldMethod
, MergeKind
);
4286 // Merge attributes from the parameters.
4287 ObjCMethodDecl::param_const_iterator oi
= oldMethod
->param_begin(),
4288 oe
= oldMethod
->param_end();
4289 for (ObjCMethodDecl::param_iterator
4290 ni
= newMethod
->param_begin(), ne
= newMethod
->param_end();
4291 ni
!= ne
&& oi
!= oe
; ++ni
, ++oi
)
4292 mergeParamDeclAttributes(*ni
, *oi
, *this);
4294 CheckObjCMethodOverride(newMethod
, oldMethod
);
4297 static void diagnoseVarDeclTypeMismatch(Sema
&S
, VarDecl
*New
, VarDecl
* Old
) {
4298 assert(!S
.Context
.hasSameType(New
->getType(), Old
->getType()));
4300 S
.Diag(New
->getLocation(), New
->isThisDeclarationADefinition()
4301 ? diag::err_redefinition_different_type
4302 : diag::err_redeclaration_different_type
)
4303 << New
->getDeclName() << New
->getType() << Old
->getType();
4305 diag::kind PrevDiag
;
4306 SourceLocation OldLocation
;
4307 std::tie(PrevDiag
, OldLocation
)
4308 = getNoteDiagForInvalidRedeclaration(Old
, New
);
4309 S
.Diag(OldLocation
, PrevDiag
);
4310 New
->setInvalidDecl();
4313 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4314 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4315 /// emitting diagnostics as appropriate.
4317 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4318 /// to here in AddInitializerToDecl. We can't check them before the initializer
4320 void Sema::MergeVarDeclTypes(VarDecl
*New
, VarDecl
*Old
,
4321 bool MergeTypeWithOld
) {
4322 if (New
->isInvalidDecl() || Old
->isInvalidDecl())
4326 if (getLangOpts().CPlusPlus
) {
4327 if (New
->getType()->isUndeducedType()) {
4328 // We don't know what the new type is until the initializer is attached.
4330 } else if (Context
.hasSameType(New
->getType(), Old
->getType())) {
4331 // These could still be something that needs exception specs checked.
4332 return MergeVarDeclExceptionSpecs(New
, Old
);
4334 // C++ [basic.link]p10:
4335 // [...] the types specified by all declarations referring to a given
4336 // object or function shall be identical, except that declarations for an
4337 // array object can specify array types that differ by the presence or
4338 // absence of a major array bound (8.3.4).
4339 else if (Old
->getType()->isArrayType() && New
->getType()->isArrayType()) {
4340 const ArrayType
*OldArray
= Context
.getAsArrayType(Old
->getType());
4341 const ArrayType
*NewArray
= Context
.getAsArrayType(New
->getType());
4343 // We are merging a variable declaration New into Old. If it has an array
4344 // bound, and that bound differs from Old's bound, we should diagnose the
4346 if (!NewArray
->isIncompleteArrayType() && !NewArray
->isDependentType()) {
4347 for (VarDecl
*PrevVD
= Old
->getMostRecentDecl(); PrevVD
;
4348 PrevVD
= PrevVD
->getPreviousDecl()) {
4349 QualType PrevVDTy
= PrevVD
->getType();
4350 if (PrevVDTy
->isIncompleteArrayType() || PrevVDTy
->isDependentType())
4353 if (!Context
.hasSameType(New
->getType(), PrevVDTy
))
4354 return diagnoseVarDeclTypeMismatch(*this, New
, PrevVD
);
4358 if (OldArray
->isIncompleteArrayType() && NewArray
->isArrayType()) {
4359 if (Context
.hasSameType(OldArray
->getElementType(),
4360 NewArray
->getElementType()))
4361 MergedT
= New
->getType();
4363 // FIXME: Check visibility. New is hidden but has a complete type. If New
4364 // has no array bound, it should not inherit one from Old, if Old is not
4366 else if (OldArray
->isArrayType() && NewArray
->isIncompleteArrayType()) {
4367 if (Context
.hasSameType(OldArray
->getElementType(),
4368 NewArray
->getElementType()))
4369 MergedT
= Old
->getType();
4372 else if (New
->getType()->isObjCObjectPointerType() &&
4373 Old
->getType()->isObjCObjectPointerType()) {
4374 MergedT
= Context
.mergeObjCGCQualifiers(New
->getType(),
4379 // All declarations that refer to the same object or function shall have
4381 MergedT
= Context
.mergeTypes(New
->getType(), Old
->getType());
4383 if (MergedT
.isNull()) {
4384 // It's OK if we couldn't merge types if either type is dependent, for a
4385 // block-scope variable. In other cases (static data members of class
4386 // templates, variable templates, ...), we require the types to be
4388 // FIXME: The C++ standard doesn't say anything about this.
4389 if ((New
->getType()->isDependentType() ||
4390 Old
->getType()->isDependentType()) && New
->isLocalVarDecl()) {
4391 // If the old type was dependent, we can't merge with it, so the new type
4392 // becomes dependent for now. We'll reproduce the original type when we
4393 // instantiate the TypeSourceInfo for the variable.
4394 if (!New
->getType()->isDependentType() && MergeTypeWithOld
)
4395 New
->setType(Context
.DependentTy
);
4398 return diagnoseVarDeclTypeMismatch(*this, New
, Old
);
4401 // Don't actually update the type on the new declaration if the old
4402 // declaration was an extern declaration in a different scope.
4403 if (MergeTypeWithOld
)
4404 New
->setType(MergedT
);
4407 static bool mergeTypeWithPrevious(Sema
&S
, VarDecl
*NewVD
, VarDecl
*OldVD
,
4408 LookupResult
&Previous
) {
4410 // For an identifier with internal or external linkage declared
4411 // in a scope in which a prior declaration of that identifier is
4412 // visible, if the prior declaration specifies internal or
4413 // external linkage, the type of the identifier at the later
4414 // declaration becomes the composite type.
4416 // If the variable isn't visible, we do not merge with its type.
4417 if (Previous
.isShadowed())
4420 if (S
.getLangOpts().CPlusPlus
) {
4421 // C++11 [dcl.array]p3:
4422 // If there is a preceding declaration of the entity in the same
4423 // scope in which the bound was specified, an omitted array bound
4424 // is taken to be the same as in that earlier declaration.
4425 return NewVD
->isPreviousDeclInSameBlockScope() ||
4426 (!OldVD
->getLexicalDeclContext()->isFunctionOrMethod() &&
4427 !NewVD
->getLexicalDeclContext()->isFunctionOrMethod());
4429 // If the old declaration was function-local, don't merge with its
4430 // type unless we're in the same function.
4431 return !OldVD
->getLexicalDeclContext()->isFunctionOrMethod() ||
4432 OldVD
->getLexicalDeclContext() == NewVD
->getLexicalDeclContext();
4436 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4437 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4438 /// situation, merging decls or emitting diagnostics as appropriate.
4440 /// Tentative definition rules (C99 6.9.2p2) are checked by
4441 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4442 /// definitions here, since the initializer hasn't been attached.
4444 void Sema::MergeVarDecl(VarDecl
*New
, LookupResult
&Previous
) {
4445 // If the new decl is already invalid, don't do any other checking.
4446 if (New
->isInvalidDecl())
4449 if (!shouldLinkPossiblyHiddenDecl(Previous
, New
))
4452 VarTemplateDecl
*NewTemplate
= New
->getDescribedVarTemplate();
4454 // Verify the old decl was also a variable or variable template.
4455 VarDecl
*Old
= nullptr;
4456 VarTemplateDecl
*OldTemplate
= nullptr;
4457 if (Previous
.isSingleResult()) {
4459 OldTemplate
= dyn_cast
<VarTemplateDecl
>(Previous
.getFoundDecl());
4460 Old
= OldTemplate
? OldTemplate
->getTemplatedDecl() : nullptr;
4463 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4464 if (checkUsingShadowRedecl
<VarTemplateDecl
>(*this, Shadow
, NewTemplate
))
4465 return New
->setInvalidDecl();
4467 Old
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl());
4470 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4471 if (checkUsingShadowRedecl
<VarDecl
>(*this, Shadow
, New
))
4472 return New
->setInvalidDecl();
4476 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
4477 << New
->getDeclName();
4478 notePreviousDefinition(Previous
.getRepresentativeDecl(),
4479 New
->getLocation());
4480 return New
->setInvalidDecl();
4483 // If the old declaration was found in an inline namespace and the new
4484 // declaration was qualified, update the DeclContext to match.
4485 adjustDeclContextForDeclaratorDecl(New
, Old
);
4487 // Ensure the template parameters are compatible.
4489 !TemplateParameterListsAreEqual(NewTemplate
->getTemplateParameters(),
4490 OldTemplate
->getTemplateParameters(),
4491 /*Complain=*/true, TPL_TemplateMatch
))
4492 return New
->setInvalidDecl();
4494 // C++ [class.mem]p1:
4495 // A member shall not be declared twice in the member-specification [...]
4497 // Here, we need only consider static data members.
4498 if (Old
->isStaticDataMember() && !New
->isOutOfLine()) {
4499 Diag(New
->getLocation(), diag::err_duplicate_member
)
4500 << New
->getIdentifier();
4501 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4502 New
->setInvalidDecl();
4505 mergeDeclAttributes(New
, Old
);
4506 // Warn if an already-declared variable is made a weak_import in a subsequent
4508 if (New
->hasAttr
<WeakImportAttr
>() &&
4509 Old
->getStorageClass() == SC_None
&&
4510 !Old
->hasAttr
<WeakImportAttr
>()) {
4511 Diag(New
->getLocation(), diag::warn_weak_import
) << New
->getDeclName();
4512 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4513 // Remove weak_import attribute on new declaration.
4514 New
->dropAttr
<WeakImportAttr
>();
4517 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
4518 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
4519 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
4521 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4522 New
->dropAttr
<InternalLinkageAttr
>();
4526 VarDecl
*MostRecent
= Old
->getMostRecentDecl();
4527 if (MostRecent
!= Old
) {
4528 MergeVarDeclTypes(New
, MostRecent
,
4529 mergeTypeWithPrevious(*this, New
, MostRecent
, Previous
));
4530 if (New
->isInvalidDecl())
4534 MergeVarDeclTypes(New
, Old
, mergeTypeWithPrevious(*this, New
, Old
, Previous
));
4535 if (New
->isInvalidDecl())
4538 diag::kind PrevDiag
;
4539 SourceLocation OldLocation
;
4540 std::tie(PrevDiag
, OldLocation
) =
4541 getNoteDiagForInvalidRedeclaration(Old
, New
);
4543 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4544 if (New
->getStorageClass() == SC_Static
&&
4545 !New
->isStaticDataMember() &&
4546 Old
->hasExternalFormalLinkage()) {
4547 if (getLangOpts().MicrosoftExt
) {
4548 Diag(New
->getLocation(), diag::ext_static_non_static
)
4549 << New
->getDeclName();
4550 Diag(OldLocation
, PrevDiag
);
4552 Diag(New
->getLocation(), diag::err_static_non_static
)
4553 << New
->getDeclName();
4554 Diag(OldLocation
, PrevDiag
);
4555 return New
->setInvalidDecl();
4559 // For an identifier declared with the storage-class specifier
4560 // extern in a scope in which a prior declaration of that
4561 // identifier is visible,23) if the prior declaration specifies
4562 // internal or external linkage, the linkage of the identifier at
4563 // the later declaration is the same as the linkage specified at
4564 // the prior declaration. If no prior declaration is visible, or
4565 // if the prior declaration specifies no linkage, then the
4566 // identifier has external linkage.
4567 if (New
->hasExternalStorage() && Old
->hasLinkage())
4569 else if (New
->getCanonicalDecl()->getStorageClass() != SC_Static
&&
4570 !New
->isStaticDataMember() &&
4571 Old
->getCanonicalDecl()->getStorageClass() == SC_Static
) {
4572 Diag(New
->getLocation(), diag::err_non_static_static
) << New
->getDeclName();
4573 Diag(OldLocation
, PrevDiag
);
4574 return New
->setInvalidDecl();
4577 // Check if extern is followed by non-extern and vice-versa.
4578 if (New
->hasExternalStorage() &&
4579 !Old
->hasLinkage() && Old
->isLocalVarDeclOrParm()) {
4580 Diag(New
->getLocation(), diag::err_extern_non_extern
) << New
->getDeclName();
4581 Diag(OldLocation
, PrevDiag
);
4582 return New
->setInvalidDecl();
4584 if (Old
->hasLinkage() && New
->isLocalVarDeclOrParm() &&
4585 !New
->hasExternalStorage()) {
4586 Diag(New
->getLocation(), diag::err_non_extern_extern
) << New
->getDeclName();
4587 Diag(OldLocation
, PrevDiag
);
4588 return New
->setInvalidDecl();
4591 if (CheckRedeclarationInModule(New
, Old
))
4594 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4596 // FIXME: The test for external storage here seems wrong? We still
4597 // need to check for mismatches.
4598 if (!New
->hasExternalStorage() && !New
->isFileVarDecl() &&
4599 // Don't complain about out-of-line definitions of static members.
4600 !(Old
->getLexicalDeclContext()->isRecord() &&
4601 !New
->getLexicalDeclContext()->isRecord())) {
4602 Diag(New
->getLocation(), diag::err_redefinition
) << New
->getDeclName();
4603 Diag(OldLocation
, PrevDiag
);
4604 return New
->setInvalidDecl();
4607 if (New
->isInline() && !Old
->getMostRecentDecl()->isInline()) {
4608 if (VarDecl
*Def
= Old
->getDefinition()) {
4609 // C++1z [dcl.fcn.spec]p4:
4610 // If the definition of a variable appears in a translation unit before
4611 // its first declaration as inline, the program is ill-formed.
4612 Diag(New
->getLocation(), diag::err_inline_decl_follows_def
) << New
;
4613 Diag(Def
->getLocation(), diag::note_previous_definition
);
4617 // If this redeclaration makes the variable inline, we may need to add it to
4618 // UndefinedButUsed.
4619 if (!Old
->isInline() && New
->isInline() && Old
->isUsed(false) &&
4620 !Old
->getDefinition() && !New
->isThisDeclarationADefinition())
4621 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
4624 if (New
->getTLSKind() != Old
->getTLSKind()) {
4625 if (!Old
->getTLSKind()) {
4626 Diag(New
->getLocation(), diag::err_thread_non_thread
) << New
->getDeclName();
4627 Diag(OldLocation
, PrevDiag
);
4628 } else if (!New
->getTLSKind()) {
4629 Diag(New
->getLocation(), diag::err_non_thread_thread
) << New
->getDeclName();
4630 Diag(OldLocation
, PrevDiag
);
4632 // Do not allow redeclaration to change the variable between requiring
4633 // static and dynamic initialization.
4634 // FIXME: GCC allows this, but uses the TLS keyword on the first
4635 // declaration to determine the kind. Do we need to be compatible here?
4636 Diag(New
->getLocation(), diag::err_thread_thread_different_kind
)
4637 << New
->getDeclName() << (New
->getTLSKind() == VarDecl::TLS_Dynamic
);
4638 Diag(OldLocation
, PrevDiag
);
4642 // C++ doesn't have tentative definitions, so go right ahead and check here.
4643 if (getLangOpts().CPlusPlus
) {
4644 if (Old
->isStaticDataMember() && Old
->getCanonicalDecl()->isInline() &&
4645 Old
->getCanonicalDecl()->isConstexpr()) {
4646 // This definition won't be a definition any more once it's been merged.
4647 Diag(New
->getLocation(),
4648 diag::warn_deprecated_redundant_constexpr_static_def
);
4649 } else if (New
->isThisDeclarationADefinition() == VarDecl::Definition
) {
4650 VarDecl
*Def
= Old
->getDefinition();
4651 if (Def
&& checkVarDeclRedefinition(Def
, New
))
4656 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
4657 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4658 Diag(OldLocation
, PrevDiag
);
4659 New
->setInvalidDecl();
4663 // Merge "used" flag.
4664 if (Old
->getMostRecentDecl()->isUsed(false))
4667 // Keep a chain of previous declarations.
4668 New
->setPreviousDecl(Old
);
4670 NewTemplate
->setPreviousDecl(OldTemplate
);
4672 // Inherit access appropriately.
4673 New
->setAccess(Old
->getAccess());
4675 NewTemplate
->setAccess(New
->getAccess());
4677 if (Old
->isInline())
4678 New
->setImplicitlyInline();
4681 void Sema::notePreviousDefinition(const NamedDecl
*Old
, SourceLocation New
) {
4682 SourceManager
&SrcMgr
= getSourceManager();
4683 auto FNewDecLoc
= SrcMgr
.getDecomposedLoc(New
);
4684 auto FOldDecLoc
= SrcMgr
.getDecomposedLoc(Old
->getLocation());
4685 auto *FNew
= SrcMgr
.getFileEntryForID(FNewDecLoc
.first
);
4686 auto *FOld
= SrcMgr
.getFileEntryForID(FOldDecLoc
.first
);
4687 auto &HSI
= PP
.getHeaderSearchInfo();
4688 StringRef HdrFilename
=
4689 SrcMgr
.getFilename(SrcMgr
.getSpellingLoc(Old
->getLocation()));
4691 auto noteFromModuleOrInclude
= [&](Module
*Mod
,
4692 SourceLocation IncLoc
) -> bool {
4693 // Redefinition errors with modules are common with non modular mapped
4694 // headers, example: a non-modular header H in module A that also gets
4695 // included directly in a TU. Pointing twice to the same header/definition
4696 // is confusing, try to get better diagnostics when modules is on.
4697 if (IncLoc
.isValid()) {
4699 Diag(IncLoc
, diag::note_redefinition_modules_same_file
)
4700 << HdrFilename
.str() << Mod
->getFullModuleName();
4701 if (!Mod
->DefinitionLoc
.isInvalid())
4702 Diag(Mod
->DefinitionLoc
, diag::note_defined_here
)
4703 << Mod
->getFullModuleName();
4705 Diag(IncLoc
, diag::note_redefinition_include_same_file
)
4706 << HdrFilename
.str();
4714 // Is it the same file and same offset? Provide more information on why
4715 // this leads to a redefinition error.
4716 if (FNew
== FOld
&& FNewDecLoc
.second
== FOldDecLoc
.second
) {
4717 SourceLocation OldIncLoc
= SrcMgr
.getIncludeLoc(FOldDecLoc
.first
);
4718 SourceLocation NewIncLoc
= SrcMgr
.getIncludeLoc(FNewDecLoc
.first
);
4720 noteFromModuleOrInclude(Old
->getOwningModule(), OldIncLoc
);
4721 EmittedDiag
|= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc
);
4723 // If the header has no guards, emit a note suggesting one.
4724 if (FOld
&& !HSI
.isFileMultipleIncludeGuarded(FOld
))
4725 Diag(Old
->getLocation(), diag::note_use_ifdef_guards
);
4731 // Redefinition coming from different files or couldn't do better above.
4732 if (Old
->getLocation().isValid())
4733 Diag(Old
->getLocation(), diag::note_previous_definition
);
4736 /// We've just determined that \p Old and \p New both appear to be definitions
4737 /// of the same variable. Either diagnose or fix the problem.
4738 bool Sema::checkVarDeclRedefinition(VarDecl
*Old
, VarDecl
*New
) {
4739 if (!hasVisibleDefinition(Old
) &&
4740 (New
->getFormalLinkage() == InternalLinkage
||
4742 isa
<VarTemplateSpecializationDecl
>(New
) ||
4743 New
->getDescribedVarTemplate() ||
4744 New
->getNumTemplateParameterLists() ||
4745 New
->getDeclContext()->isDependentContext())) {
4746 // The previous definition is hidden, and multiple definitions are
4747 // permitted (in separate TUs). Demote this to a declaration.
4748 New
->demoteThisDefinitionToDeclaration();
4750 // Make the canonical definition visible.
4751 if (auto *OldTD
= Old
->getDescribedVarTemplate())
4752 makeMergedDefinitionVisible(OldTD
);
4753 makeMergedDefinitionVisible(Old
);
4756 Diag(New
->getLocation(), diag::err_redefinition
) << New
;
4757 notePreviousDefinition(Old
, New
->getLocation());
4758 New
->setInvalidDecl();
4763 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4764 /// no declarator (e.g. "struct foo;") is parsed.
4765 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
4767 const ParsedAttributesView
&DeclAttrs
,
4768 RecordDecl
*&AnonRecord
) {
4769 return ParsedFreeStandingDeclSpec(
4770 S
, AS
, DS
, DeclAttrs
, MultiTemplateParamsArg(), false, AnonRecord
);
4773 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4774 // disambiguate entities defined in different scopes.
4775 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4777 // We will pick our mangling number depending on which version of MSVC is being
4779 static unsigned getMSManglingNumber(const LangOptions
&LO
, Scope
*S
) {
4780 return LO
.isCompatibleWithMSVC(LangOptions::MSVC2015
)
4781 ? S
->getMSCurManglingNumber()
4782 : S
->getMSLastManglingNumber();
4785 void Sema::handleTagNumbering(const TagDecl
*Tag
, Scope
*TagScope
) {
4786 if (!Context
.getLangOpts().CPlusPlus
)
4789 if (isa
<CXXRecordDecl
>(Tag
->getParent())) {
4790 // If this tag is the direct child of a class, number it if
4792 if (!Tag
->getName().empty() || Tag
->getTypedefNameForAnonDecl())
4794 MangleNumberingContext
&MCtx
=
4795 Context
.getManglingNumberContext(Tag
->getParent());
4796 Context
.setManglingNumber(
4797 Tag
, MCtx
.getManglingNumber(
4798 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4802 // If this tag isn't a direct child of a class, number it if it is local.
4803 MangleNumberingContext
*MCtx
;
4804 Decl
*ManglingContextDecl
;
4805 std::tie(MCtx
, ManglingContextDecl
) =
4806 getCurrentMangleNumberContext(Tag
->getDeclContext());
4808 Context
.setManglingNumber(
4809 Tag
, MCtx
->getManglingNumber(
4810 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4815 struct NonCLikeKind
{
4827 explicit operator bool() { return Kind
!= None
; }
4831 /// Determine whether a class is C-like, according to the rules of C++
4832 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4833 static NonCLikeKind
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl
*RD
) {
4834 if (RD
->isInvalidDecl())
4835 return {NonCLikeKind::Invalid
, {}};
4837 // C++ [dcl.typedef]p9: [P1766R1]
4838 // An unnamed class with a typedef name for linkage purposes shall not
4840 // -- have any base classes
4841 if (RD
->getNumBases())
4842 return {NonCLikeKind::BaseClass
,
4843 SourceRange(RD
->bases_begin()->getBeginLoc(),
4844 RD
->bases_end()[-1].getEndLoc())};
4845 bool Invalid
= false;
4846 for (Decl
*D
: RD
->decls()) {
4847 // Don't complain about things we already diagnosed.
4848 if (D
->isInvalidDecl()) {
4853 // -- have any [...] default member initializers
4854 if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
4855 if (FD
->hasInClassInitializer()) {
4856 auto *Init
= FD
->getInClassInitializer();
4857 return {NonCLikeKind::DefaultMemberInit
,
4858 Init
? Init
->getSourceRange() : D
->getSourceRange()};
4863 // FIXME: We don't allow friend declarations. This violates the wording of
4864 // P1766, but not the intent.
4865 if (isa
<FriendDecl
>(D
))
4866 return {NonCLikeKind::Friend
, D
->getSourceRange()};
4868 // -- declare any members other than non-static data members, member
4869 // enumerations, or member classes,
4870 if (isa
<StaticAssertDecl
>(D
) || isa
<IndirectFieldDecl
>(D
) ||
4873 auto *MemberRD
= dyn_cast
<CXXRecordDecl
>(D
);
4875 if (D
->isImplicit())
4877 return {NonCLikeKind::OtherMember
, D
->getSourceRange()};
4880 // -- contain a lambda-expression,
4881 if (MemberRD
->isLambda())
4882 return {NonCLikeKind::Lambda
, MemberRD
->getSourceRange()};
4884 // and all member classes shall also satisfy these requirements
4886 if (MemberRD
->isThisDeclarationADefinition()) {
4887 if (auto Kind
= getNonCLikeKindForAnonymousStruct(MemberRD
))
4892 return {Invalid
? NonCLikeKind::Invalid
: NonCLikeKind::None
, {}};
4895 void Sema::setTagNameForLinkagePurposes(TagDecl
*TagFromDeclSpec
,
4896 TypedefNameDecl
*NewTD
) {
4897 if (TagFromDeclSpec
->isInvalidDecl())
4900 // Do nothing if the tag already has a name for linkage purposes.
4901 if (TagFromDeclSpec
->hasNameForLinkage())
4904 // A well-formed anonymous tag must always be a TUK_Definition.
4905 assert(TagFromDeclSpec
->isThisDeclarationADefinition());
4907 // The type must match the tag exactly; no qualifiers allowed.
4908 if (!Context
.hasSameType(NewTD
->getUnderlyingType(),
4909 Context
.getTagDeclType(TagFromDeclSpec
))) {
4910 if (getLangOpts().CPlusPlus
)
4911 Context
.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec
, NewTD
);
4915 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4916 // An unnamed class with a typedef name for linkage purposes shall [be
4919 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4920 // shouldn't happen, but there are constructs that the language rule doesn't
4921 // disallow for which we can't reasonably avoid computing linkage early.
4922 const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(TagFromDeclSpec
);
4923 NonCLikeKind NonCLike
= RD
? getNonCLikeKindForAnonymousStruct(RD
)
4925 bool ChangesLinkage
= TagFromDeclSpec
->hasLinkageBeenComputed();
4926 if (NonCLike
|| ChangesLinkage
) {
4927 if (NonCLike
.Kind
== NonCLikeKind::Invalid
)
4930 unsigned DiagID
= diag::ext_non_c_like_anon_struct_in_typedef
;
4931 if (ChangesLinkage
) {
4932 // If the linkage changes, we can't accept this as an extension.
4933 if (NonCLike
.Kind
== NonCLikeKind::None
)
4934 DiagID
= diag::err_typedef_changes_linkage
;
4936 DiagID
= diag::err_non_c_like_anon_struct_in_typedef
;
4939 SourceLocation FixitLoc
=
4940 getLocForEndOfToken(TagFromDeclSpec
->getInnerLocStart());
4941 llvm::SmallString
<40> TextToInsert
;
4942 TextToInsert
+= ' ';
4943 TextToInsert
+= NewTD
->getIdentifier()->getName();
4945 Diag(FixitLoc
, DiagID
)
4946 << isa
<TypeAliasDecl
>(NewTD
)
4947 << FixItHint::CreateInsertion(FixitLoc
, TextToInsert
);
4948 if (NonCLike
.Kind
!= NonCLikeKind::None
) {
4949 Diag(NonCLike
.Range
.getBegin(), diag::note_non_c_like_anon_struct
)
4950 << NonCLike
.Kind
- 1 << NonCLike
.Range
;
4952 Diag(NewTD
->getLocation(), diag::note_typedef_for_linkage_here
)
4953 << NewTD
<< isa
<TypeAliasDecl
>(NewTD
);
4959 // Otherwise, set this as the anon-decl typedef for the tag.
4960 TagFromDeclSpec
->setTypedefNameForAnonDecl(NewTD
);
4963 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T
) {
4965 case DeclSpec::TST_class
:
4967 case DeclSpec::TST_struct
:
4969 case DeclSpec::TST_interface
:
4971 case DeclSpec::TST_union
:
4973 case DeclSpec::TST_enum
:
4976 llvm_unreachable("unexpected type specifier");
4980 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4981 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4982 /// parameters to cope with template friend declarations.
4983 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
4985 const ParsedAttributesView
&DeclAttrs
,
4986 MultiTemplateParamsArg TemplateParams
,
4987 bool IsExplicitInstantiation
,
4988 RecordDecl
*&AnonRecord
) {
4989 Decl
*TagD
= nullptr;
4990 TagDecl
*Tag
= nullptr;
4991 if (DS
.getTypeSpecType() == DeclSpec::TST_class
||
4992 DS
.getTypeSpecType() == DeclSpec::TST_struct
||
4993 DS
.getTypeSpecType() == DeclSpec::TST_interface
||
4994 DS
.getTypeSpecType() == DeclSpec::TST_union
||
4995 DS
.getTypeSpecType() == DeclSpec::TST_enum
) {
4996 TagD
= DS
.getRepAsDecl();
4998 if (!TagD
) // We probably had an error
5001 // Note that the above type specs guarantee that the
5002 // type rep is a Decl, whereas in many of the others
5004 if (isa
<TagDecl
>(TagD
))
5005 Tag
= cast
<TagDecl
>(TagD
);
5006 else if (ClassTemplateDecl
*CTD
= dyn_cast
<ClassTemplateDecl
>(TagD
))
5007 Tag
= CTD
->getTemplatedDecl();
5011 handleTagNumbering(Tag
, S
);
5012 Tag
->setFreeStanding();
5013 if (Tag
->isInvalidDecl())
5017 if (unsigned TypeQuals
= DS
.getTypeQualifiers()) {
5018 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5019 // or incomplete types shall not be restrict-qualified."
5020 if (TypeQuals
& DeclSpec::TQ_restrict
)
5021 Diag(DS
.getRestrictSpecLoc(),
5022 diag::err_typecheck_invalid_restrict_not_pointer_noarg
)
5023 << DS
.getSourceRange();
5026 if (DS
.isInlineSpecified())
5027 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
5028 << getLangOpts().CPlusPlus17
;
5030 if (DS
.hasConstexprSpecifier()) {
5031 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5032 // and definitions of functions and variables.
5033 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5034 // the declaration of a function or function template
5036 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_tag
)
5037 << GetDiagnosticTypeSpecifierID(DS
.getTypeSpecType())
5038 << static_cast<int>(DS
.getConstexprSpecifier());
5040 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind
)
5041 << static_cast<int>(DS
.getConstexprSpecifier());
5042 // Don't emit warnings after this error.
5046 DiagnoseFunctionSpecifiers(DS
);
5048 if (DS
.isFriendSpecified()) {
5049 // If we're dealing with a decl but not a TagDecl, assume that
5050 // whatever routines created it handled the friendship aspect.
5053 return ActOnFriendTypeDecl(S
, DS
, TemplateParams
);
5056 const CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
5057 bool IsExplicitSpecialization
=
5058 !TemplateParams
.empty() && TemplateParams
.back()->size() == 0;
5059 if (Tag
&& SS
.isNotEmpty() && !Tag
->isCompleteDefinition() &&
5060 !IsExplicitInstantiation
&& !IsExplicitSpecialization
&&
5061 !isa
<ClassTemplatePartialSpecializationDecl
>(Tag
)) {
5062 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5063 // nested-name-specifier unless it is an explicit instantiation
5064 // or an explicit specialization.
5066 // FIXME: We allow class template partial specializations here too, per the
5067 // obvious intent of DR1819.
5069 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5070 Diag(SS
.getBeginLoc(), diag::err_standalone_class_nested_name_specifier
)
5071 << GetDiagnosticTypeSpecifierID(DS
.getTypeSpecType()) << SS
.getRange();
5075 // Track whether this decl-specifier declares anything.
5076 bool DeclaresAnything
= true;
5078 // Handle anonymous struct definitions.
5079 if (RecordDecl
*Record
= dyn_cast_or_null
<RecordDecl
>(Tag
)) {
5080 if (!Record
->getDeclName() && Record
->isCompleteDefinition() &&
5081 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
) {
5082 if (getLangOpts().CPlusPlus
||
5083 Record
->getDeclContext()->isRecord()) {
5084 // If CurContext is a DeclContext that can contain statements,
5085 // RecursiveASTVisitor won't visit the decls that
5086 // BuildAnonymousStructOrUnion() will put into CurContext.
5087 // Also store them here so that they can be part of the
5088 // DeclStmt that gets created in this case.
5089 // FIXME: Also return the IndirectFieldDecls created by
5090 // BuildAnonymousStructOr union, for the same reason?
5091 if (CurContext
->isFunctionOrMethod())
5092 AnonRecord
= Record
;
5093 return BuildAnonymousStructOrUnion(S
, DS
, AS
, Record
,
5094 Context
.getPrintingPolicy());
5097 DeclaresAnything
= false;
5102 // A struct-declaration that does not declare an anonymous structure or
5103 // anonymous union shall contain a struct-declarator-list.
5105 // This rule also existed in C89 and C99; the grammar for struct-declaration
5106 // did not permit a struct-declaration without a struct-declarator-list.
5107 if (!getLangOpts().CPlusPlus
&& CurContext
->isRecord() &&
5108 DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
) {
5109 // Check for Microsoft C extension: anonymous struct/union member.
5110 // Handle 2 kinds of anonymous struct/union:
5114 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5115 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5116 if ((Tag
&& Tag
->getDeclName()) ||
5117 DS
.getTypeSpecType() == DeclSpec::TST_typename
) {
5118 RecordDecl
*Record
= nullptr;
5120 Record
= dyn_cast
<RecordDecl
>(Tag
);
5121 else if (const RecordType
*RT
=
5122 DS
.getRepAsType().get()->getAsStructureType())
5123 Record
= RT
->getDecl();
5124 else if (const RecordType
*UT
= DS
.getRepAsType().get()->getAsUnionType())
5125 Record
= UT
->getDecl();
5127 if (Record
&& getLangOpts().MicrosoftExt
) {
5128 Diag(DS
.getBeginLoc(), diag::ext_ms_anonymous_record
)
5129 << Record
->isUnion() << DS
.getSourceRange();
5130 return BuildMicrosoftCAnonymousStruct(S
, DS
, Record
);
5133 DeclaresAnything
= false;
5137 // Skip all the checks below if we have a type error.
5138 if (DS
.getTypeSpecType() == DeclSpec::TST_error
||
5139 (TagD
&& TagD
->isInvalidDecl()))
5142 if (getLangOpts().CPlusPlus
&&
5143 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
)
5144 if (EnumDecl
*Enum
= dyn_cast_or_null
<EnumDecl
>(Tag
))
5145 if (Enum
->enumerator_begin() == Enum
->enumerator_end() &&
5146 !Enum
->getIdentifier() && !Enum
->isInvalidDecl())
5147 DeclaresAnything
= false;
5149 if (!DS
.isMissingDeclaratorOk()) {
5150 // Customize diagnostic for a typedef missing a name.
5151 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
)
5152 Diag(DS
.getBeginLoc(), diag::ext_typedef_without_a_name
)
5153 << DS
.getSourceRange();
5155 DeclaresAnything
= false;
5158 if (DS
.isModulePrivateSpecified() &&
5159 Tag
&& Tag
->getDeclContext()->isFunctionOrMethod())
5160 Diag(DS
.getModulePrivateSpecLoc(), diag::err_module_private_local_class
)
5161 << Tag
->getTagKind()
5162 << FixItHint::CreateRemoval(DS
.getModulePrivateSpecLoc());
5164 ActOnDocumentableDecl(TagD
);
5167 // A declaration [...] shall declare at least a declarator [...], a tag,
5168 // or the members of an enumeration.
5170 // [If there are no declarators], and except for the declaration of an
5171 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5172 // names into the program, or shall redeclare a name introduced by a
5173 // previous declaration.
5174 if (!DeclaresAnything
) {
5175 // In C, we allow this as a (popular) extension / bug. Don't bother
5176 // producing further diagnostics for redundant qualifiers after this.
5177 Diag(DS
.getBeginLoc(), (IsExplicitInstantiation
|| !TemplateParams
.empty())
5178 ? diag::err_no_declarators
5179 : diag::ext_no_declarators
)
5180 << DS
.getSourceRange();
5185 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5186 // init-declarator-list of the declaration shall not be empty.
5187 // C++ [dcl.fct.spec]p1:
5188 // If a cv-qualifier appears in a decl-specifier-seq, the
5189 // init-declarator-list of the declaration shall not be empty.
5191 // Spurious qualifiers here appear to be valid in C.
5192 unsigned DiagID
= diag::warn_standalone_specifier
;
5193 if (getLangOpts().CPlusPlus
)
5194 DiagID
= diag::ext_standalone_specifier
;
5196 // Note that a linkage-specification sets a storage class, but
5197 // 'extern "C" struct foo;' is actually valid and not theoretically
5199 if (DeclSpec::SCS SCS
= DS
.getStorageClassSpec()) {
5200 if (SCS
== DeclSpec::SCS_mutable
)
5201 // Since mutable is not a viable storage class specifier in C, there is
5202 // no reason to treat it as an extension. Instead, diagnose as an error.
5203 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_nonmember
);
5204 else if (!DS
.isExternInLinkageSpec() && SCS
!= DeclSpec::SCS_typedef
)
5205 Diag(DS
.getStorageClassSpecLoc(), DiagID
)
5206 << DeclSpec::getSpecifierName(SCS
);
5209 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
5210 Diag(DS
.getThreadStorageClassSpecLoc(), DiagID
)
5211 << DeclSpec::getSpecifierName(TSCS
);
5212 if (DS
.getTypeQualifiers()) {
5213 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5214 Diag(DS
.getConstSpecLoc(), DiagID
) << "const";
5215 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5216 Diag(DS
.getConstSpecLoc(), DiagID
) << "volatile";
5217 // Restrict is covered above.
5218 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5219 Diag(DS
.getAtomicSpecLoc(), DiagID
) << "_Atomic";
5220 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5221 Diag(DS
.getUnalignedSpecLoc(), DiagID
) << "__unaligned";
5224 // Warn about ignored type attributes, for example:
5225 // __attribute__((aligned)) struct A;
5226 // Attributes should be placed after tag to apply to type declaration.
5227 if (!DS
.getAttributes().empty() || !DeclAttrs
.empty()) {
5228 DeclSpec::TST TypeSpecType
= DS
.getTypeSpecType();
5229 if (TypeSpecType
== DeclSpec::TST_class
||
5230 TypeSpecType
== DeclSpec::TST_struct
||
5231 TypeSpecType
== DeclSpec::TST_interface
||
5232 TypeSpecType
== DeclSpec::TST_union
||
5233 TypeSpecType
== DeclSpec::TST_enum
) {
5234 for (const ParsedAttr
&AL
: DS
.getAttributes())
5235 Diag(AL
.getLoc(), diag::warn_declspec_attribute_ignored
)
5236 << AL
<< GetDiagnosticTypeSpecifierID(TypeSpecType
);
5237 for (const ParsedAttr
&AL
: DeclAttrs
)
5238 Diag(AL
.getLoc(), diag::warn_declspec_attribute_ignored
)
5239 << AL
<< GetDiagnosticTypeSpecifierID(TypeSpecType
);
5246 /// We are trying to inject an anonymous member into the given scope;
5247 /// check if there's an existing declaration that can't be overloaded.
5249 /// \return true if this is a forbidden redeclaration
5250 static bool CheckAnonMemberRedeclaration(Sema
&SemaRef
,
5253 DeclarationName Name
,
5254 SourceLocation NameLoc
,
5256 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupMemberName
,
5257 Sema::ForVisibleRedeclaration
);
5258 if (!SemaRef
.LookupName(R
, S
)) return false;
5260 // Pick a representative declaration.
5261 NamedDecl
*PrevDecl
= R
.getRepresentativeDecl()->getUnderlyingDecl();
5262 assert(PrevDecl
&& "Expected a non-null Decl");
5264 if (!SemaRef
.isDeclInScope(PrevDecl
, Owner
, S
))
5267 SemaRef
.Diag(NameLoc
, diag::err_anonymous_record_member_redecl
)
5269 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
5274 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5275 /// anonymous struct or union AnonRecord into the owning context Owner
5276 /// and scope S. This routine will be invoked just after we realize
5277 /// that an unnamed union or struct is actually an anonymous union or
5284 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5285 /// // f into the surrounding scope.x
5288 /// This routine is recursive, injecting the names of nested anonymous
5289 /// structs/unions into the owning context and scope as well.
5291 InjectAnonymousStructOrUnionMembers(Sema
&SemaRef
, Scope
*S
, DeclContext
*Owner
,
5292 RecordDecl
*AnonRecord
, AccessSpecifier AS
,
5293 SmallVectorImpl
<NamedDecl
*> &Chaining
) {
5294 bool Invalid
= false;
5296 // Look every FieldDecl and IndirectFieldDecl with a name.
5297 for (auto *D
: AnonRecord
->decls()) {
5298 if ((isa
<FieldDecl
>(D
) || isa
<IndirectFieldDecl
>(D
)) &&
5299 cast
<NamedDecl
>(D
)->getDeclName()) {
5300 ValueDecl
*VD
= cast
<ValueDecl
>(D
);
5301 if (CheckAnonMemberRedeclaration(SemaRef
, S
, Owner
, VD
->getDeclName(),
5303 AnonRecord
->isUnion())) {
5304 // C++ [class.union]p2:
5305 // The names of the members of an anonymous union shall be
5306 // distinct from the names of any other entity in the
5307 // scope in which the anonymous union is declared.
5310 // C++ [class.union]p2:
5311 // For the purpose of name lookup, after the anonymous union
5312 // definition, the members of the anonymous union are
5313 // considered to have been defined in the scope in which the
5314 // anonymous union is declared.
5315 unsigned OldChainingSize
= Chaining
.size();
5316 if (IndirectFieldDecl
*IF
= dyn_cast
<IndirectFieldDecl
>(VD
))
5317 Chaining
.append(IF
->chain_begin(), IF
->chain_end());
5319 Chaining
.push_back(VD
);
5321 assert(Chaining
.size() >= 2);
5322 NamedDecl
**NamedChain
=
5323 new (SemaRef
.Context
)NamedDecl
*[Chaining
.size()];
5324 for (unsigned i
= 0; i
< Chaining
.size(); i
++)
5325 NamedChain
[i
] = Chaining
[i
];
5327 IndirectFieldDecl
*IndirectField
= IndirectFieldDecl::Create(
5328 SemaRef
.Context
, Owner
, VD
->getLocation(), VD
->getIdentifier(),
5329 VD
->getType(), {NamedChain
, Chaining
.size()});
5331 for (const auto *Attr
: VD
->attrs())
5332 IndirectField
->addAttr(Attr
->clone(SemaRef
.Context
));
5334 IndirectField
->setAccess(AS
);
5335 IndirectField
->setImplicit();
5336 SemaRef
.PushOnScopeChains(IndirectField
, S
);
5338 // That includes picking up the appropriate access specifier.
5339 if (AS
!= AS_none
) IndirectField
->setAccess(AS
);
5341 Chaining
.resize(OldChainingSize
);
5349 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5350 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5351 /// illegal input values are mapped to SC_None.
5353 StorageClassSpecToVarDeclStorageClass(const DeclSpec
&DS
) {
5354 DeclSpec::SCS StorageClassSpec
= DS
.getStorageClassSpec();
5355 assert(StorageClassSpec
!= DeclSpec::SCS_typedef
&&
5356 "Parser allowed 'typedef' as storage class VarDecl.");
5357 switch (StorageClassSpec
) {
5358 case DeclSpec::SCS_unspecified
: return SC_None
;
5359 case DeclSpec::SCS_extern
:
5360 if (DS
.isExternInLinkageSpec())
5363 case DeclSpec::SCS_static
: return SC_Static
;
5364 case DeclSpec::SCS_auto
: return SC_Auto
;
5365 case DeclSpec::SCS_register
: return SC_Register
;
5366 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
5367 // Illegal SCSs map to None: error reporting is up to the caller.
5368 case DeclSpec::SCS_mutable
: // Fall through.
5369 case DeclSpec::SCS_typedef
: return SC_None
;
5371 llvm_unreachable("unknown storage class specifier");
5374 static SourceLocation
findDefaultInitializer(const CXXRecordDecl
*Record
) {
5375 assert(Record
->hasInClassInitializer());
5377 for (const auto *I
: Record
->decls()) {
5378 const auto *FD
= dyn_cast
<FieldDecl
>(I
);
5379 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
5380 FD
= IFD
->getAnonField();
5381 if (FD
&& FD
->hasInClassInitializer())
5382 return FD
->getLocation();
5385 llvm_unreachable("couldn't find in-class initializer");
5388 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5389 SourceLocation DefaultInitLoc
) {
5390 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5393 S
.Diag(DefaultInitLoc
, diag::err_multiple_mem_union_initialization
);
5394 S
.Diag(findDefaultInitializer(Parent
), diag::note_previous_initializer
) << 0;
5397 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5398 CXXRecordDecl
*AnonUnion
) {
5399 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5402 checkDuplicateDefaultInit(S
, Parent
, findDefaultInitializer(AnonUnion
));
5405 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5406 /// anonymous structure or union. Anonymous unions are a C++ feature
5407 /// (C++ [class.union]) and a C11 feature; anonymous structures
5408 /// are a C11 feature and GNU C++ extension.
5409 Decl
*Sema::BuildAnonymousStructOrUnion(Scope
*S
, DeclSpec
&DS
,
5412 const PrintingPolicy
&Policy
) {
5413 DeclContext
*Owner
= Record
->getDeclContext();
5415 // Diagnose whether this anonymous struct/union is an extension.
5416 if (Record
->isUnion() && !getLangOpts().CPlusPlus
&& !getLangOpts().C11
)
5417 Diag(Record
->getLocation(), diag::ext_anonymous_union
);
5418 else if (!Record
->isUnion() && getLangOpts().CPlusPlus
)
5419 Diag(Record
->getLocation(), diag::ext_gnu_anonymous_struct
);
5420 else if (!Record
->isUnion() && !getLangOpts().C11
)
5421 Diag(Record
->getLocation(), diag::ext_c11_anonymous_struct
);
5423 // C and C++ require different kinds of checks for anonymous
5425 bool Invalid
= false;
5426 if (getLangOpts().CPlusPlus
) {
5427 const char *PrevSpec
= nullptr;
5428 if (Record
->isUnion()) {
5429 // C++ [class.union]p6:
5430 // C++17 [class.union.anon]p2:
5431 // Anonymous unions declared in a named namespace or in the
5432 // global namespace shall be declared static.
5434 DeclContext
*OwnerScope
= Owner
->getRedeclContext();
5435 if (DS
.getStorageClassSpec() != DeclSpec::SCS_static
&&
5436 (OwnerScope
->isTranslationUnit() ||
5437 (OwnerScope
->isNamespace() &&
5438 !cast
<NamespaceDecl
>(OwnerScope
)->isAnonymousNamespace()))) {
5439 Diag(Record
->getLocation(), diag::err_anonymous_union_not_static
)
5440 << FixItHint::CreateInsertion(Record
->getLocation(), "static ");
5442 // Recover by adding 'static'.
5443 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_static
, SourceLocation(),
5444 PrevSpec
, DiagID
, Policy
);
5446 // C++ [class.union]p6:
5447 // A storage class is not allowed in a declaration of an
5448 // anonymous union in a class scope.
5449 else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
&&
5450 isa
<RecordDecl
>(Owner
)) {
5451 Diag(DS
.getStorageClassSpecLoc(),
5452 diag::err_anonymous_union_with_storage_spec
)
5453 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
5455 // Recover by removing the storage specifier.
5456 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified
,
5458 PrevSpec
, DiagID
, Context
.getPrintingPolicy());
5462 // Ignore const/volatile/restrict qualifiers.
5463 if (DS
.getTypeQualifiers()) {
5464 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5465 Diag(DS
.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified
)
5466 << Record
->isUnion() << "const"
5467 << FixItHint::CreateRemoval(DS
.getConstSpecLoc());
5468 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5469 Diag(DS
.getVolatileSpecLoc(),
5470 diag::ext_anonymous_struct_union_qualified
)
5471 << Record
->isUnion() << "volatile"
5472 << FixItHint::CreateRemoval(DS
.getVolatileSpecLoc());
5473 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
5474 Diag(DS
.getRestrictSpecLoc(),
5475 diag::ext_anonymous_struct_union_qualified
)
5476 << Record
->isUnion() << "restrict"
5477 << FixItHint::CreateRemoval(DS
.getRestrictSpecLoc());
5478 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5479 Diag(DS
.getAtomicSpecLoc(),
5480 diag::ext_anonymous_struct_union_qualified
)
5481 << Record
->isUnion() << "_Atomic"
5482 << FixItHint::CreateRemoval(DS
.getAtomicSpecLoc());
5483 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5484 Diag(DS
.getUnalignedSpecLoc(),
5485 diag::ext_anonymous_struct_union_qualified
)
5486 << Record
->isUnion() << "__unaligned"
5487 << FixItHint::CreateRemoval(DS
.getUnalignedSpecLoc());
5489 DS
.ClearTypeQualifiers();
5492 // C++ [class.union]p2:
5493 // The member-specification of an anonymous union shall only
5494 // define non-static data members. [Note: nested types and
5495 // functions cannot be declared within an anonymous union. ]
5496 for (auto *Mem
: Record
->decls()) {
5497 // Ignore invalid declarations; we already diagnosed them.
5498 if (Mem
->isInvalidDecl())
5501 if (auto *FD
= dyn_cast
<FieldDecl
>(Mem
)) {
5502 // C++ [class.union]p3:
5503 // An anonymous union shall not have private or protected
5504 // members (clause 11).
5505 assert(FD
->getAccess() != AS_none
);
5506 if (FD
->getAccess() != AS_public
) {
5507 Diag(FD
->getLocation(), diag::err_anonymous_record_nonpublic_member
)
5508 << Record
->isUnion() << (FD
->getAccess() == AS_protected
);
5512 // C++ [class.union]p1
5513 // An object of a class with a non-trivial constructor, a non-trivial
5514 // copy constructor, a non-trivial destructor, or a non-trivial copy
5515 // assignment operator cannot be a member of a union, nor can an
5516 // array of such objects.
5517 if (CheckNontrivialField(FD
))
5519 } else if (Mem
->isImplicit()) {
5520 // Any implicit members are fine.
5521 } else if (isa
<TagDecl
>(Mem
) && Mem
->getDeclContext() != Record
) {
5522 // This is a type that showed up in an
5523 // elaborated-type-specifier inside the anonymous struct or
5524 // union, but which actually declares a type outside of the
5525 // anonymous struct or union. It's okay.
5526 } else if (auto *MemRecord
= dyn_cast
<RecordDecl
>(Mem
)) {
5527 if (!MemRecord
->isAnonymousStructOrUnion() &&
5528 MemRecord
->getDeclName()) {
5529 // Visual C++ allows type definition in anonymous struct or union.
5530 if (getLangOpts().MicrosoftExt
)
5531 Diag(MemRecord
->getLocation(), diag::ext_anonymous_record_with_type
)
5532 << Record
->isUnion();
5534 // This is a nested type declaration.
5535 Diag(MemRecord
->getLocation(), diag::err_anonymous_record_with_type
)
5536 << Record
->isUnion();
5540 // This is an anonymous type definition within another anonymous type.
5541 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5542 // not part of standard C++.
5543 Diag(MemRecord
->getLocation(),
5544 diag::ext_anonymous_record_with_anonymous_type
)
5545 << Record
->isUnion();
5547 } else if (isa
<AccessSpecDecl
>(Mem
)) {
5548 // Any access specifier is fine.
5549 } else if (isa
<StaticAssertDecl
>(Mem
)) {
5550 // In C++1z, static_assert declarations are also fine.
5552 // We have something that isn't a non-static data
5553 // member. Complain about it.
5554 unsigned DK
= diag::err_anonymous_record_bad_member
;
5555 if (isa
<TypeDecl
>(Mem
))
5556 DK
= diag::err_anonymous_record_with_type
;
5557 else if (isa
<FunctionDecl
>(Mem
))
5558 DK
= diag::err_anonymous_record_with_function
;
5559 else if (isa
<VarDecl
>(Mem
))
5560 DK
= diag::err_anonymous_record_with_static
;
5562 // Visual C++ allows type definition in anonymous struct or union.
5563 if (getLangOpts().MicrosoftExt
&&
5564 DK
== diag::err_anonymous_record_with_type
)
5565 Diag(Mem
->getLocation(), diag::ext_anonymous_record_with_type
)
5566 << Record
->isUnion();
5568 Diag(Mem
->getLocation(), DK
) << Record
->isUnion();
5574 // C++11 [class.union]p8 (DR1460):
5575 // At most one variant member of a union may have a
5576 // brace-or-equal-initializer.
5577 if (cast
<CXXRecordDecl
>(Record
)->hasInClassInitializer() &&
5579 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Owner
),
5580 cast
<CXXRecordDecl
>(Record
));
5583 if (!Record
->isUnion() && !Owner
->isRecord()) {
5584 Diag(Record
->getLocation(), diag::err_anonymous_struct_not_member
)
5585 << getLangOpts().CPlusPlus
;
5590 // [If there are no declarators], and except for the declaration of an
5591 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5592 // names into the program
5593 // C++ [class.mem]p2:
5594 // each such member-declaration shall either declare at least one member
5595 // name of the class or declare at least one unnamed bit-field
5597 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5598 if (getLangOpts().CPlusPlus
&& Record
->field_empty())
5599 Diag(DS
.getBeginLoc(), diag::ext_no_declarators
) << DS
.getSourceRange();
5601 // Mock up a declarator.
5602 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::Member
);
5603 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5604 assert(TInfo
&& "couldn't build declarator info for anonymous struct/union");
5606 // Create a declaration for this anonymous struct/union.
5607 NamedDecl
*Anon
= nullptr;
5608 if (RecordDecl
*OwningClass
= dyn_cast
<RecordDecl
>(Owner
)) {
5609 Anon
= FieldDecl::Create(
5610 Context
, OwningClass
, DS
.getBeginLoc(), Record
->getLocation(),
5611 /*IdentifierInfo=*/nullptr, Context
.getTypeDeclType(Record
), TInfo
,
5612 /*BitWidth=*/nullptr, /*Mutable=*/false,
5613 /*InitStyle=*/ICIS_NoInit
);
5614 Anon
->setAccess(AS
);
5615 ProcessDeclAttributes(S
, Anon
, Dc
);
5617 if (getLangOpts().CPlusPlus
)
5618 FieldCollector
->Add(cast
<FieldDecl
>(Anon
));
5620 DeclSpec::SCS SCSpec
= DS
.getStorageClassSpec();
5621 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(DS
);
5622 if (SCSpec
== DeclSpec::SCS_mutable
) {
5623 // mutable can only appear on non-static class members, so it's always
5625 Diag(Record
->getLocation(), diag::err_mutable_nonmember
);
5630 assert(DS
.getAttributes().empty() && "No attribute expected");
5631 Anon
= VarDecl::Create(Context
, Owner
, DS
.getBeginLoc(),
5632 Record
->getLocation(), /*IdentifierInfo=*/nullptr,
5633 Context
.getTypeDeclType(Record
), TInfo
, SC
);
5635 // Default-initialize the implicit variable. This initialization will be
5636 // trivial in almost all cases, except if a union member has an in-class
5638 // union { int n = 0; };
5639 ActOnUninitializedDecl(Anon
);
5641 Anon
->setImplicit();
5643 // Mark this as an anonymous struct/union type.
5644 Record
->setAnonymousStructOrUnion(true);
5646 // Add the anonymous struct/union object to the current
5647 // context. We'll be referencing this object when we refer to one of
5649 Owner
->addDecl(Anon
);
5651 // Inject the members of the anonymous struct/union into the owning
5652 // context and into the identifier resolver chain for name lookup
5654 SmallVector
<NamedDecl
*, 2> Chain
;
5655 Chain
.push_back(Anon
);
5657 if (InjectAnonymousStructOrUnionMembers(*this, S
, Owner
, Record
, AS
, Chain
))
5660 if (VarDecl
*NewVD
= dyn_cast
<VarDecl
>(Anon
)) {
5661 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
5662 MangleNumberingContext
*MCtx
;
5663 Decl
*ManglingContextDecl
;
5664 std::tie(MCtx
, ManglingContextDecl
) =
5665 getCurrentMangleNumberContext(NewVD
->getDeclContext());
5667 Context
.setManglingNumber(
5668 NewVD
, MCtx
->getManglingNumber(
5669 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
5670 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
5676 Anon
->setInvalidDecl();
5681 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5682 /// Microsoft C anonymous structure.
5683 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5686 /// struct A { int a; };
5687 /// struct B { struct A; int b; };
5694 Decl
*Sema::BuildMicrosoftCAnonymousStruct(Scope
*S
, DeclSpec
&DS
,
5695 RecordDecl
*Record
) {
5696 assert(Record
&& "expected a record!");
5698 // Mock up a declarator.
5699 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::TypeName
);
5700 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5701 assert(TInfo
&& "couldn't build declarator info for anonymous struct");
5703 auto *ParentDecl
= cast
<RecordDecl
>(CurContext
);
5704 QualType RecTy
= Context
.getTypeDeclType(Record
);
5706 // Create a declaration for this anonymous struct.
5708 FieldDecl::Create(Context
, ParentDecl
, DS
.getBeginLoc(), DS
.getBeginLoc(),
5709 /*IdentifierInfo=*/nullptr, RecTy
, TInfo
,
5710 /*BitWidth=*/nullptr, /*Mutable=*/false,
5711 /*InitStyle=*/ICIS_NoInit
);
5712 Anon
->setImplicit();
5714 // Add the anonymous struct object to the current context.
5715 CurContext
->addDecl(Anon
);
5717 // Inject the members of the anonymous struct into the current
5718 // context and into the identifier resolver chain for name lookup
5720 SmallVector
<NamedDecl
*, 2> Chain
;
5721 Chain
.push_back(Anon
);
5723 RecordDecl
*RecordDef
= Record
->getDefinition();
5724 if (RequireCompleteSizedType(Anon
->getLocation(), RecTy
,
5725 diag::err_field_incomplete_or_sizeless
) ||
5726 InjectAnonymousStructOrUnionMembers(*this, S
, CurContext
, RecordDef
,
5728 Anon
->setInvalidDecl();
5729 ParentDecl
->setInvalidDecl();
5735 /// GetNameForDeclarator - Determine the full declaration name for the
5736 /// given Declarator.
5737 DeclarationNameInfo
Sema::GetNameForDeclarator(Declarator
&D
) {
5738 return GetNameFromUnqualifiedId(D
.getName());
5741 /// Retrieves the declaration name from a parsed unqualified-id.
5743 Sema::GetNameFromUnqualifiedId(const UnqualifiedId
&Name
) {
5744 DeclarationNameInfo NameInfo
;
5745 NameInfo
.setLoc(Name
.StartLocation
);
5747 switch (Name
.getKind()) {
5749 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
5750 case UnqualifiedIdKind::IK_Identifier
:
5751 NameInfo
.setName(Name
.Identifier
);
5754 case UnqualifiedIdKind::IK_DeductionGuideName
: {
5755 // C++ [temp.deduct.guide]p3:
5756 // The simple-template-id shall name a class template specialization.
5757 // The template-name shall be the same identifier as the template-name
5758 // of the simple-template-id.
5759 // These together intend to imply that the template-name shall name a
5761 // FIXME: template<typename T> struct X {};
5762 // template<typename T> using Y = X<T>;
5763 // Y(int) -> Y<int>;
5764 // satisfies these rules but does not name a class template.
5765 TemplateName TN
= Name
.TemplateName
.get().get();
5766 auto *Template
= TN
.getAsTemplateDecl();
5767 if (!Template
|| !isa
<ClassTemplateDecl
>(Template
)) {
5768 Diag(Name
.StartLocation
,
5769 diag::err_deduction_guide_name_not_class_template
)
5770 << (int)getTemplateNameKindForDiagnostics(TN
) << TN
;
5772 Diag(Template
->getLocation(), diag::note_template_decl_here
);
5773 return DeclarationNameInfo();
5777 Context
.DeclarationNames
.getCXXDeductionGuideName(Template
));
5781 case UnqualifiedIdKind::IK_OperatorFunctionId
:
5782 NameInfo
.setName(Context
.DeclarationNames
.getCXXOperatorName(
5783 Name
.OperatorFunctionId
.Operator
));
5784 NameInfo
.setCXXOperatorNameRange(SourceRange(
5785 Name
.OperatorFunctionId
.SymbolLocations
[0], Name
.EndLocation
));
5788 case UnqualifiedIdKind::IK_LiteralOperatorId
:
5789 NameInfo
.setName(Context
.DeclarationNames
.getCXXLiteralOperatorName(
5791 NameInfo
.setCXXLiteralOperatorNameLoc(Name
.EndLocation
);
5794 case UnqualifiedIdKind::IK_ConversionFunctionId
: {
5795 TypeSourceInfo
*TInfo
;
5796 QualType Ty
= GetTypeFromParser(Name
.ConversionFunctionId
, &TInfo
);
5798 return DeclarationNameInfo();
5799 NameInfo
.setName(Context
.DeclarationNames
.getCXXConversionFunctionName(
5800 Context
.getCanonicalType(Ty
)));
5801 NameInfo
.setNamedTypeInfo(TInfo
);
5805 case UnqualifiedIdKind::IK_ConstructorName
: {
5806 TypeSourceInfo
*TInfo
;
5807 QualType Ty
= GetTypeFromParser(Name
.ConstructorName
, &TInfo
);
5809 return DeclarationNameInfo();
5810 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5811 Context
.getCanonicalType(Ty
)));
5812 NameInfo
.setNamedTypeInfo(TInfo
);
5816 case UnqualifiedIdKind::IK_ConstructorTemplateId
: {
5817 // In well-formed code, we can only have a constructor
5818 // template-id that refers to the current context, so go there
5819 // to find the actual type being constructed.
5820 CXXRecordDecl
*CurClass
= dyn_cast
<CXXRecordDecl
>(CurContext
);
5821 if (!CurClass
|| CurClass
->getIdentifier() != Name
.TemplateId
->Name
)
5822 return DeclarationNameInfo();
5824 // Determine the type of the class being constructed.
5825 QualType CurClassType
= Context
.getTypeDeclType(CurClass
);
5827 // FIXME: Check two things: that the template-id names the same type as
5828 // CurClassType, and that the template-id does not occur when the name
5831 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5832 Context
.getCanonicalType(CurClassType
)));
5833 // FIXME: should we retrieve TypeSourceInfo?
5834 NameInfo
.setNamedTypeInfo(nullptr);
5838 case UnqualifiedIdKind::IK_DestructorName
: {
5839 TypeSourceInfo
*TInfo
;
5840 QualType Ty
= GetTypeFromParser(Name
.DestructorName
, &TInfo
);
5842 return DeclarationNameInfo();
5843 NameInfo
.setName(Context
.DeclarationNames
.getCXXDestructorName(
5844 Context
.getCanonicalType(Ty
)));
5845 NameInfo
.setNamedTypeInfo(TInfo
);
5849 case UnqualifiedIdKind::IK_TemplateId
: {
5850 TemplateName TName
= Name
.TemplateId
->Template
.get();
5851 SourceLocation TNameLoc
= Name
.TemplateId
->TemplateNameLoc
;
5852 return Context
.getNameForTemplate(TName
, TNameLoc
);
5855 } // switch (Name.getKind())
5857 llvm_unreachable("Unknown name kind");
5860 static QualType
getCoreType(QualType Ty
) {
5862 if (Ty
->isPointerType() || Ty
->isReferenceType())
5863 Ty
= Ty
->getPointeeType();
5864 else if (Ty
->isArrayType())
5865 Ty
= Ty
->castAsArrayTypeUnsafe()->getElementType();
5867 return Ty
.withoutLocalFastQualifiers();
5871 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5872 /// and Definition have "nearly" matching parameters. This heuristic is
5873 /// used to improve diagnostics in the case where an out-of-line function
5874 /// definition doesn't match any declaration within the class or namespace.
5875 /// Also sets Params to the list of indices to the parameters that differ
5876 /// between the declaration and the definition. If hasSimilarParameters
5877 /// returns true and Params is empty, then all of the parameters match.
5878 static bool hasSimilarParameters(ASTContext
&Context
,
5879 FunctionDecl
*Declaration
,
5880 FunctionDecl
*Definition
,
5881 SmallVectorImpl
<unsigned> &Params
) {
5883 if (Declaration
->param_size() != Definition
->param_size())
5885 for (unsigned Idx
= 0; Idx
< Declaration
->param_size(); ++Idx
) {
5886 QualType DeclParamTy
= Declaration
->getParamDecl(Idx
)->getType();
5887 QualType DefParamTy
= Definition
->getParamDecl(Idx
)->getType();
5889 // The parameter types are identical
5890 if (Context
.hasSameUnqualifiedType(DefParamTy
, DeclParamTy
))
5893 QualType DeclParamBaseTy
= getCoreType(DeclParamTy
);
5894 QualType DefParamBaseTy
= getCoreType(DefParamTy
);
5895 const IdentifierInfo
*DeclTyName
= DeclParamBaseTy
.getBaseTypeIdentifier();
5896 const IdentifierInfo
*DefTyName
= DefParamBaseTy
.getBaseTypeIdentifier();
5898 if (Context
.hasSameUnqualifiedType(DeclParamBaseTy
, DefParamBaseTy
) ||
5899 (DeclTyName
&& DeclTyName
== DefTyName
))
5900 Params
.push_back(Idx
);
5901 else // The two parameters aren't even close
5908 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5909 /// declarator needs to be rebuilt in the current instantiation.
5910 /// Any bits of declarator which appear before the name are valid for
5911 /// consideration here. That's specifically the type in the decl spec
5912 /// and the base type in any member-pointer chunks.
5913 static bool RebuildDeclaratorInCurrentInstantiation(Sema
&S
, Declarator
&D
,
5914 DeclarationName Name
) {
5915 // The types we specifically need to rebuild are:
5916 // - typenames, typeofs, and decltypes
5917 // - types which will become injected class names
5918 // Of course, we also need to rebuild any type referencing such a
5919 // type. It's safest to just say "dependent", but we call out a
5922 DeclSpec
&DS
= D
.getMutableDeclSpec();
5923 switch (DS
.getTypeSpecType()) {
5924 case DeclSpec::TST_typename
:
5925 case DeclSpec::TST_typeofType
:
5926 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5927 #include "clang/Basic/TransformTypeTraits.def"
5928 case DeclSpec::TST_atomic
: {
5929 // Grab the type from the parser.
5930 TypeSourceInfo
*TSI
= nullptr;
5931 QualType T
= S
.GetTypeFromParser(DS
.getRepAsType(), &TSI
);
5932 if (T
.isNull() || !T
->isInstantiationDependentType()) break;
5934 // Make sure there's a type source info. This isn't really much
5935 // of a waste; most dependent types should have type source info
5936 // attached already.
5938 TSI
= S
.Context
.getTrivialTypeSourceInfo(T
, DS
.getTypeSpecTypeLoc());
5940 // Rebuild the type in the current instantiation.
5941 TSI
= S
.RebuildTypeInCurrentInstantiation(TSI
, D
.getIdentifierLoc(), Name
);
5942 if (!TSI
) return true;
5944 // Store the new type back in the decl spec.
5945 ParsedType LocType
= S
.CreateParsedType(TSI
->getType(), TSI
);
5946 DS
.UpdateTypeRep(LocType
);
5950 case DeclSpec::TST_decltype
:
5951 case DeclSpec::TST_typeofExpr
: {
5952 Expr
*E
= DS
.getRepAsExpr();
5953 ExprResult Result
= S
.RebuildExprInCurrentInstantiation(E
);
5954 if (Result
.isInvalid()) return true;
5955 DS
.UpdateExprRep(Result
.get());
5960 // Nothing to do for these decl specs.
5964 // It doesn't matter what order we do this in.
5965 for (unsigned I
= 0, E
= D
.getNumTypeObjects(); I
!= E
; ++I
) {
5966 DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
5968 // The only type information in the declarator which can come
5969 // before the declaration name is the base type of a member
5971 if (Chunk
.Kind
!= DeclaratorChunk::MemberPointer
)
5974 // Rebuild the scope specifier in-place.
5975 CXXScopeSpec
&SS
= Chunk
.Mem
.Scope();
5976 if (S
.RebuildNestedNameSpecifierInCurrentInstantiation(SS
))
5983 /// Returns true if the declaration is declared in a system header or from a
5985 static bool isFromSystemHeader(SourceManager
&SM
, const Decl
*D
) {
5986 return SM
.isInSystemHeader(D
->getLocation()) ||
5987 SM
.isInSystemMacro(D
->getLocation());
5990 void Sema::warnOnReservedIdentifier(const NamedDecl
*D
) {
5991 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5993 if (D
->getPreviousDecl() || D
->isImplicit())
5995 ReservedIdentifierStatus Status
= D
->isReserved(getLangOpts());
5996 if (Status
!= ReservedIdentifierStatus::NotReserved
&&
5997 !isFromSystemHeader(Context
.getSourceManager(), D
)) {
5998 Diag(D
->getLocation(), diag::warn_reserved_extern_symbol
)
5999 << D
<< static_cast<int>(Status
);
6003 Decl
*Sema::ActOnDeclarator(Scope
*S
, Declarator
&D
) {
6004 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration
);
6006 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6007 // declaration only if the `bind_to_declaration` extension is set.
6008 SmallVector
<FunctionDecl
*, 4> Bases
;
6009 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
6010 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6011 implementation_extension_bind_to_declaration
))
6012 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6013 S
, D
, MultiTemplateParamsArg(), Bases
);
6015 Decl
*Dcl
= HandleDeclarator(S
, D
, MultiTemplateParamsArg());
6017 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer() &&
6018 Dcl
&& Dcl
->getDeclContext()->isFileContext())
6019 Dcl
->setTopLevelDeclInObjCContainer();
6022 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
6027 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6028 /// If T is the name of a class, then each of the following shall have a
6029 /// name different from T:
6030 /// - every static data member of class T;
6031 /// - every member function of class T
6032 /// - every member of class T that is itself a type;
6033 /// \returns true if the declaration name violates these rules.
6034 bool Sema::DiagnoseClassNameShadow(DeclContext
*DC
,
6035 DeclarationNameInfo NameInfo
) {
6036 DeclarationName Name
= NameInfo
.getName();
6038 CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
);
6039 while (Record
&& Record
->isAnonymousStructOrUnion())
6040 Record
= dyn_cast
<CXXRecordDecl
>(Record
->getParent());
6041 if (Record
&& Record
->getIdentifier() && Record
->getDeclName() == Name
) {
6042 Diag(NameInfo
.getLoc(), diag::err_member_name_of_class
) << Name
;
6049 /// Diagnose a declaration whose declarator-id has the given
6050 /// nested-name-specifier.
6052 /// \param SS The nested-name-specifier of the declarator-id.
6054 /// \param DC The declaration context to which the nested-name-specifier
6057 /// \param Name The name of the entity being declared.
6059 /// \param Loc The location of the name of the entity being declared.
6061 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6062 /// we're declaring an explicit / partial specialization / instantiation.
6064 /// \returns true if we cannot safely recover from this error, false otherwise.
6065 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec
&SS
, DeclContext
*DC
,
6066 DeclarationName Name
,
6067 SourceLocation Loc
, bool IsTemplateId
) {
6068 DeclContext
*Cur
= CurContext
;
6069 while (isa
<LinkageSpecDecl
>(Cur
) || isa
<CapturedDecl
>(Cur
))
6070 Cur
= Cur
->getParent();
6072 // If the user provided a superfluous scope specifier that refers back to the
6073 // class in which the entity is already declared, diagnose and ignore it.
6079 // Note, it was once ill-formed to give redundant qualification in all
6080 // contexts, but that rule was removed by DR482.
6081 if (Cur
->Equals(DC
)) {
6082 if (Cur
->isRecord()) {
6083 Diag(Loc
, LangOpts
.MicrosoftExt
? diag::warn_member_extra_qualification
6084 : diag::err_member_extra_qualification
)
6085 << Name
<< FixItHint::CreateRemoval(SS
.getRange());
6088 Diag(Loc
, diag::warn_namespace_member_extra_qualification
) << Name
;
6093 // Check whether the qualifying scope encloses the scope of the original
6094 // declaration. For a template-id, we perform the checks in
6095 // CheckTemplateSpecializationScope.
6096 if (!Cur
->Encloses(DC
) && !IsTemplateId
) {
6097 if (Cur
->isRecord())
6098 Diag(Loc
, diag::err_member_qualification
)
6099 << Name
<< SS
.getRange();
6100 else if (isa
<TranslationUnitDecl
>(DC
))
6101 Diag(Loc
, diag::err_invalid_declarator_global_scope
)
6102 << Name
<< SS
.getRange();
6103 else if (isa
<FunctionDecl
>(Cur
))
6104 Diag(Loc
, diag::err_invalid_declarator_in_function
)
6105 << Name
<< SS
.getRange();
6106 else if (isa
<BlockDecl
>(Cur
))
6107 Diag(Loc
, diag::err_invalid_declarator_in_block
)
6108 << Name
<< SS
.getRange();
6109 else if (isa
<ExportDecl
>(Cur
)) {
6110 if (!isa
<NamespaceDecl
>(DC
))
6111 Diag(Loc
, diag::err_export_non_namespace_scope_name
)
6112 << Name
<< SS
.getRange();
6114 // The cases that DC is not NamespaceDecl should be handled in
6115 // CheckRedeclarationExported.
6118 Diag(Loc
, diag::err_invalid_declarator_scope
)
6119 << Name
<< cast
<NamedDecl
>(Cur
) << cast
<NamedDecl
>(DC
) << SS
.getRange();
6124 if (Cur
->isRecord()) {
6125 // Cannot qualify members within a class.
6126 Diag(Loc
, diag::err_member_qualification
)
6127 << Name
<< SS
.getRange();
6130 // C++ constructors and destructors with incorrect scopes can break
6131 // our AST invariants by having the wrong underlying types. If
6132 // that's the case, then drop this declaration entirely.
6133 if ((Name
.getNameKind() == DeclarationName::CXXConstructorName
||
6134 Name
.getNameKind() == DeclarationName::CXXDestructorName
) &&
6135 !Context
.hasSameType(Name
.getCXXNameType(),
6136 Context
.getTypeDeclType(cast
<CXXRecordDecl
>(Cur
))))
6142 // C++11 [dcl.meaning]p1:
6143 // [...] "The nested-name-specifier of the qualified declarator-id shall
6144 // not begin with a decltype-specifer"
6145 NestedNameSpecifierLoc
SpecLoc(SS
.getScopeRep(), SS
.location_data());
6146 while (SpecLoc
.getPrefix())
6147 SpecLoc
= SpecLoc
.getPrefix();
6148 if (isa_and_nonnull
<DecltypeType
>(
6149 SpecLoc
.getNestedNameSpecifier()->getAsType()))
6150 Diag(Loc
, diag::err_decltype_in_declarator
)
6151 << SpecLoc
.getTypeLoc().getSourceRange();
6156 NamedDecl
*Sema::HandleDeclarator(Scope
*S
, Declarator
&D
,
6157 MultiTemplateParamsArg TemplateParamLists
) {
6158 // TODO: consider using NameInfo for diagnostic.
6159 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
6160 DeclarationName Name
= NameInfo
.getName();
6162 // All of these full declarators require an identifier. If it doesn't have
6163 // one, the ParsedFreeStandingDeclSpec action should be used.
6164 if (D
.isDecompositionDeclarator()) {
6165 return ActOnDecompositionDeclarator(S
, D
, TemplateParamLists
);
6167 if (!D
.isInvalidType()) // Reject this if we think it is valid.
6168 Diag(D
.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident
)
6169 << D
.getDeclSpec().getSourceRange() << D
.getSourceRange();
6171 } else if (DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_DeclarationType
))
6174 // The scope passed in may not be a decl scope. Zip up the scope tree until
6175 // we find one that is.
6176 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
6177 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
6180 DeclContext
*DC
= CurContext
;
6181 if (D
.getCXXScopeSpec().isInvalid())
6183 else if (D
.getCXXScopeSpec().isSet()) {
6184 if (DiagnoseUnexpandedParameterPack(D
.getCXXScopeSpec(),
6185 UPPC_DeclarationQualifier
))
6188 bool EnteringContext
= !D
.getDeclSpec().isFriendSpecified();
6189 DC
= computeDeclContext(D
.getCXXScopeSpec(), EnteringContext
);
6190 if (!DC
|| isa
<EnumDecl
>(DC
)) {
6191 // If we could not compute the declaration context, it's because the
6192 // declaration context is dependent but does not refer to a class,
6193 // class template, or class template partial specialization. Complain
6194 // and return early, to avoid the coming semantic disaster.
6195 Diag(D
.getIdentifierLoc(),
6196 diag::err_template_qualified_declarator_no_match
)
6197 << D
.getCXXScopeSpec().getScopeRep()
6198 << D
.getCXXScopeSpec().getRange();
6201 bool IsDependentContext
= DC
->isDependentContext();
6203 if (!IsDependentContext
&&
6204 RequireCompleteDeclContext(D
.getCXXScopeSpec(), DC
))
6207 // If a class is incomplete, do not parse entities inside it.
6208 if (isa
<CXXRecordDecl
>(DC
) && !cast
<CXXRecordDecl
>(DC
)->hasDefinition()) {
6209 Diag(D
.getIdentifierLoc(),
6210 diag::err_member_def_undefined_record
)
6211 << Name
<< DC
<< D
.getCXXScopeSpec().getRange();
6214 if (!D
.getDeclSpec().isFriendSpecified()) {
6215 if (diagnoseQualifiedDeclaration(
6216 D
.getCXXScopeSpec(), DC
, Name
, D
.getIdentifierLoc(),
6217 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
)) {
6225 // Check whether we need to rebuild the type of the given
6226 // declaration in the current instantiation.
6227 if (EnteringContext
&& IsDependentContext
&&
6228 TemplateParamLists
.size() != 0) {
6229 ContextRAII
SavedContext(*this, DC
);
6230 if (RebuildDeclaratorInCurrentInstantiation(*this, D
, Name
))
6235 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6236 QualType R
= TInfo
->getType();
6238 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6239 UPPC_DeclarationType
))
6242 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
6243 forRedeclarationInCurContext());
6245 // See if this is a redefinition of a variable in the same scope.
6246 if (!D
.getCXXScopeSpec().isSet()) {
6247 bool IsLinkageLookup
= false;
6248 bool CreateBuiltins
= false;
6250 // If the declaration we're planning to build will be a function
6251 // or object with linkage, then look for another declaration with
6252 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6254 // If the declaration we're planning to build will be declared with
6255 // external linkage in the translation unit, create any builtin with
6257 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
6259 else if (CurContext
->isFunctionOrMethod() &&
6260 (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern
||
6261 R
->isFunctionType())) {
6262 IsLinkageLookup
= true;
6264 CurContext
->getEnclosingNamespaceContext()->isTranslationUnit();
6265 } else if (CurContext
->getRedeclContext()->isTranslationUnit() &&
6266 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
)
6267 CreateBuiltins
= true;
6269 if (IsLinkageLookup
) {
6270 Previous
.clear(LookupRedeclarationWithLinkage
);
6271 Previous
.setRedeclarationKind(ForExternalRedeclaration
);
6274 LookupName(Previous
, S
, CreateBuiltins
);
6275 } else { // Something like "int foo::x;"
6276 LookupQualifiedName(Previous
, DC
);
6278 // C++ [dcl.meaning]p1:
6279 // When the declarator-id is qualified, the declaration shall refer to a
6280 // previously declared member of the class or namespace to which the
6281 // qualifier refers (or, in the case of a namespace, of an element of the
6282 // inline namespace set of that namespace (7.3.1)) or to a specialization
6285 // Note that we already checked the context above, and that we do not have
6286 // enough information to make sure that Previous contains the declaration
6287 // we want to match. For example, given:
6294 // void X::f(int) { } // ill-formed
6296 // In this case, Previous will point to the overload set
6297 // containing the two f's declared in X, but neither of them
6300 // C++ [dcl.meaning]p1:
6301 // [...] the member shall not merely have been introduced by a
6302 // using-declaration in the scope of the class or namespace nominated by
6303 // the nested-name-specifier of the declarator-id.
6304 RemoveUsingDecls(Previous
);
6307 if (Previous
.isSingleResult() &&
6308 Previous
.getFoundDecl()->isTemplateParameter()) {
6309 // Maybe we will complain about the shadowed template parameter.
6310 if (!D
.isInvalidType())
6311 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
6312 Previous
.getFoundDecl());
6314 // Just pretend that we didn't see the previous declaration.
6318 if (!R
->isFunctionType() && DiagnoseClassNameShadow(DC
, NameInfo
))
6319 // Forget that the previous declaration is the injected-class-name.
6322 // In C++, the previous declaration we find might be a tag type
6323 // (class or enum). In this case, the new declaration will hide the
6324 // tag type. Note that this applies to functions, function templates, and
6325 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6326 if (Previous
.isSingleTagDecl() &&
6327 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
6328 (TemplateParamLists
.size() == 0 || R
->isFunctionType()))
6331 // Check that there are no default arguments other than in the parameters
6332 // of a function declaration (C++ only).
6333 if (getLangOpts().CPlusPlus
)
6334 CheckExtraCXXDefaultArguments(D
);
6338 bool AddToScope
= true;
6339 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
6340 if (TemplateParamLists
.size()) {
6341 Diag(D
.getIdentifierLoc(), diag::err_template_typedef
);
6345 New
= ActOnTypedefDeclarator(S
, D
, DC
, TInfo
, Previous
);
6346 } else if (R
->isFunctionType()) {
6347 New
= ActOnFunctionDeclarator(S
, D
, DC
, TInfo
, Previous
,
6351 New
= ActOnVariableDeclarator(S
, D
, DC
, TInfo
, Previous
, TemplateParamLists
,
6358 // If this has an identifier and is not a function template specialization,
6359 // add it to the scope stack.
6360 if (New
->getDeclName() && AddToScope
)
6361 PushOnScopeChains(New
, S
);
6363 if (isInOpenMPDeclareTargetContext())
6364 checkDeclIsAllowedInOpenMPTarget(nullptr, New
);
6369 /// Helper method to turn variable array types into constant array
6370 /// types in certain situations which would otherwise be errors (for
6371 /// GCC compatibility).
6372 static QualType
TryToFixInvalidVariablyModifiedType(QualType T
,
6373 ASTContext
&Context
,
6374 bool &SizeIsNegative
,
6375 llvm::APSInt
&Oversized
) {
6376 // This method tries to turn a variable array into a constant
6377 // array even when the size isn't an ICE. This is necessary
6378 // for compatibility with code that depends on gcc's buggy
6379 // constant expression folding, like struct {char x[(int)(char*)2];}
6380 SizeIsNegative
= false;
6383 if (T
->isDependentType())
6386 QualifierCollector Qs
;
6387 const Type
*Ty
= Qs
.strip(T
);
6389 if (const PointerType
* PTy
= dyn_cast
<PointerType
>(Ty
)) {
6390 QualType Pointee
= PTy
->getPointeeType();
6391 QualType FixedType
=
6392 TryToFixInvalidVariablyModifiedType(Pointee
, Context
, SizeIsNegative
,
6394 if (FixedType
.isNull()) return FixedType
;
6395 FixedType
= Context
.getPointerType(FixedType
);
6396 return Qs
.apply(Context
, FixedType
);
6398 if (const ParenType
* PTy
= dyn_cast
<ParenType
>(Ty
)) {
6399 QualType Inner
= PTy
->getInnerType();
6400 QualType FixedType
=
6401 TryToFixInvalidVariablyModifiedType(Inner
, Context
, SizeIsNegative
,
6403 if (FixedType
.isNull()) return FixedType
;
6404 FixedType
= Context
.getParenType(FixedType
);
6405 return Qs
.apply(Context
, FixedType
);
6408 const VariableArrayType
* VLATy
= dyn_cast
<VariableArrayType
>(T
);
6412 QualType ElemTy
= VLATy
->getElementType();
6413 if (ElemTy
->isVariablyModifiedType()) {
6414 ElemTy
= TryToFixInvalidVariablyModifiedType(ElemTy
, Context
,
6415 SizeIsNegative
, Oversized
);
6416 if (ElemTy
.isNull())
6420 Expr::EvalResult Result
;
6421 if (!VLATy
->getSizeExpr() ||
6422 !VLATy
->getSizeExpr()->EvaluateAsInt(Result
, Context
))
6425 llvm::APSInt Res
= Result
.Val
.getInt();
6427 // Check whether the array size is negative.
6428 if (Res
.isSigned() && Res
.isNegative()) {
6429 SizeIsNegative
= true;
6433 // Check whether the array is too large to be addressed.
6434 unsigned ActiveSizeBits
=
6435 (!ElemTy
->isDependentType() && !ElemTy
->isVariablyModifiedType() &&
6436 !ElemTy
->isIncompleteType() && !ElemTy
->isUndeducedType())
6437 ? ConstantArrayType::getNumAddressingBits(Context
, ElemTy
, Res
)
6438 : Res
.getActiveBits();
6439 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
)) {
6444 QualType FoldedArrayType
= Context
.getConstantArrayType(
6445 ElemTy
, Res
, VLATy
->getSizeExpr(), ArrayType::Normal
, 0);
6446 return Qs
.apply(Context
, FoldedArrayType
);
6450 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL
, TypeLoc DstTL
) {
6451 SrcTL
= SrcTL
.getUnqualifiedLoc();
6452 DstTL
= DstTL
.getUnqualifiedLoc();
6453 if (PointerTypeLoc SrcPTL
= SrcTL
.getAs
<PointerTypeLoc
>()) {
6454 PointerTypeLoc DstPTL
= DstTL
.castAs
<PointerTypeLoc
>();
6455 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getPointeeLoc(),
6456 DstPTL
.getPointeeLoc());
6457 DstPTL
.setStarLoc(SrcPTL
.getStarLoc());
6460 if (ParenTypeLoc SrcPTL
= SrcTL
.getAs
<ParenTypeLoc
>()) {
6461 ParenTypeLoc DstPTL
= DstTL
.castAs
<ParenTypeLoc
>();
6462 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getInnerLoc(),
6463 DstPTL
.getInnerLoc());
6464 DstPTL
.setLParenLoc(SrcPTL
.getLParenLoc());
6465 DstPTL
.setRParenLoc(SrcPTL
.getRParenLoc());
6468 ArrayTypeLoc SrcATL
= SrcTL
.castAs
<ArrayTypeLoc
>();
6469 ArrayTypeLoc DstATL
= DstTL
.castAs
<ArrayTypeLoc
>();
6470 TypeLoc SrcElemTL
= SrcATL
.getElementLoc();
6471 TypeLoc DstElemTL
= DstATL
.getElementLoc();
6472 if (VariableArrayTypeLoc SrcElemATL
=
6473 SrcElemTL
.getAs
<VariableArrayTypeLoc
>()) {
6474 ConstantArrayTypeLoc DstElemATL
= DstElemTL
.castAs
<ConstantArrayTypeLoc
>();
6475 FixInvalidVariablyModifiedTypeLoc(SrcElemATL
, DstElemATL
);
6477 DstElemTL
.initializeFullCopy(SrcElemTL
);
6479 DstATL
.setLBracketLoc(SrcATL
.getLBracketLoc());
6480 DstATL
.setSizeExpr(SrcATL
.getSizeExpr());
6481 DstATL
.setRBracketLoc(SrcATL
.getRBracketLoc());
6484 /// Helper method to turn variable array types into constant array
6485 /// types in certain situations which would otherwise be errors (for
6486 /// GCC compatibility).
6487 static TypeSourceInfo
*
6488 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo
*TInfo
,
6489 ASTContext
&Context
,
6490 bool &SizeIsNegative
,
6491 llvm::APSInt
&Oversized
) {
6493 = TryToFixInvalidVariablyModifiedType(TInfo
->getType(), Context
,
6494 SizeIsNegative
, Oversized
);
6495 if (FixedTy
.isNull())
6497 TypeSourceInfo
*FixedTInfo
= Context
.getTrivialTypeSourceInfo(FixedTy
);
6498 FixInvalidVariablyModifiedTypeLoc(TInfo
->getTypeLoc(),
6499 FixedTInfo
->getTypeLoc());
6503 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6504 /// true if we were successful.
6505 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo
*&TInfo
,
6506 QualType
&T
, SourceLocation Loc
,
6507 unsigned FailedFoldDiagID
) {
6508 bool SizeIsNegative
;
6509 llvm::APSInt Oversized
;
6510 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
6511 TInfo
, Context
, SizeIsNegative
, Oversized
);
6513 Diag(Loc
, diag::ext_vla_folded_to_constant
);
6515 T
= FixedTInfo
->getType();
6520 Diag(Loc
, diag::err_typecheck_negative_array_size
);
6521 else if (Oversized
.getBoolValue())
6522 Diag(Loc
, diag::err_array_too_large
) << toString(Oversized
, 10);
6523 else if (FailedFoldDiagID
)
6524 Diag(Loc
, FailedFoldDiagID
);
6528 /// Register the given locally-scoped extern "C" declaration so
6529 /// that it can be found later for redeclarations. We include any extern "C"
6530 /// declaration that is not visible in the translation unit here, not just
6531 /// function-scope declarations.
6533 Sema::RegisterLocallyScopedExternCDecl(NamedDecl
*ND
, Scope
*S
) {
6534 if (!getLangOpts().CPlusPlus
&&
6535 ND
->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6536 // Don't need to track declarations in the TU in C.
6539 // Note that we have a locally-scoped external with this name.
6540 Context
.getExternCContextDecl()->makeDeclVisibleInContext(ND
);
6543 NamedDecl
*Sema::findLocallyScopedExternCDecl(DeclarationName Name
) {
6544 // FIXME: We can have multiple results via __attribute__((overloadable)).
6545 auto Result
= Context
.getExternCContextDecl()->lookup(Name
);
6546 return Result
.empty() ? nullptr : *Result
.begin();
6549 /// Diagnose function specifiers on a declaration of an identifier that
6550 /// does not identify a function.
6551 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec
&DS
) {
6552 // FIXME: We should probably indicate the identifier in question to avoid
6553 // confusion for constructs like "virtual int a(), b;"
6554 if (DS
.isVirtualSpecified())
6555 Diag(DS
.getVirtualSpecLoc(),
6556 diag::err_virtual_non_function
);
6558 if (DS
.hasExplicitSpecifier())
6559 Diag(DS
.getExplicitSpecLoc(),
6560 diag::err_explicit_non_function
);
6562 if (DS
.isNoreturnSpecified())
6563 Diag(DS
.getNoreturnSpecLoc(),
6564 diag::err_noreturn_non_function
);
6568 Sema::ActOnTypedefDeclarator(Scope
* S
, Declarator
& D
, DeclContext
* DC
,
6569 TypeSourceInfo
*TInfo
, LookupResult
&Previous
) {
6570 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6571 if (D
.getCXXScopeSpec().isSet()) {
6572 Diag(D
.getIdentifierLoc(), diag::err_qualified_typedef_declarator
)
6573 << D
.getCXXScopeSpec().getRange();
6575 // Pretend we didn't see the scope specifier.
6580 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
6582 if (D
.getDeclSpec().isInlineSpecified())
6583 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
6584 << getLangOpts().CPlusPlus17
;
6585 if (D
.getDeclSpec().hasConstexprSpecifier())
6586 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr
)
6587 << 1 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
6589 if (D
.getName().getKind() != UnqualifiedIdKind::IK_Identifier
) {
6590 if (D
.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName
)
6591 Diag(D
.getName().StartLocation
,
6592 diag::err_deduction_guide_invalid_specifier
)
6595 Diag(D
.getName().StartLocation
, diag::err_typedef_not_identifier
)
6596 << D
.getName().getSourceRange();
6600 TypedefDecl
*NewTD
= ParseTypedefDecl(S
, D
, TInfo
->getType(), TInfo
);
6601 if (!NewTD
) return nullptr;
6603 // Handle attributes prior to checking for duplicates in MergeVarDecl
6604 ProcessDeclAttributes(S
, NewTD
, D
);
6606 CheckTypedefForVariablyModifiedType(S
, NewTD
);
6608 bool Redeclaration
= D
.isRedeclaration();
6609 NamedDecl
*ND
= ActOnTypedefNameDecl(S
, DC
, NewTD
, Previous
, Redeclaration
);
6610 D
.setRedeclaration(Redeclaration
);
6615 Sema::CheckTypedefForVariablyModifiedType(Scope
*S
, TypedefNameDecl
*NewTD
) {
6616 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6617 // then it shall have block scope.
6618 // Note that variably modified types must be fixed before merging the decl so
6619 // that redeclarations will match.
6620 TypeSourceInfo
*TInfo
= NewTD
->getTypeSourceInfo();
6621 QualType T
= TInfo
->getType();
6622 if (T
->isVariablyModifiedType()) {
6623 setFunctionHasBranchProtectedScope();
6625 if (S
->getFnParent() == nullptr) {
6626 bool SizeIsNegative
;
6627 llvm::APSInt Oversized
;
6628 TypeSourceInfo
*FixedTInfo
=
6629 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo
, Context
,
6633 Diag(NewTD
->getLocation(), diag::ext_vla_folded_to_constant
);
6634 NewTD
->setTypeSourceInfo(FixedTInfo
);
6637 Diag(NewTD
->getLocation(), diag::err_typecheck_negative_array_size
);
6638 else if (T
->isVariableArrayType())
6639 Diag(NewTD
->getLocation(), diag::err_vla_decl_in_file_scope
);
6640 else if (Oversized
.getBoolValue())
6641 Diag(NewTD
->getLocation(), diag::err_array_too_large
)
6642 << toString(Oversized
, 10);
6644 Diag(NewTD
->getLocation(), diag::err_vm_decl_in_file_scope
);
6645 NewTD
->setInvalidDecl();
6651 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6652 /// declares a typedef-name, either using the 'typedef' type specifier or via
6653 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6655 Sema::ActOnTypedefNameDecl(Scope
*S
, DeclContext
*DC
, TypedefNameDecl
*NewTD
,
6656 LookupResult
&Previous
, bool &Redeclaration
) {
6658 // Find the shadowed declaration before filtering for scope.
6659 NamedDecl
*ShadowedDecl
= getShadowedDeclaration(NewTD
, Previous
);
6661 // Merge the decl with the existing one if appropriate. If the decl is
6662 // in an outer scope, it isn't the same thing.
6663 FilterLookupForScope(Previous
, DC
, S
, /*ConsiderLinkage*/false,
6664 /*AllowInlineNamespace*/false);
6665 filterNonConflictingPreviousTypedefDecls(*this, NewTD
, Previous
);
6666 if (!Previous
.empty()) {
6667 Redeclaration
= true;
6668 MergeTypedefNameDecl(S
, NewTD
, Previous
);
6670 inferGslPointerAttribute(NewTD
);
6673 if (ShadowedDecl
&& !Redeclaration
)
6674 CheckShadow(NewTD
, ShadowedDecl
, Previous
);
6676 // If this is the C FILE type, notify the AST context.
6677 if (IdentifierInfo
*II
= NewTD
->getIdentifier())
6678 if (!NewTD
->isInvalidDecl() &&
6679 NewTD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6680 if (II
->isStr("FILE"))
6681 Context
.setFILEDecl(NewTD
);
6682 else if (II
->isStr("jmp_buf"))
6683 Context
.setjmp_bufDecl(NewTD
);
6684 else if (II
->isStr("sigjmp_buf"))
6685 Context
.setsigjmp_bufDecl(NewTD
);
6686 else if (II
->isStr("ucontext_t"))
6687 Context
.setucontext_tDecl(NewTD
);
6693 /// Determines whether the given declaration is an out-of-scope
6694 /// previous declaration.
6696 /// This routine should be invoked when name lookup has found a
6697 /// previous declaration (PrevDecl) that is not in the scope where a
6698 /// new declaration by the same name is being introduced. If the new
6699 /// declaration occurs in a local scope, previous declarations with
6700 /// linkage may still be considered previous declarations (C99
6701 /// 6.2.2p4-5, C++ [basic.link]p6).
6703 /// \param PrevDecl the previous declaration found by name
6706 /// \param DC the context in which the new declaration is being
6709 /// \returns true if PrevDecl is an out-of-scope previous declaration
6710 /// for a new delcaration with the same name.
6712 isOutOfScopePreviousDeclaration(NamedDecl
*PrevDecl
, DeclContext
*DC
,
6713 ASTContext
&Context
) {
6717 if (!PrevDecl
->hasLinkage())
6720 if (Context
.getLangOpts().CPlusPlus
) {
6721 // C++ [basic.link]p6:
6722 // If there is a visible declaration of an entity with linkage
6723 // having the same name and type, ignoring entities declared
6724 // outside the innermost enclosing namespace scope, the block
6725 // scope declaration declares that same entity and receives the
6726 // linkage of the previous declaration.
6727 DeclContext
*OuterContext
= DC
->getRedeclContext();
6728 if (!OuterContext
->isFunctionOrMethod())
6729 // This rule only applies to block-scope declarations.
6732 DeclContext
*PrevOuterContext
= PrevDecl
->getDeclContext();
6733 if (PrevOuterContext
->isRecord())
6734 // We found a member function: ignore it.
6737 // Find the innermost enclosing namespace for the new and
6738 // previous declarations.
6739 OuterContext
= OuterContext
->getEnclosingNamespaceContext();
6740 PrevOuterContext
= PrevOuterContext
->getEnclosingNamespaceContext();
6742 // The previous declaration is in a different namespace, so it
6743 // isn't the same function.
6744 if (!OuterContext
->Equals(PrevOuterContext
))
6751 static void SetNestedNameSpecifier(Sema
&S
, DeclaratorDecl
*DD
, Declarator
&D
) {
6752 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
6753 if (!SS
.isSet()) return;
6754 DD
->setQualifierInfo(SS
.getWithLocInContext(S
.Context
));
6757 bool Sema::inferObjCARCLifetime(ValueDecl
*decl
) {
6758 QualType type
= decl
->getType();
6759 Qualifiers::ObjCLifetime lifetime
= type
.getObjCLifetime();
6760 if (lifetime
== Qualifiers::OCL_Autoreleasing
) {
6761 // Various kinds of declaration aren't allowed to be __autoreleasing.
6762 unsigned kind
= -1U;
6763 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6764 if (var
->hasAttr
<BlocksAttr
>())
6765 kind
= 0; // __block
6766 else if (!var
->hasLocalStorage())
6768 } else if (isa
<ObjCIvarDecl
>(decl
)) {
6770 } else if (isa
<FieldDecl
>(decl
)) {
6775 Diag(decl
->getLocation(), diag::err_arc_autoreleasing_var
)
6778 } else if (lifetime
== Qualifiers::OCL_None
) {
6779 // Try to infer lifetime.
6780 if (!type
->isObjCLifetimeType())
6783 lifetime
= type
->getObjCARCImplicitLifetime();
6784 type
= Context
.getLifetimeQualifiedType(type
, lifetime
);
6785 decl
->setType(type
);
6788 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6789 // Thread-local variables cannot have lifetime.
6790 if (lifetime
&& lifetime
!= Qualifiers::OCL_ExplicitNone
&&
6791 var
->getTLSKind()) {
6792 Diag(var
->getLocation(), diag::err_arc_thread_ownership
)
6801 void Sema::deduceOpenCLAddressSpace(ValueDecl
*Decl
) {
6802 if (Decl
->getType().hasAddressSpace())
6804 if (Decl
->getType()->isDependentType())
6806 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(Decl
)) {
6807 QualType Type
= Var
->getType();
6808 if (Type
->isSamplerT() || Type
->isVoidType())
6810 LangAS ImplAS
= LangAS::opencl_private
;
6811 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6812 // __opencl_c_program_scope_global_variables feature, the address space
6813 // for a variable at program scope or a static or extern variable inside
6814 // a function are inferred to be __global.
6815 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6816 Var
->hasGlobalStorage())
6817 ImplAS
= LangAS::opencl_global
;
6818 // If the original type from a decayed type is an array type and that array
6819 // type has no address space yet, deduce it now.
6820 if (auto DT
= dyn_cast
<DecayedType
>(Type
)) {
6821 auto OrigTy
= DT
->getOriginalType();
6822 if (!OrigTy
.hasAddressSpace() && OrigTy
->isArrayType()) {
6823 // Add the address space to the original array type and then propagate
6824 // that to the element type through `getAsArrayType`.
6825 OrigTy
= Context
.getAddrSpaceQualType(OrigTy
, ImplAS
);
6826 OrigTy
= QualType(Context
.getAsArrayType(OrigTy
), 0);
6827 // Re-generate the decayed type.
6828 Type
= Context
.getDecayedType(OrigTy
);
6831 Type
= Context
.getAddrSpaceQualType(Type
, ImplAS
);
6832 // Apply any qualifiers (including address space) from the array type to
6833 // the element type. This implements C99 6.7.3p8: "If the specification of
6834 // an array type includes any type qualifiers, the element type is so
6835 // qualified, not the array type."
6836 if (Type
->isArrayType())
6837 Type
= QualType(Context
.getAsArrayType(Type
), 0);
6838 Decl
->setType(Type
);
6842 static void checkAttributesAfterMerging(Sema
&S
, NamedDecl
&ND
) {
6843 // Ensure that an auto decl is deduced otherwise the checks below might cache
6844 // the wrong linkage.
6845 assert(S
.ParsingInitForAutoVars
.count(&ND
) == 0);
6847 // 'weak' only applies to declarations with external linkage.
6848 if (WeakAttr
*Attr
= ND
.getAttr
<WeakAttr
>()) {
6849 if (!ND
.isExternallyVisible()) {
6850 S
.Diag(Attr
->getLocation(), diag::err_attribute_weak_static
);
6851 ND
.dropAttr
<WeakAttr
>();
6854 if (WeakRefAttr
*Attr
= ND
.getAttr
<WeakRefAttr
>()) {
6855 if (ND
.isExternallyVisible()) {
6856 S
.Diag(Attr
->getLocation(), diag::err_attribute_weakref_not_static
);
6857 ND
.dropAttr
<WeakRefAttr
>();
6858 ND
.dropAttr
<AliasAttr
>();
6862 if (auto *VD
= dyn_cast
<VarDecl
>(&ND
)) {
6863 if (VD
->hasInit()) {
6864 if (const auto *Attr
= VD
->getAttr
<AliasAttr
>()) {
6865 assert(VD
->isThisDeclarationADefinition() &&
6866 !VD
->isExternallyVisible() && "Broken AliasAttr handled late!");
6867 S
.Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << VD
<< 0;
6868 VD
->dropAttr
<AliasAttr
>();
6873 // 'selectany' only applies to externally visible variable declarations.
6874 // It does not apply to functions.
6875 if (SelectAnyAttr
*Attr
= ND
.getAttr
<SelectAnyAttr
>()) {
6876 if (isa
<FunctionDecl
>(ND
) || !ND
.isExternallyVisible()) {
6877 S
.Diag(Attr
->getLocation(),
6878 diag::err_attribute_selectany_non_extern_data
);
6879 ND
.dropAttr
<SelectAnyAttr
>();
6883 if (const InheritableAttr
*Attr
= getDLLAttr(&ND
)) {
6884 auto *VD
= dyn_cast
<VarDecl
>(&ND
);
6885 bool IsAnonymousNS
= false;
6886 bool IsMicrosoft
= S
.Context
.getTargetInfo().getCXXABI().isMicrosoft();
6888 const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(VD
->getDeclContext());
6889 while (NS
&& !IsAnonymousNS
) {
6890 IsAnonymousNS
= NS
->isAnonymousNamespace();
6891 NS
= dyn_cast
<NamespaceDecl
>(NS
->getParent());
6894 // dll attributes require external linkage. Static locals may have external
6895 // linkage but still cannot be explicitly imported or exported.
6896 // In Microsoft mode, a variable defined in anonymous namespace must have
6897 // external linkage in order to be exported.
6898 bool AnonNSInMicrosoftMode
= IsAnonymousNS
&& IsMicrosoft
;
6899 if ((ND
.isExternallyVisible() && AnonNSInMicrosoftMode
) ||
6900 (!AnonNSInMicrosoftMode
&&
6901 (!ND
.isExternallyVisible() || (VD
&& VD
->isStaticLocal())))) {
6902 S
.Diag(ND
.getLocation(), diag::err_attribute_dll_not_extern
)
6904 ND
.setInvalidDecl();
6908 // Check the attributes on the function type, if any.
6909 if (const auto *FD
= dyn_cast
<FunctionDecl
>(&ND
)) {
6910 // Don't declare this variable in the second operand of the for-statement;
6911 // GCC miscompiles that by ending its lifetime before evaluating the
6912 // third operand. See gcc.gnu.org/PR86769.
6913 AttributedTypeLoc ATL
;
6914 for (TypeLoc TL
= FD
->getTypeSourceInfo()->getTypeLoc();
6915 (ATL
= TL
.getAsAdjusted
<AttributedTypeLoc
>());
6916 TL
= ATL
.getModifiedLoc()) {
6917 // The [[lifetimebound]] attribute can be applied to the implicit object
6918 // parameter of a non-static member function (other than a ctor or dtor)
6919 // by applying it to the function type.
6920 if (const auto *A
= ATL
.getAttrAs
<LifetimeBoundAttr
>()) {
6921 const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
6922 if (!MD
|| MD
->isStatic()) {
6923 S
.Diag(A
->getLocation(), diag::err_lifetimebound_no_object_param
)
6924 << !MD
<< A
->getRange();
6925 } else if (isa
<CXXConstructorDecl
>(MD
) || isa
<CXXDestructorDecl
>(MD
)) {
6926 S
.Diag(A
->getLocation(), diag::err_lifetimebound_ctor_dtor
)
6927 << isa
<CXXDestructorDecl
>(MD
) << A
->getRange();
6934 static void checkDLLAttributeRedeclaration(Sema
&S
, NamedDecl
*OldDecl
,
6936 bool IsSpecialization
,
6937 bool IsDefinition
) {
6938 if (OldDecl
->isInvalidDecl() || NewDecl
->isInvalidDecl())
6941 bool IsTemplate
= false;
6942 if (TemplateDecl
*OldTD
= dyn_cast
<TemplateDecl
>(OldDecl
)) {
6943 OldDecl
= OldTD
->getTemplatedDecl();
6945 if (!IsSpecialization
)
6946 IsDefinition
= false;
6948 if (TemplateDecl
*NewTD
= dyn_cast
<TemplateDecl
>(NewDecl
)) {
6949 NewDecl
= NewTD
->getTemplatedDecl();
6953 if (!OldDecl
|| !NewDecl
)
6956 const DLLImportAttr
*OldImportAttr
= OldDecl
->getAttr
<DLLImportAttr
>();
6957 const DLLExportAttr
*OldExportAttr
= OldDecl
->getAttr
<DLLExportAttr
>();
6958 const DLLImportAttr
*NewImportAttr
= NewDecl
->getAttr
<DLLImportAttr
>();
6959 const DLLExportAttr
*NewExportAttr
= NewDecl
->getAttr
<DLLExportAttr
>();
6961 // dllimport and dllexport are inheritable attributes so we have to exclude
6962 // inherited attribute instances.
6963 bool HasNewAttr
= (NewImportAttr
&& !NewImportAttr
->isInherited()) ||
6964 (NewExportAttr
&& !NewExportAttr
->isInherited());
6966 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6967 // the only exception being explicit specializations.
6968 // Implicitly generated declarations are also excluded for now because there
6969 // is no other way to switch these to use dllimport or dllexport.
6970 bool AddsAttr
= !(OldImportAttr
|| OldExportAttr
) && HasNewAttr
;
6972 if (AddsAttr
&& !IsSpecialization
&& !OldDecl
->isImplicit()) {
6973 // Allow with a warning for free functions and global variables.
6974 bool JustWarn
= false;
6975 if (!OldDecl
->isCXXClassMember()) {
6976 auto *VD
= dyn_cast
<VarDecl
>(OldDecl
);
6977 if (VD
&& !VD
->getDescribedVarTemplate())
6979 auto *FD
= dyn_cast
<FunctionDecl
>(OldDecl
);
6980 if (FD
&& FD
->getTemplatedKind() == FunctionDecl::TK_NonTemplate
)
6984 // We cannot change a declaration that's been used because IR has already
6985 // been emitted. Dllimported functions will still work though (modulo
6986 // address equality) as they can use the thunk.
6987 if (OldDecl
->isUsed())
6988 if (!isa
<FunctionDecl
>(OldDecl
) || !NewImportAttr
)
6991 unsigned DiagID
= JustWarn
? diag::warn_attribute_dll_redeclaration
6992 : diag::err_attribute_dll_redeclaration
;
6993 S
.Diag(NewDecl
->getLocation(), DiagID
)
6995 << (NewImportAttr
? (const Attr
*)NewImportAttr
: NewExportAttr
);
6996 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
6998 NewDecl
->setInvalidDecl();
7003 // A redeclaration is not allowed to drop a dllimport attribute, the only
7004 // exceptions being inline function definitions (except for function
7005 // templates), local extern declarations, qualified friend declarations or
7006 // special MSVC extension: in the last case, the declaration is treated as if
7007 // it were marked dllexport.
7008 bool IsInline
= false, IsStaticDataMember
= false, IsQualifiedFriend
= false;
7009 bool IsMicrosoftABI
= S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols();
7010 if (const auto *VD
= dyn_cast
<VarDecl
>(NewDecl
)) {
7011 // Ignore static data because out-of-line definitions are diagnosed
7013 IsStaticDataMember
= VD
->isStaticDataMember();
7014 IsDefinition
= VD
->isThisDeclarationADefinition(S
.Context
) !=
7015 VarDecl::DeclarationOnly
;
7016 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(NewDecl
)) {
7017 IsInline
= FD
->isInlined();
7018 IsQualifiedFriend
= FD
->getQualifier() &&
7019 FD
->getFriendObjectKind() == Decl::FOK_Declared
;
7022 if (OldImportAttr
&& !HasNewAttr
&&
7023 (!IsInline
|| (IsMicrosoftABI
&& IsTemplate
)) && !IsStaticDataMember
&&
7024 !NewDecl
->isLocalExternDecl() && !IsQualifiedFriend
) {
7025 if (IsMicrosoftABI
&& IsDefinition
) {
7026 S
.Diag(NewDecl
->getLocation(),
7027 diag::warn_redeclaration_without_import_attribute
)
7029 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7030 NewDecl
->dropAttr
<DLLImportAttr
>();
7032 DLLExportAttr::CreateImplicit(S
.Context
, NewImportAttr
->getRange()));
7034 S
.Diag(NewDecl
->getLocation(),
7035 diag::warn_redeclaration_without_attribute_prev_attribute_ignored
)
7036 << NewDecl
<< OldImportAttr
;
7037 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7038 S
.Diag(OldImportAttr
->getLocation(), diag::note_previous_attribute
);
7039 OldDecl
->dropAttr
<DLLImportAttr
>();
7040 NewDecl
->dropAttr
<DLLImportAttr
>();
7042 } else if (IsInline
&& OldImportAttr
&& !IsMicrosoftABI
) {
7043 // In MinGW, seeing a function declared inline drops the dllimport
7045 OldDecl
->dropAttr
<DLLImportAttr
>();
7046 NewDecl
->dropAttr
<DLLImportAttr
>();
7047 S
.Diag(NewDecl
->getLocation(),
7048 diag::warn_dllimport_dropped_from_inline_function
)
7049 << NewDecl
<< OldImportAttr
;
7052 // A specialization of a class template member function is processed here
7053 // since it's a redeclaration. If the parent class is dllexport, the
7054 // specialization inherits that attribute. This doesn't happen automatically
7055 // since the parent class isn't instantiated until later.
7056 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDecl
)) {
7057 if (MD
->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
&&
7058 !NewImportAttr
&& !NewExportAttr
) {
7059 if (const DLLExportAttr
*ParentExportAttr
=
7060 MD
->getParent()->getAttr
<DLLExportAttr
>()) {
7061 DLLExportAttr
*NewAttr
= ParentExportAttr
->clone(S
.Context
);
7062 NewAttr
->setInherited(true);
7063 NewDecl
->addAttr(NewAttr
);
7069 /// Given that we are within the definition of the given function,
7070 /// will that definition behave like C99's 'inline', where the
7071 /// definition is discarded except for optimization purposes?
7072 static bool isFunctionDefinitionDiscarded(Sema
&S
, FunctionDecl
*FD
) {
7073 // Try to avoid calling GetGVALinkageForFunction.
7075 // All cases of this require the 'inline' keyword.
7076 if (!FD
->isInlined()) return false;
7078 // This is only possible in C++ with the gnu_inline attribute.
7079 if (S
.getLangOpts().CPlusPlus
&& !FD
->hasAttr
<GNUInlineAttr
>())
7082 // Okay, go ahead and call the relatively-more-expensive function.
7083 return S
.Context
.GetGVALinkageForFunction(FD
) == GVA_AvailableExternally
;
7086 /// Determine whether a variable is extern "C" prior to attaching
7087 /// an initializer. We can't just call isExternC() here, because that
7088 /// will also compute and cache whether the declaration is externally
7089 /// visible, which might change when we attach the initializer.
7091 /// This can only be used if the declaration is known to not be a
7092 /// redeclaration of an internal linkage declaration.
7098 /// Attaching the initializer here makes this declaration not externally
7099 /// visible, because its type has internal linkage.
7101 /// FIXME: This is a hack.
7102 template<typename T
>
7103 static bool isIncompleteDeclExternC(Sema
&S
, const T
*D
) {
7104 if (S
.getLangOpts().CPlusPlus
) {
7105 // In C++, the overloadable attribute negates the effects of extern "C".
7106 if (!D
->isInExternCContext() || D
->template hasAttr
<OverloadableAttr
>())
7109 // So do CUDA's host/device attributes.
7110 if (S
.getLangOpts().CUDA
&& (D
->template hasAttr
<CUDADeviceAttr
>() ||
7111 D
->template hasAttr
<CUDAHostAttr
>()))
7114 return D
->isExternC();
7117 static bool shouldConsiderLinkage(const VarDecl
*VD
) {
7118 const DeclContext
*DC
= VD
->getDeclContext()->getRedeclContext();
7119 if (DC
->isFunctionOrMethod() || isa
<OMPDeclareReductionDecl
>(DC
) ||
7120 isa
<OMPDeclareMapperDecl
>(DC
))
7121 return VD
->hasExternalStorage();
7122 if (DC
->isFileContext())
7126 if (isa
<RequiresExprBodyDecl
>(DC
))
7128 llvm_unreachable("Unexpected context");
7131 static bool shouldConsiderLinkage(const FunctionDecl
*FD
) {
7132 const DeclContext
*DC
= FD
->getDeclContext()->getRedeclContext();
7133 if (DC
->isFileContext() || DC
->isFunctionOrMethod() ||
7134 isa
<OMPDeclareReductionDecl
>(DC
) || isa
<OMPDeclareMapperDecl
>(DC
))
7138 llvm_unreachable("Unexpected context");
7141 static bool hasParsedAttr(Scope
*S
, const Declarator
&PD
,
7142 ParsedAttr::Kind Kind
) {
7143 // Check decl attributes on the DeclSpec.
7144 if (PD
.getDeclSpec().getAttributes().hasAttribute(Kind
))
7147 // Walk the declarator structure, checking decl attributes that were in a type
7148 // position to the decl itself.
7149 for (unsigned I
= 0, E
= PD
.getNumTypeObjects(); I
!= E
; ++I
) {
7150 if (PD
.getTypeObject(I
).getAttrs().hasAttribute(Kind
))
7154 // Finally, check attributes on the decl itself.
7155 return PD
.getAttributes().hasAttribute(Kind
) ||
7156 PD
.getDeclarationAttributes().hasAttribute(Kind
);
7159 /// Adjust the \c DeclContext for a function or variable that might be a
7160 /// function-local external declaration.
7161 bool Sema::adjustContextForLocalExternDecl(DeclContext
*&DC
) {
7162 if (!DC
->isFunctionOrMethod())
7165 // If this is a local extern function or variable declared within a function
7166 // template, don't add it into the enclosing namespace scope until it is
7167 // instantiated; it might have a dependent type right now.
7168 if (DC
->isDependentContext())
7171 // C++11 [basic.link]p7:
7172 // When a block scope declaration of an entity with linkage is not found to
7173 // refer to some other declaration, then that entity is a member of the
7174 // innermost enclosing namespace.
7176 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7177 // semantically-enclosing namespace, not a lexically-enclosing one.
7178 while (!DC
->isFileContext() && !isa
<LinkageSpecDecl
>(DC
))
7179 DC
= DC
->getParent();
7183 /// Returns true if given declaration has external C language linkage.
7184 static bool isDeclExternC(const Decl
*D
) {
7185 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
7186 return FD
->isExternC();
7187 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
7188 return VD
->isExternC();
7190 llvm_unreachable("Unknown type of decl!");
7193 /// Returns true if there hasn't been any invalid type diagnosed.
7194 static bool diagnoseOpenCLTypes(Sema
&Se
, VarDecl
*NewVD
) {
7195 DeclContext
*DC
= NewVD
->getDeclContext();
7196 QualType R
= NewVD
->getType();
7198 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7199 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7201 if (R
->isImageType() || R
->isPipeType()) {
7202 Se
.Diag(NewVD
->getLocation(),
7203 diag::err_opencl_type_can_only_be_used_as_function_parameter
)
7205 NewVD
->setInvalidDecl();
7209 // OpenCL v1.2 s6.9.r:
7210 // The event type cannot be used to declare a program scope variable.
7211 // OpenCL v2.0 s6.9.q:
7212 // The clk_event_t and reserve_id_t types cannot be declared in program
7214 if (NewVD
->hasGlobalStorage() && !NewVD
->isStaticLocal()) {
7215 if (R
->isReserveIDT() || R
->isClkEventT() || R
->isEventT()) {
7216 Se
.Diag(NewVD
->getLocation(),
7217 diag::err_invalid_type_for_program_scope_var
)
7219 NewVD
->setInvalidDecl();
7224 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7225 if (!Se
.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7226 Se
.getLangOpts())) {
7227 QualType NR
= R
.getCanonicalType();
7228 while (NR
->isPointerType() || NR
->isMemberFunctionPointerType() ||
7229 NR
->isReferenceType()) {
7230 if (NR
->isFunctionPointerType() || NR
->isMemberFunctionPointerType() ||
7231 NR
->isFunctionReferenceType()) {
7232 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_function_pointer
)
7233 << NR
->isReferenceType();
7234 NewVD
->setInvalidDecl();
7237 NR
= NR
->getPointeeType();
7241 if (!Se
.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7242 Se
.getLangOpts())) {
7243 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7244 // half array type (unless the cl_khr_fp16 extension is enabled).
7245 if (Se
.Context
.getBaseElementType(R
)->isHalfType()) {
7246 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_half_declaration
) << R
;
7247 NewVD
->setInvalidDecl();
7252 // OpenCL v1.2 s6.9.r:
7253 // The event type cannot be used with the __local, __constant and __global
7254 // address space qualifiers.
7255 if (R
->isEventT()) {
7256 if (R
.getAddressSpace() != LangAS::opencl_private
) {
7257 Se
.Diag(NewVD
->getBeginLoc(), diag::err_event_t_addr_space_qual
);
7258 NewVD
->setInvalidDecl();
7263 if (R
->isSamplerT()) {
7264 // OpenCL v1.2 s6.9.b p4:
7265 // The sampler type cannot be used with the __local and __global address
7266 // space qualifiers.
7267 if (R
.getAddressSpace() == LangAS::opencl_local
||
7268 R
.getAddressSpace() == LangAS::opencl_global
) {
7269 Se
.Diag(NewVD
->getLocation(), diag::err_wrong_sampler_addressspace
);
7270 NewVD
->setInvalidDecl();
7273 // OpenCL v1.2 s6.12.14.1:
7274 // A global sampler must be declared with either the constant address
7275 // space qualifier or with the const qualifier.
7276 if (DC
->isTranslationUnit() &&
7277 !(R
.getAddressSpace() == LangAS::opencl_constant
||
7278 R
.isConstQualified())) {
7279 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_nonconst_global_sampler
);
7280 NewVD
->setInvalidDecl();
7282 if (NewVD
->isInvalidDecl())
7289 template <typename AttrTy
>
7290 static void copyAttrFromTypedefToDecl(Sema
&S
, Decl
*D
, const TypedefType
*TT
) {
7291 const TypedefNameDecl
*TND
= TT
->getDecl();
7292 if (const auto *Attribute
= TND
->getAttr
<AttrTy
>()) {
7293 AttrTy
*Clone
= Attribute
->clone(S
.Context
);
7294 Clone
->setInherited(true);
7299 NamedDecl
*Sema::ActOnVariableDeclarator(
7300 Scope
*S
, Declarator
&D
, DeclContext
*DC
, TypeSourceInfo
*TInfo
,
7301 LookupResult
&Previous
, MultiTemplateParamsArg TemplateParamLists
,
7302 bool &AddToScope
, ArrayRef
<BindingDecl
*> Bindings
) {
7303 QualType R
= TInfo
->getType();
7304 DeclarationName Name
= GetNameForDeclarator(D
).getName();
7306 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
7308 if (D
.isDecompositionDeclarator()) {
7309 // Take the name of the first declarator as our name for diagnostic
7311 auto &Decomp
= D
.getDecompositionDeclarator();
7312 if (!Decomp
.bindings().empty()) {
7313 II
= Decomp
.bindings()[0].Name
;
7317 Diag(D
.getIdentifierLoc(), diag::err_bad_variable_name
) << Name
;
7322 DeclSpec::SCS SCSpec
= D
.getDeclSpec().getStorageClassSpec();
7323 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(D
.getDeclSpec());
7325 // dllimport globals without explicit storage class are treated as extern. We
7326 // have to change the storage class this early to get the right DeclContext.
7327 if (SC
== SC_None
&& !DC
->isRecord() &&
7328 hasParsedAttr(S
, D
, ParsedAttr::AT_DLLImport
) &&
7329 !hasParsedAttr(S
, D
, ParsedAttr::AT_DLLExport
))
7332 DeclContext
*OriginalDC
= DC
;
7333 bool IsLocalExternDecl
= SC
== SC_Extern
&&
7334 adjustContextForLocalExternDecl(DC
);
7336 if (SCSpec
== DeclSpec::SCS_mutable
) {
7337 // mutable can only appear on non-static class members, so it's always
7339 Diag(D
.getIdentifierLoc(), diag::err_mutable_nonmember
);
7344 if (getLangOpts().CPlusPlus11
&& SCSpec
== DeclSpec::SCS_register
&&
7345 !D
.getAsmLabel() && !getSourceManager().isInSystemMacro(
7346 D
.getDeclSpec().getStorageClassSpecLoc())) {
7347 // In C++11, the 'register' storage class specifier is deprecated.
7348 // Suppress the warning in system macros, it's used in macros in some
7349 // popular C system headers, such as in glibc's htonl() macro.
7350 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7351 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
7352 : diag::warn_deprecated_register
)
7353 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7356 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
7358 if (!DC
->isRecord() && S
->getFnParent() == nullptr) {
7359 // C99 6.9p2: The storage-class specifiers auto and register shall not
7360 // appear in the declaration specifiers in an external declaration.
7361 // Global Register+Asm is a GNU extension we support.
7362 if (SC
== SC_Auto
|| (SC
== SC_Register
&& !D
.getAsmLabel())) {
7363 Diag(D
.getIdentifierLoc(), diag::err_typecheck_sclass_fscope
);
7368 // If this variable has a VLA type and an initializer, try to
7369 // fold to a constant-sized type. This is otherwise invalid.
7370 if (D
.hasInitializer() && R
->isVariableArrayType())
7371 tryToFixVariablyModifiedVarType(TInfo
, R
, D
.getIdentifierLoc(),
7374 bool IsMemberSpecialization
= false;
7375 bool IsVariableTemplateSpecialization
= false;
7376 bool IsPartialSpecialization
= false;
7377 bool IsVariableTemplate
= false;
7378 VarDecl
*NewVD
= nullptr;
7379 VarTemplateDecl
*NewTemplate
= nullptr;
7380 TemplateParameterList
*TemplateParams
= nullptr;
7381 if (!getLangOpts().CPlusPlus
) {
7382 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(),
7385 if (R
->getContainedDeducedType())
7386 ParsingInitForAutoVars
.insert(NewVD
);
7388 if (D
.isInvalidType())
7389 NewVD
->setInvalidDecl();
7391 if (NewVD
->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7392 NewVD
->hasLocalStorage())
7393 checkNonTrivialCUnion(NewVD
->getType(), NewVD
->getLocation(),
7394 NTCUC_AutoVar
, NTCUK_Destruct
);
7396 bool Invalid
= false;
7398 if (DC
->isRecord() && !CurContext
->isRecord()) {
7399 // This is an out-of-line definition of a static data member.
7404 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7405 diag::err_static_out_of_line
)
7406 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7411 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7412 // to names of variables declared in a block or to function parameters.
7413 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7416 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7417 diag::err_storage_class_for_static_member
)
7418 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7420 case SC_PrivateExtern
:
7421 llvm_unreachable("C storage class in c++!");
7425 if (SC
== SC_Static
&& CurContext
->isRecord()) {
7426 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
7427 // Walk up the enclosing DeclContexts to check for any that are
7428 // incompatible with static data members.
7429 const DeclContext
*FunctionOrMethod
= nullptr;
7430 const CXXRecordDecl
*AnonStruct
= nullptr;
7431 for (DeclContext
*Ctxt
= DC
; Ctxt
; Ctxt
= Ctxt
->getParent()) {
7432 if (Ctxt
->isFunctionOrMethod()) {
7433 FunctionOrMethod
= Ctxt
;
7436 const CXXRecordDecl
*ParentDecl
= dyn_cast
<CXXRecordDecl
>(Ctxt
);
7437 if (ParentDecl
&& !ParentDecl
->getDeclName()) {
7438 AnonStruct
= ParentDecl
;
7442 if (FunctionOrMethod
) {
7443 // C++ [class.static.data]p5: A local class shall not have static data
7445 Diag(D
.getIdentifierLoc(),
7446 diag::err_static_data_member_not_allowed_in_local_class
)
7447 << Name
<< RD
->getDeclName() << RD
->getTagKind();
7448 } else if (AnonStruct
) {
7449 // C++ [class.static.data]p4: Unnamed classes and classes contained
7450 // directly or indirectly within unnamed classes shall not contain
7451 // static data members.
7452 Diag(D
.getIdentifierLoc(),
7453 diag::err_static_data_member_not_allowed_in_anon_struct
)
7454 << Name
<< AnonStruct
->getTagKind();
7456 } else if (RD
->isUnion()) {
7457 // C++98 [class.union]p1: If a union contains a static data member,
7458 // the program is ill-formed. C++11 drops this restriction.
7459 Diag(D
.getIdentifierLoc(),
7460 getLangOpts().CPlusPlus11
7461 ? diag::warn_cxx98_compat_static_data_member_in_union
7462 : diag::ext_static_data_member_in_union
) << Name
;
7467 // Match up the template parameter lists with the scope specifier, then
7468 // determine whether we have a template or a template specialization.
7469 bool InvalidScope
= false;
7470 TemplateParams
= MatchTemplateParametersToScopeSpecifier(
7471 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
7472 D
.getCXXScopeSpec(),
7473 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7474 ? D
.getName().TemplateId
7477 /*never a friend*/ false, IsMemberSpecialization
, InvalidScope
);
7478 Invalid
|= InvalidScope
;
7480 if (TemplateParams
) {
7481 if (!TemplateParams
->size() &&
7482 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
7483 // There is an extraneous 'template<>' for this variable. Complain
7484 // about it, but allow the declaration of the variable.
7485 Diag(TemplateParams
->getTemplateLoc(),
7486 diag::err_template_variable_noparams
)
7488 << SourceRange(TemplateParams
->getTemplateLoc(),
7489 TemplateParams
->getRAngleLoc());
7490 TemplateParams
= nullptr;
7492 // Check that we can declare a template here.
7493 if (CheckTemplateDeclScope(S
, TemplateParams
))
7496 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
7497 // This is an explicit specialization or a partial specialization.
7498 IsVariableTemplateSpecialization
= true;
7499 IsPartialSpecialization
= TemplateParams
->size() > 0;
7500 } else { // if (TemplateParams->size() > 0)
7501 // This is a template declaration.
7502 IsVariableTemplate
= true;
7504 // Only C++1y supports variable templates (N3651).
7505 Diag(D
.getIdentifierLoc(),
7506 getLangOpts().CPlusPlus14
7507 ? diag::warn_cxx11_compat_variable_template
7508 : diag::ext_variable_template
);
7512 // Check that we can declare a member specialization here.
7513 if (!TemplateParamLists
.empty() && IsMemberSpecialization
&&
7514 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
7517 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) &&
7518 "should have a 'template<>' for this decl");
7521 if (IsVariableTemplateSpecialization
) {
7522 SourceLocation TemplateKWLoc
=
7523 TemplateParamLists
.size() > 0
7524 ? TemplateParamLists
[0]->getTemplateLoc()
7526 DeclResult Res
= ActOnVarTemplateSpecialization(
7527 S
, D
, TInfo
, TemplateKWLoc
, TemplateParams
, SC
,
7528 IsPartialSpecialization
);
7529 if (Res
.isInvalid())
7531 NewVD
= cast
<VarDecl
>(Res
.get());
7533 } else if (D
.isDecompositionDeclarator()) {
7534 NewVD
= DecompositionDecl::Create(Context
, DC
, D
.getBeginLoc(),
7535 D
.getIdentifierLoc(), R
, TInfo
, SC
,
7538 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(),
7539 D
.getIdentifierLoc(), II
, R
, TInfo
, SC
);
7541 // If this is supposed to be a variable template, create it as such.
7542 if (IsVariableTemplate
) {
7544 VarTemplateDecl::Create(Context
, DC
, D
.getIdentifierLoc(), Name
,
7545 TemplateParams
, NewVD
);
7546 NewVD
->setDescribedVarTemplate(NewTemplate
);
7549 // If this decl has an auto type in need of deduction, make a note of the
7550 // Decl so we can diagnose uses of it in its own initializer.
7551 if (R
->getContainedDeducedType())
7552 ParsingInitForAutoVars
.insert(NewVD
);
7554 if (D
.isInvalidType() || Invalid
) {
7555 NewVD
->setInvalidDecl();
7557 NewTemplate
->setInvalidDecl();
7560 SetNestedNameSpecifier(*this, NewVD
, D
);
7562 // If we have any template parameter lists that don't directly belong to
7563 // the variable (matching the scope specifier), store them.
7564 unsigned VDTemplateParamLists
= TemplateParams
? 1 : 0;
7565 if (TemplateParamLists
.size() > VDTemplateParamLists
)
7566 NewVD
->setTemplateParameterListsInfo(
7567 Context
, TemplateParamLists
.drop_back(VDTemplateParamLists
));
7570 if (D
.getDeclSpec().isInlineSpecified()) {
7571 if (!getLangOpts().CPlusPlus
) {
7572 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
7574 } else if (CurContext
->isFunctionOrMethod()) {
7575 // 'inline' is not allowed on block scope variable declaration.
7576 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7577 diag::err_inline_declaration_block_scope
) << Name
7578 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
7580 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7581 getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_inline_variable
7582 : diag::ext_inline_variable
);
7583 NewVD
->setInlineSpecified();
7587 // Set the lexical context. If the declarator has a C++ scope specifier, the
7588 // lexical context will be different from the semantic context.
7589 NewVD
->setLexicalDeclContext(CurContext
);
7591 NewTemplate
->setLexicalDeclContext(CurContext
);
7593 if (IsLocalExternDecl
) {
7594 if (D
.isDecompositionDeclarator())
7595 for (auto *B
: Bindings
)
7596 B
->setLocalExternDecl();
7598 NewVD
->setLocalExternDecl();
7601 bool EmitTLSUnsupportedError
= false;
7602 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec()) {
7603 // C++11 [dcl.stc]p4:
7604 // When thread_local is applied to a variable of block scope the
7605 // storage-class-specifier static is implied if it does not appear
7607 // Core issue: 'static' is not implied if the variable is declared
7609 if (NewVD
->hasLocalStorage() &&
7610 (SCSpec
!= DeclSpec::SCS_unspecified
||
7611 TSCS
!= DeclSpec::TSCS_thread_local
||
7612 !DC
->isFunctionOrMethod()))
7613 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7614 diag::err_thread_non_global
)
7615 << DeclSpec::getSpecifierName(TSCS
);
7616 else if (!Context
.getTargetInfo().isTLSSupported()) {
7617 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsDevice
||
7618 getLangOpts().SYCLIsDevice
) {
7619 // Postpone error emission until we've collected attributes required to
7620 // figure out whether it's a host or device variable and whether the
7621 // error should be ignored.
7622 EmitTLSUnsupportedError
= true;
7623 // We still need to mark the variable as TLS so it shows up in AST with
7624 // proper storage class for other tools to use even if we're not going
7625 // to emit any code for it.
7626 NewVD
->setTSCSpec(TSCS
);
7628 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7629 diag::err_thread_unsupported
);
7631 NewVD
->setTSCSpec(TSCS
);
7634 switch (D
.getDeclSpec().getConstexprSpecifier()) {
7635 case ConstexprSpecKind::Unspecified
:
7638 case ConstexprSpecKind::Consteval
:
7639 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7640 diag::err_constexpr_wrong_decl_kind
)
7641 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
7644 case ConstexprSpecKind::Constexpr
:
7645 NewVD
->setConstexpr(true);
7646 // C++1z [dcl.spec.constexpr]p1:
7647 // A static data member declared with the constexpr specifier is
7648 // implicitly an inline variable.
7649 if (NewVD
->isStaticDataMember() &&
7650 (getLangOpts().CPlusPlus17
||
7651 Context
.getTargetInfo().getCXXABI().isMicrosoft()))
7652 NewVD
->setImplicitlyInline();
7655 case ConstexprSpecKind::Constinit
:
7656 if (!NewVD
->hasGlobalStorage())
7657 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7658 diag::err_constinit_local_variable
);
7660 NewVD
->addAttr(ConstInitAttr::Create(
7661 Context
, D
.getDeclSpec().getConstexprSpecLoc(),
7662 AttributeCommonInfo::AS_Keyword
, ConstInitAttr::Keyword_constinit
));
7667 // An inline definition of a function with external linkage shall
7668 // not contain a definition of a modifiable object with static or
7669 // thread storage duration...
7670 // We only apply this when the function is required to be defined
7671 // elsewhere, i.e. when the function is not 'extern inline'. Note
7672 // that a local variable with thread storage duration still has to
7673 // be marked 'static'. Also note that it's possible to get these
7674 // semantics in C++ using __attribute__((gnu_inline)).
7675 if (SC
== SC_Static
&& S
->getFnParent() != nullptr &&
7676 !NewVD
->getType().isConstQualified()) {
7677 FunctionDecl
*CurFD
= getCurFunctionDecl();
7678 if (CurFD
&& isFunctionDefinitionDiscarded(*this, CurFD
)) {
7679 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7680 diag::warn_static_local_in_extern_inline
);
7681 MaybeSuggestAddingStaticToDecl(CurFD
);
7685 if (D
.getDeclSpec().isModulePrivateSpecified()) {
7686 if (IsVariableTemplateSpecialization
)
7687 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7688 << (IsPartialSpecialization
? 1 : 0)
7689 << FixItHint::CreateRemoval(
7690 D
.getDeclSpec().getModulePrivateSpecLoc());
7691 else if (IsMemberSpecialization
)
7692 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7694 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
7695 else if (NewVD
->hasLocalStorage())
7696 Diag(NewVD
->getLocation(), diag::err_module_private_local
)
7698 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
7699 << FixItHint::CreateRemoval(
7700 D
.getDeclSpec().getModulePrivateSpecLoc());
7702 NewVD
->setModulePrivate();
7704 NewTemplate
->setModulePrivate();
7705 for (auto *B
: Bindings
)
7706 B
->setModulePrivate();
7710 if (getLangOpts().OpenCL
) {
7711 deduceOpenCLAddressSpace(NewVD
);
7713 DeclSpec::TSCS TSC
= D
.getDeclSpec().getThreadStorageClassSpec();
7714 if (TSC
!= TSCS_unspecified
) {
7715 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7716 diag::err_opencl_unknown_type_specifier
)
7717 << getLangOpts().getOpenCLVersionString()
7718 << DeclSpec::getSpecifierName(TSC
) << 1;
7719 NewVD
->setInvalidDecl();
7723 // Handle attributes prior to checking for duplicates in MergeVarDecl
7724 ProcessDeclAttributes(S
, NewVD
, D
);
7726 // FIXME: This is probably the wrong location to be doing this and we should
7727 // probably be doing this for more attributes (especially for function
7728 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7729 // the code to copy attributes would be generated by TableGen.
7730 if (R
->isFunctionPointerType())
7731 if (const auto *TT
= R
->getAs
<TypedefType
>())
7732 copyAttrFromTypedefToDecl
<AllocSizeAttr
>(*this, NewVD
, TT
);
7734 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsDevice
||
7735 getLangOpts().SYCLIsDevice
) {
7736 if (EmitTLSUnsupportedError
&&
7737 ((getLangOpts().CUDA
&& DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) ||
7738 (getLangOpts().OpenMPIsDevice
&&
7739 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD
))))
7740 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7741 diag::err_thread_unsupported
);
7743 if (EmitTLSUnsupportedError
&&
7744 (LangOpts
.SYCLIsDevice
|| (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsDevice
)))
7745 targetDiag(D
.getIdentifierLoc(), diag::err_thread_unsupported
);
7746 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7747 // storage [duration]."
7748 if (SC
== SC_None
&& S
->getFnParent() != nullptr &&
7749 (NewVD
->hasAttr
<CUDASharedAttr
>() ||
7750 NewVD
->hasAttr
<CUDAConstantAttr
>())) {
7751 NewVD
->setStorageClass(SC_Static
);
7755 // Ensure that dllimport globals without explicit storage class are treated as
7756 // extern. The storage class is set above using parsed attributes. Now we can
7757 // check the VarDecl itself.
7758 assert(!NewVD
->hasAttr
<DLLImportAttr
>() ||
7759 NewVD
->getAttr
<DLLImportAttr
>()->isInherited() ||
7760 NewVD
->isStaticDataMember() || NewVD
->getStorageClass() != SC_None
);
7762 // In auto-retain/release, infer strong retension for variables of
7764 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewVD
))
7765 NewVD
->setInvalidDecl();
7767 // Handle GNU asm-label extension (encoded as an attribute).
7768 if (Expr
*E
= (Expr
*)D
.getAsmLabel()) {
7769 // The parser guarantees this is a string.
7770 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
7771 StringRef Label
= SE
->getString();
7772 if (S
->getFnParent() != nullptr) {
7776 Diag(E
->getExprLoc(), diag::warn_asm_label_on_auto_decl
) << Label
;
7779 // Local Named register
7780 if (!Context
.getTargetInfo().isValidGCCRegisterName(Label
) &&
7781 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7782 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
7786 case SC_PrivateExtern
:
7789 } else if (SC
== SC_Register
) {
7790 // Global Named register
7791 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) {
7792 const auto &TI
= Context
.getTargetInfo();
7793 bool HasSizeMismatch
;
7795 if (!TI
.isValidGCCRegisterName(Label
))
7796 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
7797 else if (!TI
.validateGlobalRegisterVariable(Label
,
7798 Context
.getTypeSize(R
),
7800 Diag(E
->getExprLoc(), diag::err_asm_invalid_global_var_reg
) << Label
;
7801 else if (HasSizeMismatch
)
7802 Diag(E
->getExprLoc(), diag::err_asm_register_size_mismatch
) << Label
;
7805 if (!R
->isIntegralType(Context
) && !R
->isPointerType()) {
7806 Diag(D
.getBeginLoc(), diag::err_asm_bad_register_type
);
7807 NewVD
->setInvalidDecl(true);
7811 NewVD
->addAttr(AsmLabelAttr::Create(Context
, Label
,
7812 /*IsLiteralLabel=*/true,
7813 SE
->getStrTokenLoc(0)));
7814 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
7815 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
7816 ExtnameUndeclaredIdentifiers
.find(NewVD
->getIdentifier());
7817 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
7818 if (isDeclExternC(NewVD
)) {
7819 NewVD
->addAttr(I
->second
);
7820 ExtnameUndeclaredIdentifiers
.erase(I
);
7822 Diag(NewVD
->getLocation(), diag::warn_redefine_extname_not_applied
)
7823 << /*Variable*/1 << NewVD
;
7827 // Find the shadowed declaration before filtering for scope.
7828 NamedDecl
*ShadowedDecl
= D
.getCXXScopeSpec().isEmpty()
7829 ? getShadowedDeclaration(NewVD
, Previous
)
7832 // Don't consider existing declarations that are in a different
7833 // scope and are out-of-semantic-context declarations (if the new
7834 // declaration has linkage).
7835 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewVD
),
7836 D
.getCXXScopeSpec().isNotEmpty() ||
7837 IsMemberSpecialization
||
7838 IsVariableTemplateSpecialization
);
7840 // Check whether the previous declaration is in the same block scope. This
7841 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7842 if (getLangOpts().CPlusPlus
&&
7843 NewVD
->isLocalVarDecl() && NewVD
->hasExternalStorage())
7844 NewVD
->setPreviousDeclInSameBlockScope(
7845 Previous
.isSingleResult() && !Previous
.isShadowed() &&
7846 isDeclInScope(Previous
.getFoundDecl(), OriginalDC
, S
, false));
7848 if (!getLangOpts().CPlusPlus
) {
7849 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
7851 // If this is an explicit specialization of a static data member, check it.
7852 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl() &&
7853 CheckMemberSpecialization(NewVD
, Previous
))
7854 NewVD
->setInvalidDecl();
7856 // Merge the decl with the existing one if appropriate.
7857 if (!Previous
.empty()) {
7858 if (Previous
.isSingleResult() &&
7859 isa
<FieldDecl
>(Previous
.getFoundDecl()) &&
7860 D
.getCXXScopeSpec().isSet()) {
7861 // The user tried to define a non-static data member
7862 // out-of-line (C++ [dcl.meaning]p1).
7863 Diag(NewVD
->getLocation(), diag::err_nonstatic_member_out_of_line
)
7864 << D
.getCXXScopeSpec().getRange();
7866 NewVD
->setInvalidDecl();
7868 } else if (D
.getCXXScopeSpec().isSet()) {
7869 // No previous declaration in the qualifying scope.
7870 Diag(D
.getIdentifierLoc(), diag::err_no_member
)
7871 << Name
<< computeDeclContext(D
.getCXXScopeSpec(), true)
7872 << D
.getCXXScopeSpec().getRange();
7873 NewVD
->setInvalidDecl();
7876 if (!IsVariableTemplateSpecialization
)
7877 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
7880 VarTemplateDecl
*PrevVarTemplate
=
7881 NewVD
->getPreviousDecl()
7882 ? NewVD
->getPreviousDecl()->getDescribedVarTemplate()
7885 // Check the template parameter list of this declaration, possibly
7886 // merging in the template parameter list from the previous variable
7887 // template declaration.
7888 if (CheckTemplateParameterList(
7890 PrevVarTemplate
? PrevVarTemplate
->getTemplateParameters()
7892 (D
.getCXXScopeSpec().isSet() && DC
&& DC
->isRecord() &&
7893 DC
->isDependentContext())
7894 ? TPC_ClassTemplateMember
7896 NewVD
->setInvalidDecl();
7898 // If we are providing an explicit specialization of a static variable
7899 // template, make a note of that.
7900 if (PrevVarTemplate
&&
7901 PrevVarTemplate
->getInstantiatedFromMemberTemplate())
7902 PrevVarTemplate
->setMemberSpecialization();
7906 // Diagnose shadowed variables iff this isn't a redeclaration.
7907 if (ShadowedDecl
&& !D
.isRedeclaration())
7908 CheckShadow(NewVD
, ShadowedDecl
, Previous
);
7910 ProcessPragmaWeak(S
, NewVD
);
7912 // If this is the first declaration of an extern C variable, update
7913 // the map of such variables.
7914 if (NewVD
->isFirstDecl() && !NewVD
->isInvalidDecl() &&
7915 isIncompleteDeclExternC(*this, NewVD
))
7916 RegisterLocallyScopedExternCDecl(NewVD
, S
);
7918 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
7919 MangleNumberingContext
*MCtx
;
7920 Decl
*ManglingContextDecl
;
7921 std::tie(MCtx
, ManglingContextDecl
) =
7922 getCurrentMangleNumberContext(NewVD
->getDeclContext());
7924 Context
.setManglingNumber(
7925 NewVD
, MCtx
->getManglingNumber(
7926 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
7927 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
7931 // Special handling of variable named 'main'.
7932 if (Name
.getAsIdentifierInfo() && Name
.getAsIdentifierInfo()->isStr("main") &&
7933 NewVD
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7934 !getLangOpts().Freestanding
&& !NewVD
->getDescribedVarTemplate()) {
7936 // C++ [basic.start.main]p3
7937 // A program that declares a variable main at global scope is ill-formed.
7938 if (getLangOpts().CPlusPlus
)
7939 Diag(D
.getBeginLoc(), diag::err_main_global_variable
);
7941 // In C, and external-linkage variable named main results in undefined
7943 else if (NewVD
->hasExternalFormalLinkage())
7944 Diag(D
.getBeginLoc(), diag::warn_main_redefined
);
7947 if (D
.isRedeclaration() && !Previous
.empty()) {
7948 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
7949 checkDLLAttributeRedeclaration(*this, Prev
, NewVD
, IsMemberSpecialization
,
7950 D
.isFunctionDefinition());
7954 if (NewVD
->isInvalidDecl())
7955 NewTemplate
->setInvalidDecl();
7956 ActOnDocumentableDecl(NewTemplate
);
7960 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl())
7961 CompleteMemberSpecialization(NewVD
, Previous
);
7966 /// Enum describing the %select options in diag::warn_decl_shadow.
7967 enum ShadowedDeclKind
{
7974 SDK_StructuredBinding
7977 /// Determine what kind of declaration we're shadowing.
7978 static ShadowedDeclKind
computeShadowedDeclKind(const NamedDecl
*ShadowedDecl
,
7979 const DeclContext
*OldDC
) {
7980 if (isa
<TypeAliasDecl
>(ShadowedDecl
))
7982 else if (isa
<TypedefDecl
>(ShadowedDecl
))
7984 else if (isa
<BindingDecl
>(ShadowedDecl
))
7985 return SDK_StructuredBinding
;
7986 else if (isa
<RecordDecl
>(OldDC
))
7987 return isa
<FieldDecl
>(ShadowedDecl
) ? SDK_Field
: SDK_StaticMember
;
7989 return OldDC
->isFileContext() ? SDK_Global
: SDK_Local
;
7992 /// Return the location of the capture if the given lambda captures the given
7993 /// variable \p VD, or an invalid source location otherwise.
7994 static SourceLocation
getCaptureLocation(const LambdaScopeInfo
*LSI
,
7995 const VarDecl
*VD
) {
7996 for (const Capture
&Capture
: LSI
->Captures
) {
7997 if (Capture
.isVariableCapture() && Capture
.getVariable() == VD
)
7998 return Capture
.getLocation();
8000 return SourceLocation();
8003 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine
&Diags
,
8004 const LookupResult
&R
) {
8005 // Only diagnose if we're shadowing an unambiguous field or variable.
8006 if (R
.getResultKind() != LookupResult::Found
)
8009 // Return false if warning is ignored.
8010 return !Diags
.isIgnored(diag::warn_decl_shadow
, R
.getNameLoc());
8013 /// Return the declaration shadowed by the given variable \p D, or null
8014 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8015 NamedDecl
*Sema::getShadowedDeclaration(const VarDecl
*D
,
8016 const LookupResult
&R
) {
8017 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8020 // Don't diagnose declarations at file scope.
8021 if (D
->hasGlobalStorage())
8024 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8025 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8029 /// Return the declaration shadowed by the given typedef \p D, or null
8030 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8031 NamedDecl
*Sema::getShadowedDeclaration(const TypedefNameDecl
*D
,
8032 const LookupResult
&R
) {
8033 // Don't warn if typedef declaration is part of a class
8034 if (D
->getDeclContext()->isRecord())
8037 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8040 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8041 return isa
<TypedefNameDecl
>(ShadowedDecl
) ? ShadowedDecl
: nullptr;
8044 /// Return the declaration shadowed by the given variable \p D, or null
8045 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8046 NamedDecl
*Sema::getShadowedDeclaration(const BindingDecl
*D
,
8047 const LookupResult
&R
) {
8048 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8051 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8052 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8056 /// Diagnose variable or built-in function shadowing. Implements
8059 /// This method is called whenever a VarDecl is added to a "useful"
8062 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8063 /// \param R the lookup of the name
8065 void Sema::CheckShadow(NamedDecl
*D
, NamedDecl
*ShadowedDecl
,
8066 const LookupResult
&R
) {
8067 DeclContext
*NewDC
= D
->getDeclContext();
8069 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ShadowedDecl
)) {
8070 // Fields are not shadowed by variables in C++ static methods.
8071 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDC
))
8075 // Fields shadowed by constructor parameters are a special case. Usually
8076 // the constructor initializes the field with the parameter.
8077 if (isa
<CXXConstructorDecl
>(NewDC
))
8078 if (const auto PVD
= dyn_cast
<ParmVarDecl
>(D
)) {
8079 // Remember that this was shadowed so we can either warn about its
8080 // modification or its existence depending on warning settings.
8081 ShadowingDecls
.insert({PVD
->getCanonicalDecl(), FD
});
8086 if (VarDecl
*shadowedVar
= dyn_cast
<VarDecl
>(ShadowedDecl
))
8087 if (shadowedVar
->isExternC()) {
8088 // For shadowing external vars, make sure that we point to the global
8089 // declaration, not a locally scoped extern declaration.
8090 for (auto *I
: shadowedVar
->redecls())
8091 if (I
->isFileVarDecl()) {
8097 DeclContext
*OldDC
= ShadowedDecl
->getDeclContext()->getRedeclContext();
8099 unsigned WarningDiag
= diag::warn_decl_shadow
;
8100 SourceLocation CaptureLoc
;
8101 if (isa
<VarDecl
>(D
) && isa
<VarDecl
>(ShadowedDecl
) && NewDC
&&
8102 isa
<CXXMethodDecl
>(NewDC
)) {
8103 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(NewDC
->getParent())) {
8104 if (RD
->isLambda() && OldDC
->Encloses(NewDC
->getLexicalParent())) {
8105 if (RD
->getLambdaCaptureDefault() == LCD_None
) {
8106 // Try to avoid warnings for lambdas with an explicit capture list.
8107 const auto *LSI
= cast
<LambdaScopeInfo
>(getCurFunction());
8108 // Warn only when the lambda captures the shadowed decl explicitly.
8109 CaptureLoc
= getCaptureLocation(LSI
, cast
<VarDecl
>(ShadowedDecl
));
8110 if (CaptureLoc
.isInvalid())
8111 WarningDiag
= diag::warn_decl_shadow_uncaptured_local
;
8113 // Remember that this was shadowed so we can avoid the warning if the
8114 // shadowed decl isn't captured and the warning settings allow it.
8115 cast
<LambdaScopeInfo
>(getCurFunction())
8116 ->ShadowingDecls
.push_back(
8117 {cast
<VarDecl
>(D
), cast
<VarDecl
>(ShadowedDecl
)});
8122 if (cast
<VarDecl
>(ShadowedDecl
)->hasLocalStorage()) {
8123 // A variable can't shadow a local variable in an enclosing scope, if
8124 // they are separated by a non-capturing declaration context.
8125 for (DeclContext
*ParentDC
= NewDC
;
8126 ParentDC
&& !ParentDC
->Equals(OldDC
);
8127 ParentDC
= getLambdaAwareParentOfDeclContext(ParentDC
)) {
8128 // Only block literals, captured statements, and lambda expressions
8129 // can capture; other scopes don't.
8130 if (!isa
<BlockDecl
>(ParentDC
) && !isa
<CapturedDecl
>(ParentDC
) &&
8131 !isLambdaCallOperator(ParentDC
)) {
8139 // Only warn about certain kinds of shadowing for class members.
8140 if (NewDC
&& NewDC
->isRecord()) {
8141 // In particular, don't warn about shadowing non-class members.
8142 if (!OldDC
->isRecord())
8145 // TODO: should we warn about static data members shadowing
8146 // static data members from base classes?
8148 // TODO: don't diagnose for inaccessible shadowed members.
8149 // This is hard to do perfectly because we might friend the
8150 // shadowing context, but that's just a false negative.
8154 DeclarationName Name
= R
.getLookupName();
8156 // Emit warning and note.
8157 ShadowedDeclKind Kind
= computeShadowedDeclKind(ShadowedDecl
, OldDC
);
8158 Diag(R
.getNameLoc(), WarningDiag
) << Name
<< Kind
<< OldDC
;
8159 if (!CaptureLoc
.isInvalid())
8160 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8161 << Name
<< /*explicitly*/ 1;
8162 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8165 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8166 /// when these variables are captured by the lambda.
8167 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo
*LSI
) {
8168 for (const auto &Shadow
: LSI
->ShadowingDecls
) {
8169 const VarDecl
*ShadowedDecl
= Shadow
.ShadowedDecl
;
8170 // Try to avoid the warning when the shadowed decl isn't captured.
8171 SourceLocation CaptureLoc
= getCaptureLocation(LSI
, ShadowedDecl
);
8172 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8173 Diag(Shadow
.VD
->getLocation(), CaptureLoc
.isInvalid()
8174 ? diag::warn_decl_shadow_uncaptured_local
8175 : diag::warn_decl_shadow
)
8176 << Shadow
.VD
->getDeclName()
8177 << computeShadowedDeclKind(ShadowedDecl
, OldDC
) << OldDC
;
8178 if (!CaptureLoc
.isInvalid())
8179 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8180 << Shadow
.VD
->getDeclName() << /*explicitly*/ 0;
8181 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8185 /// Check -Wshadow without the advantage of a previous lookup.
8186 void Sema::CheckShadow(Scope
*S
, VarDecl
*D
) {
8187 if (Diags
.isIgnored(diag::warn_decl_shadow
, D
->getLocation()))
8190 LookupResult
R(*this, D
->getDeclName(), D
->getLocation(),
8191 Sema::LookupOrdinaryName
, Sema::ForVisibleRedeclaration
);
8193 if (NamedDecl
*ShadowedDecl
= getShadowedDeclaration(D
, R
))
8194 CheckShadow(D
, ShadowedDecl
, R
);
8197 /// Check if 'E', which is an expression that is about to be modified, refers
8198 /// to a constructor parameter that shadows a field.
8199 void Sema::CheckShadowingDeclModification(Expr
*E
, SourceLocation Loc
) {
8200 // Quickly ignore expressions that can't be shadowing ctor parameters.
8201 if (!getLangOpts().CPlusPlus
|| ShadowingDecls
.empty())
8203 E
= E
->IgnoreParenImpCasts();
8204 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
);
8207 const NamedDecl
*D
= cast
<NamedDecl
>(DRE
->getDecl()->getCanonicalDecl());
8208 auto I
= ShadowingDecls
.find(D
);
8209 if (I
== ShadowingDecls
.end())
8211 const NamedDecl
*ShadowedDecl
= I
->second
;
8212 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8213 Diag(Loc
, diag::warn_modifying_shadowing_decl
) << D
<< OldDC
;
8214 Diag(D
->getLocation(), diag::note_var_declared_here
) << D
;
8215 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8217 // Avoid issuing multiple warnings about the same decl.
8218 ShadowingDecls
.erase(I
);
8221 /// Check for conflict between this global or extern "C" declaration and
8222 /// previous global or extern "C" declarations. This is only used in C++.
8223 template<typename T
>
8224 static bool checkGlobalOrExternCConflict(
8225 Sema
&S
, const T
*ND
, bool IsGlobal
, LookupResult
&Previous
) {
8226 assert(S
.getLangOpts().CPlusPlus
&& "only C++ has extern \"C\"");
8227 NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName());
8229 if (!Prev
&& IsGlobal
&& !isIncompleteDeclExternC(S
, ND
)) {
8230 // The common case: this global doesn't conflict with any extern "C"
8236 if (!IsGlobal
|| isIncompleteDeclExternC(S
, ND
)) {
8237 // Both the old and new declarations have C language linkage. This is a
8240 Previous
.addDecl(Prev
);
8244 // This is a global, non-extern "C" declaration, and there is a previous
8245 // non-global extern "C" declaration. Diagnose if this is a variable
8247 if (!isa
<VarDecl
>(ND
))
8250 // The declaration is extern "C". Check for any declaration in the
8251 // translation unit which might conflict.
8253 // We have already performed the lookup into the translation unit.
8255 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
8257 if (isa
<VarDecl
>(*I
)) {
8263 DeclContext::lookup_result R
=
8264 S
.Context
.getTranslationUnitDecl()->lookup(ND
->getDeclName());
8265 for (DeclContext::lookup_result::iterator I
= R
.begin(), E
= R
.end();
8267 if (isa
<VarDecl
>(*I
)) {
8271 // FIXME: If we have any other entity with this name in global scope,
8272 // the declaration is ill-formed, but that is a defect: it breaks the
8273 // 'stat' hack, for instance. Only variables can have mangled name
8274 // clashes with extern "C" declarations, so only they deserve a
8283 // Use the first declaration's location to ensure we point at something which
8284 // is lexically inside an extern "C" linkage-spec.
8285 assert(Prev
&& "should have found a previous declaration to diagnose");
8286 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(Prev
))
8287 Prev
= FD
->getFirstDecl();
8289 Prev
= cast
<VarDecl
>(Prev
)->getFirstDecl();
8291 S
.Diag(ND
->getLocation(), diag::err_extern_c_global_conflict
)
8293 S
.Diag(Prev
->getLocation(), diag::note_extern_c_global_conflict
)
8298 /// Apply special rules for handling extern "C" declarations. Returns \c true
8299 /// if we have found that this is a redeclaration of some prior entity.
8301 /// Per C++ [dcl.link]p6:
8302 /// Two declarations [for a function or variable] with C language linkage
8303 /// with the same name that appear in different scopes refer to the same
8304 /// [entity]. An entity with C language linkage shall not be declared with
8305 /// the same name as an entity in global scope.
8306 template<typename T
>
8307 static bool checkForConflictWithNonVisibleExternC(Sema
&S
, const T
*ND
,
8308 LookupResult
&Previous
) {
8309 if (!S
.getLangOpts().CPlusPlus
) {
8310 // In C, when declaring a global variable, look for a corresponding 'extern'
8311 // variable declared in function scope. We don't need this in C++, because
8312 // we find local extern decls in the surrounding file-scope DeclContext.
8313 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8314 if (NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName())) {
8316 Previous
.addDecl(Prev
);
8323 // A declaration in the translation unit can conflict with an extern "C"
8325 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit())
8326 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/true, Previous
);
8328 // An extern "C" declaration can conflict with a declaration in the
8329 // translation unit or can be a redeclaration of an extern "C" declaration
8330 // in another scope.
8331 if (isIncompleteDeclExternC(S
,ND
))
8332 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/false, Previous
);
8334 // Neither global nor extern "C": nothing to do.
8338 void Sema::CheckVariableDeclarationType(VarDecl
*NewVD
) {
8339 // If the decl is already known invalid, don't check it.
8340 if (NewVD
->isInvalidDecl())
8343 QualType T
= NewVD
->getType();
8345 // Defer checking an 'auto' type until its initializer is attached.
8346 if (T
->isUndeducedType())
8349 if (NewVD
->hasAttrs())
8350 CheckAlignasUnderalignment(NewVD
);
8352 if (T
->isObjCObjectType()) {
8353 Diag(NewVD
->getLocation(), diag::err_statically_allocated_object
)
8354 << FixItHint::CreateInsertion(NewVD
->getLocation(), "*");
8355 T
= Context
.getObjCObjectPointerType(T
);
8359 // Emit an error if an address space was applied to decl with local storage.
8360 // This includes arrays of objects with address space qualifiers, but not
8361 // automatic variables that point to other address spaces.
8362 // ISO/IEC TR 18037 S5.1.2
8363 if (!getLangOpts().OpenCL
&& NewVD
->hasLocalStorage() &&
8364 T
.getAddressSpace() != LangAS::Default
) {
8365 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 0;
8366 NewVD
->setInvalidDecl();
8370 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8372 if (getLangOpts().OpenCLVersion
== 120 &&
8373 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8375 NewVD
->isStaticLocal()) {
8376 Diag(NewVD
->getLocation(), diag::err_static_function_scope
);
8377 NewVD
->setInvalidDecl();
8381 if (getLangOpts().OpenCL
) {
8382 if (!diagnoseOpenCLTypes(*this, NewVD
))
8385 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8386 if (NewVD
->hasAttr
<BlocksAttr
>()) {
8387 Diag(NewVD
->getLocation(), diag::err_opencl_block_storage_type
);
8391 if (T
->isBlockPointerType()) {
8392 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8393 // can't use 'extern' storage class.
8394 if (!T
.isConstQualified()) {
8395 Diag(NewVD
->getLocation(), diag::err_opencl_invalid_block_declaration
)
8397 NewVD
->setInvalidDecl();
8400 if (NewVD
->hasExternalStorage()) {
8401 Diag(NewVD
->getLocation(), diag::err_opencl_extern_block_declaration
);
8402 NewVD
->setInvalidDecl();
8407 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8408 if (NewVD
->isFileVarDecl() || NewVD
->isStaticLocal() ||
8409 NewVD
->hasExternalStorage()) {
8410 if (!T
->isSamplerT() && !T
->isDependentType() &&
8411 !(T
.getAddressSpace() == LangAS::opencl_constant
||
8412 (T
.getAddressSpace() == LangAS::opencl_global
&&
8413 getOpenCLOptions().areProgramScopeVariablesSupported(
8415 int Scope
= NewVD
->isStaticLocal() | NewVD
->hasExternalStorage() << 1;
8416 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8417 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8418 << Scope
<< "global or constant";
8420 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8421 << Scope
<< "constant";
8422 NewVD
->setInvalidDecl();
8426 if (T
.getAddressSpace() == LangAS::opencl_global
) {
8427 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8428 << 1 /*is any function*/ << "global";
8429 NewVD
->setInvalidDecl();
8432 if (T
.getAddressSpace() == LangAS::opencl_constant
||
8433 T
.getAddressSpace() == LangAS::opencl_local
) {
8434 FunctionDecl
*FD
= getCurFunctionDecl();
8435 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8437 if (FD
&& !FD
->hasAttr
<OpenCLKernelAttr
>()) {
8438 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8439 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8440 << 0 /*non-kernel only*/ << "constant";
8442 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8443 << 0 /*non-kernel only*/ << "local";
8444 NewVD
->setInvalidDecl();
8447 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8448 // in the outermost scope of a kernel function.
8449 if (FD
&& FD
->hasAttr
<OpenCLKernelAttr
>()) {
8450 if (!getCurScope()->isFunctionScope()) {
8451 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8452 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8455 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8457 NewVD
->setInvalidDecl();
8461 } else if (T
.getAddressSpace() != LangAS::opencl_private
&&
8462 // If we are parsing a template we didn't deduce an addr
8464 T
.getAddressSpace() != LangAS::Default
) {
8465 // Do not allow other address spaces on automatic variable.
8466 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 1;
8467 NewVD
->setInvalidDecl();
8473 if (NewVD
->hasLocalStorage() && T
.isObjCGCWeak()
8474 && !NewVD
->hasAttr
<BlocksAttr
>()) {
8475 if (getLangOpts().getGC() != LangOptions::NonGC
)
8476 Diag(NewVD
->getLocation(), diag::warn_gc_attribute_weak_on_local
);
8478 assert(!getLangOpts().ObjCAutoRefCount
);
8479 Diag(NewVD
->getLocation(), diag::warn_attribute_weak_on_local
);
8483 bool isVM
= T
->isVariablyModifiedType();
8484 if (isVM
|| NewVD
->hasAttr
<CleanupAttr
>() ||
8485 NewVD
->hasAttr
<BlocksAttr
>())
8486 setFunctionHasBranchProtectedScope();
8488 if ((isVM
&& NewVD
->hasLinkage()) ||
8489 (T
->isVariableArrayType() && NewVD
->hasGlobalStorage())) {
8490 bool SizeIsNegative
;
8491 llvm::APSInt Oversized
;
8492 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
8493 NewVD
->getTypeSourceInfo(), Context
, SizeIsNegative
, Oversized
);
8495 if (FixedTInfo
&& T
== NewVD
->getTypeSourceInfo()->getType())
8496 FixedT
= FixedTInfo
->getType();
8497 else if (FixedTInfo
) {
8498 // Type and type-as-written are canonically different. We need to fix up
8499 // both types separately.
8500 FixedT
= TryToFixInvalidVariablyModifiedType(T
, Context
, SizeIsNegative
,
8503 if ((!FixedTInfo
|| FixedT
.isNull()) && T
->isVariableArrayType()) {
8504 const VariableArrayType
*VAT
= Context
.getAsVariableArrayType(T
);
8505 // FIXME: This won't give the correct result for
8507 SourceRange SizeRange
= VAT
->getSizeExpr()->getSourceRange();
8509 if (NewVD
->isFileVarDecl())
8510 Diag(NewVD
->getLocation(), diag::err_vla_decl_in_file_scope
)
8512 else if (NewVD
->isStaticLocal())
8513 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_static_storage
)
8516 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_extern_linkage
)
8518 NewVD
->setInvalidDecl();
8523 if (NewVD
->isFileVarDecl())
8524 Diag(NewVD
->getLocation(), diag::err_vm_decl_in_file_scope
);
8526 Diag(NewVD
->getLocation(), diag::err_vm_decl_has_extern_linkage
);
8527 NewVD
->setInvalidDecl();
8531 Diag(NewVD
->getLocation(), diag::ext_vla_folded_to_constant
);
8532 NewVD
->setType(FixedT
);
8533 NewVD
->setTypeSourceInfo(FixedTInfo
);
8536 if (T
->isVoidType()) {
8537 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8538 // of objects and functions.
8539 if (NewVD
->isThisDeclarationADefinition() || getLangOpts().CPlusPlus
) {
8540 Diag(NewVD
->getLocation(), diag::err_typecheck_decl_incomplete_type
)
8542 NewVD
->setInvalidDecl();
8547 if (!NewVD
->hasLocalStorage() && NewVD
->hasAttr
<BlocksAttr
>()) {
8548 Diag(NewVD
->getLocation(), diag::err_block_on_nonlocal
);
8549 NewVD
->setInvalidDecl();
8553 if (!NewVD
->hasLocalStorage() && T
->isSizelessType()) {
8554 Diag(NewVD
->getLocation(), diag::err_sizeless_nonlocal
) << T
;
8555 NewVD
->setInvalidDecl();
8559 if (isVM
&& NewVD
->hasAttr
<BlocksAttr
>()) {
8560 Diag(NewVD
->getLocation(), diag::err_block_on_vm
);
8561 NewVD
->setInvalidDecl();
8565 if (NewVD
->isConstexpr() && !T
->isDependentType() &&
8566 RequireLiteralType(NewVD
->getLocation(), T
,
8567 diag::err_constexpr_var_non_literal
)) {
8568 NewVD
->setInvalidDecl();
8572 // PPC MMA non-pointer types are not allowed as non-local variable types.
8573 if (Context
.getTargetInfo().getTriple().isPPC64() &&
8574 !NewVD
->isLocalVarDecl() &&
8575 CheckPPCMMAType(T
, NewVD
->getLocation())) {
8576 NewVD
->setInvalidDecl();
8581 /// Perform semantic checking on a newly-created variable
8584 /// This routine performs all of the type-checking required for a
8585 /// variable declaration once it has been built. It is used both to
8586 /// check variables after they have been parsed and their declarators
8587 /// have been translated into a declaration, and to check variables
8588 /// that have been instantiated from a template.
8590 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8592 /// Returns true if the variable declaration is a redeclaration.
8593 bool Sema::CheckVariableDeclaration(VarDecl
*NewVD
, LookupResult
&Previous
) {
8594 CheckVariableDeclarationType(NewVD
);
8596 // If the decl is already known invalid, don't check it.
8597 if (NewVD
->isInvalidDecl())
8600 // If we did not find anything by this name, look for a non-visible
8601 // extern "C" declaration with the same name.
8602 if (Previous
.empty() &&
8603 checkForConflictWithNonVisibleExternC(*this, NewVD
, Previous
))
8604 Previous
.setShadowed();
8606 if (!Previous
.empty()) {
8607 MergeVarDecl(NewVD
, Previous
);
8613 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8614 /// and if so, check that it's a valid override and remember it.
8615 bool Sema::AddOverriddenMethods(CXXRecordDecl
*DC
, CXXMethodDecl
*MD
) {
8616 llvm::SmallPtrSet
<const CXXMethodDecl
*, 4> Overridden
;
8618 // Look for methods in base classes that this method might override.
8619 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8620 /*DetectVirtual=*/false);
8621 auto VisitBase
= [&] (const CXXBaseSpecifier
*Specifier
, CXXBasePath
&Path
) {
8622 CXXRecordDecl
*BaseRecord
= Specifier
->getType()->getAsCXXRecordDecl();
8623 DeclarationName Name
= MD
->getDeclName();
8625 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
8626 // We really want to find the base class destructor here.
8627 QualType T
= Context
.getTypeDeclType(BaseRecord
);
8628 CanQualType CT
= Context
.getCanonicalType(T
);
8629 Name
= Context
.DeclarationNames
.getCXXDestructorName(CT
);
8632 for (NamedDecl
*BaseND
: BaseRecord
->lookup(Name
)) {
8633 CXXMethodDecl
*BaseMD
=
8634 dyn_cast
<CXXMethodDecl
>(BaseND
->getCanonicalDecl());
8635 if (!BaseMD
|| !BaseMD
->isVirtual() ||
8636 IsOverload(MD
, BaseMD
, /*UseMemberUsingDeclRules=*/false,
8637 /*ConsiderCudaAttrs=*/true,
8638 // C++2a [class.virtual]p2 does not consider requires
8639 // clauses when overriding.
8640 /*ConsiderRequiresClauses=*/false))
8643 if (Overridden
.insert(BaseMD
).second
) {
8644 MD
->addOverriddenMethod(BaseMD
);
8645 CheckOverridingFunctionReturnType(MD
, BaseMD
);
8646 CheckOverridingFunctionAttributes(MD
, BaseMD
);
8647 CheckOverridingFunctionExceptionSpec(MD
, BaseMD
);
8648 CheckIfOverriddenFunctionIsMarkedFinal(MD
, BaseMD
);
8651 // A method can only override one function from each base class. We
8652 // don't track indirectly overridden methods from bases of bases.
8659 DC
->lookupInBases(VisitBase
, Paths
);
8660 return !Overridden
.empty();
8664 // Struct for holding all of the extra arguments needed by
8665 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8666 struct ActOnFDArgs
{
8669 MultiTemplateParamsArg TemplateParamLists
;
8672 } // end anonymous namespace
8676 // Callback to only accept typo corrections that have a non-zero edit distance.
8677 // Also only accept corrections that have the same parent decl.
8678 class DifferentNameValidatorCCC final
: public CorrectionCandidateCallback
{
8680 DifferentNameValidatorCCC(ASTContext
&Context
, FunctionDecl
*TypoFD
,
8681 CXXRecordDecl
*Parent
)
8682 : Context(Context
), OriginalFD(TypoFD
),
8683 ExpectedParent(Parent
? Parent
->getCanonicalDecl() : nullptr) {}
8685 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
8686 if (candidate
.getEditDistance() == 0)
8689 SmallVector
<unsigned, 1> MismatchedParams
;
8690 for (TypoCorrection::const_decl_iterator CDecl
= candidate
.begin(),
8691 CDeclEnd
= candidate
.end();
8692 CDecl
!= CDeclEnd
; ++CDecl
) {
8693 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
8695 if (FD
&& !FD
->hasBody() &&
8696 hasSimilarParameters(Context
, FD
, OriginalFD
, MismatchedParams
)) {
8697 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
8698 CXXRecordDecl
*Parent
= MD
->getParent();
8699 if (Parent
&& Parent
->getCanonicalDecl() == ExpectedParent
)
8701 } else if (!ExpectedParent
) {
8710 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
8711 return std::make_unique
<DifferentNameValidatorCCC
>(*this);
8715 ASTContext
&Context
;
8716 FunctionDecl
*OriginalFD
;
8717 CXXRecordDecl
*ExpectedParent
;
8720 } // end anonymous namespace
8722 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl
*F
) {
8723 TypoCorrectedFunctionDefinitions
.insert(F
);
8726 /// Generate diagnostics for an invalid function redeclaration.
8728 /// This routine handles generating the diagnostic messages for an invalid
8729 /// function redeclaration, including finding possible similar declarations
8730 /// or performing typo correction if there are no previous declarations with
8733 /// Returns a NamedDecl iff typo correction was performed and substituting in
8734 /// the new declaration name does not cause new errors.
8735 static NamedDecl
*DiagnoseInvalidRedeclaration(
8736 Sema
&SemaRef
, LookupResult
&Previous
, FunctionDecl
*NewFD
,
8737 ActOnFDArgs
&ExtraArgs
, bool IsLocalFriend
, Scope
*S
) {
8738 DeclarationName Name
= NewFD
->getDeclName();
8739 DeclContext
*NewDC
= NewFD
->getDeclContext();
8740 SmallVector
<unsigned, 1> MismatchedParams
;
8741 SmallVector
<std::pair
<FunctionDecl
*, unsigned>, 1> NearMatches
;
8742 TypoCorrection Correction
;
8743 bool IsDefinition
= ExtraArgs
.D
.isFunctionDefinition();
8745 IsLocalFriend
? diag::err_no_matching_local_friend
:
8746 NewFD
->getFriendObjectKind() ? diag::err_qualified_friend_no_match
:
8747 diag::err_member_decl_does_not_match
;
8748 LookupResult
Prev(SemaRef
, Name
, NewFD
->getLocation(),
8749 IsLocalFriend
? Sema::LookupLocalFriendName
8750 : Sema::LookupOrdinaryName
,
8751 Sema::ForVisibleRedeclaration
);
8753 NewFD
->setInvalidDecl();
8755 SemaRef
.LookupName(Prev
, S
);
8757 SemaRef
.LookupQualifiedName(Prev
, NewDC
);
8758 assert(!Prev
.isAmbiguous() &&
8759 "Cannot have an ambiguity in previous-declaration lookup");
8760 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
8761 DifferentNameValidatorCCC
CCC(SemaRef
.Context
, NewFD
,
8762 MD
? MD
->getParent() : nullptr);
8763 if (!Prev
.empty()) {
8764 for (LookupResult::iterator Func
= Prev
.begin(), FuncEnd
= Prev
.end();
8765 Func
!= FuncEnd
; ++Func
) {
8766 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*Func
);
8768 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
8769 // Add 1 to the index so that 0 can mean the mismatch didn't
8770 // involve a parameter
8772 MismatchedParams
.empty() ? 0 : MismatchedParams
.front() + 1;
8773 NearMatches
.push_back(std::make_pair(FD
, ParamNum
));
8776 // If the qualified name lookup yielded nothing, try typo correction
8777 } else if ((Correction
= SemaRef
.CorrectTypo(
8778 Prev
.getLookupNameInfo(), Prev
.getLookupKind(), S
,
8779 &ExtraArgs
.D
.getCXXScopeSpec(), CCC
, Sema::CTK_ErrorRecovery
,
8780 IsLocalFriend
? nullptr : NewDC
))) {
8781 // Set up everything for the call to ActOnFunctionDeclarator
8782 ExtraArgs
.D
.SetIdentifier(Correction
.getCorrectionAsIdentifierInfo(),
8783 ExtraArgs
.D
.getIdentifierLoc());
8785 Previous
.setLookupName(Correction
.getCorrection());
8786 for (TypoCorrection::decl_iterator CDecl
= Correction
.begin(),
8787 CDeclEnd
= Correction
.end();
8788 CDecl
!= CDeclEnd
; ++CDecl
) {
8789 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
8790 if (FD
&& !FD
->hasBody() &&
8791 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
8792 Previous
.addDecl(FD
);
8795 bool wasRedeclaration
= ExtraArgs
.D
.isRedeclaration();
8798 // Retry building the function declaration with the new previous
8799 // declarations, and with errors suppressed.
8802 Sema::SFINAETrap
Trap(SemaRef
);
8804 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8805 // pieces need to verify the typo-corrected C++ declaration and hopefully
8806 // eliminate the need for the parameter pack ExtraArgs.
8807 Result
= SemaRef
.ActOnFunctionDeclarator(
8808 ExtraArgs
.S
, ExtraArgs
.D
,
8809 Correction
.getCorrectionDecl()->getDeclContext(),
8810 NewFD
->getTypeSourceInfo(), Previous
, ExtraArgs
.TemplateParamLists
,
8811 ExtraArgs
.AddToScope
);
8813 if (Trap
.hasErrorOccurred())
8818 // Determine which correction we picked.
8819 Decl
*Canonical
= Result
->getCanonicalDecl();
8820 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
8822 if ((*I
)->getCanonicalDecl() == Canonical
)
8823 Correction
.setCorrectionDecl(*I
);
8825 // Let Sema know about the correction.
8826 SemaRef
.MarkTypoCorrectedFunctionDefinition(Result
);
8827 SemaRef
.diagnoseTypo(
8829 SemaRef
.PDiag(IsLocalFriend
8830 ? diag::err_no_matching_local_friend_suggest
8831 : diag::err_member_decl_does_not_match_suggest
)
8832 << Name
<< NewDC
<< IsDefinition
);
8836 // Pretend the typo correction never occurred
8837 ExtraArgs
.D
.SetIdentifier(Name
.getAsIdentifierInfo(),
8838 ExtraArgs
.D
.getIdentifierLoc());
8839 ExtraArgs
.D
.setRedeclaration(wasRedeclaration
);
8841 Previous
.setLookupName(Name
);
8844 SemaRef
.Diag(NewFD
->getLocation(), DiagMsg
)
8845 << Name
<< NewDC
<< IsDefinition
<< NewFD
->getLocation();
8847 bool NewFDisConst
= false;
8848 if (CXXMethodDecl
*NewMD
= dyn_cast
<CXXMethodDecl
>(NewFD
))
8849 NewFDisConst
= NewMD
->isConst();
8851 for (SmallVectorImpl
<std::pair
<FunctionDecl
*, unsigned> >::iterator
8852 NearMatch
= NearMatches
.begin(), NearMatchEnd
= NearMatches
.end();
8853 NearMatch
!= NearMatchEnd
; ++NearMatch
) {
8854 FunctionDecl
*FD
= NearMatch
->first
;
8855 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
8856 bool FDisConst
= MD
&& MD
->isConst();
8857 bool IsMember
= MD
|| !IsLocalFriend
;
8859 // FIXME: These notes are poorly worded for the local friend case.
8860 if (unsigned Idx
= NearMatch
->second
) {
8861 ParmVarDecl
*FDParam
= FD
->getParamDecl(Idx
-1);
8862 SourceLocation Loc
= FDParam
->getTypeSpecStartLoc();
8863 if (Loc
.isInvalid()) Loc
= FD
->getLocation();
8864 SemaRef
.Diag(Loc
, IsMember
? diag::note_member_def_close_param_match
8865 : diag::note_local_decl_close_param_match
)
8866 << Idx
<< FDParam
->getType()
8867 << NewFD
->getParamDecl(Idx
- 1)->getType();
8868 } else if (FDisConst
!= NewFDisConst
) {
8869 SemaRef
.Diag(FD
->getLocation(), diag::note_member_def_close_const_match
)
8870 << NewFDisConst
<< FD
->getSourceRange().getEnd()
8872 ? FixItHint::CreateRemoval(ExtraArgs
.D
.getFunctionTypeInfo()
8873 .getConstQualifierLoc())
8874 : FixItHint::CreateInsertion(ExtraArgs
.D
.getFunctionTypeInfo()
8876 .getLocWithOffset(1),
8879 SemaRef
.Diag(FD
->getLocation(),
8880 IsMember
? diag::note_member_def_close_match
8881 : diag::note_local_decl_close_match
);
8886 static StorageClass
getFunctionStorageClass(Sema
&SemaRef
, Declarator
&D
) {
8887 switch (D
.getDeclSpec().getStorageClassSpec()) {
8888 default: llvm_unreachable("Unknown storage class!");
8889 case DeclSpec::SCS_auto
:
8890 case DeclSpec::SCS_register
:
8891 case DeclSpec::SCS_mutable
:
8892 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
8893 diag::err_typecheck_sclass_func
);
8894 D
.getMutableDeclSpec().ClearStorageClassSpecs();
8897 case DeclSpec::SCS_unspecified
: break;
8898 case DeclSpec::SCS_extern
:
8899 if (D
.getDeclSpec().isExternInLinkageSpec())
8902 case DeclSpec::SCS_static
: {
8903 if (SemaRef
.CurContext
->getRedeclContext()->isFunctionOrMethod()) {
8905 // The declaration of an identifier for a function that has
8906 // block scope shall have no explicit storage-class specifier
8907 // other than extern
8908 // See also (C++ [dcl.stc]p4).
8909 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
8910 diag::err_static_block_func
);
8915 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
8918 // No explicit storage class has already been returned
8922 static FunctionDecl
*CreateNewFunctionDecl(Sema
&SemaRef
, Declarator
&D
,
8923 DeclContext
*DC
, QualType
&R
,
8924 TypeSourceInfo
*TInfo
,
8926 bool &IsVirtualOkay
) {
8927 DeclarationNameInfo NameInfo
= SemaRef
.GetNameForDeclarator(D
);
8928 DeclarationName Name
= NameInfo
.getName();
8930 FunctionDecl
*NewFD
= nullptr;
8931 bool isInline
= D
.getDeclSpec().isInlineSpecified();
8933 if (!SemaRef
.getLangOpts().CPlusPlus
) {
8934 // Determine whether the function was written with a prototype. This is
8936 // - there is a prototype in the declarator, or
8937 // - the type R of the function is some kind of typedef or other non-
8938 // attributed reference to a type name (which eventually refers to a
8939 // function type). Note, we can't always look at the adjusted type to
8940 // check this case because attributes may cause a non-function
8941 // declarator to still have a function type. e.g.,
8942 // typedef void func(int a);
8943 // __attribute__((noreturn)) func other_func; // This has a prototype
8945 (D
.isFunctionDeclarator() && D
.getFunctionTypeInfo().hasPrototype
) ||
8946 (D
.getDeclSpec().isTypeRep() &&
8947 D
.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8948 (!R
->getAsAdjusted
<FunctionType
>() && R
->isFunctionProtoType());
8950 (HasPrototype
|| !SemaRef
.getLangOpts().requiresStrictPrototypes()) &&
8951 "Strict prototypes are required");
8953 NewFD
= FunctionDecl::Create(
8954 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
8955 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
, HasPrototype
,
8956 ConstexprSpecKind::Unspecified
,
8957 /*TrailingRequiresClause=*/nullptr);
8958 if (D
.isInvalidType())
8959 NewFD
->setInvalidDecl();
8964 ExplicitSpecifier ExplicitSpecifier
= D
.getDeclSpec().getExplicitSpecifier();
8966 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
8967 if (ConstexprKind
== ConstexprSpecKind::Constinit
) {
8968 SemaRef
.Diag(D
.getDeclSpec().getConstexprSpecLoc(),
8969 diag::err_constexpr_wrong_decl_kind
)
8970 << static_cast<int>(ConstexprKind
);
8971 ConstexprKind
= ConstexprSpecKind::Unspecified
;
8972 D
.getMutableDeclSpec().ClearConstexprSpec();
8974 Expr
*TrailingRequiresClause
= D
.getTrailingRequiresClause();
8976 // Check that the return type is not an abstract class type.
8977 // For record types, this is done by the AbstractClassUsageDiagnoser once
8978 // the class has been completely parsed.
8979 if (!DC
->isRecord() &&
8980 SemaRef
.RequireNonAbstractType(
8981 D
.getIdentifierLoc(), R
->castAs
<FunctionType
>()->getReturnType(),
8982 diag::err_abstract_type_in_decl
, SemaRef
.AbstractReturnType
))
8985 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
) {
8986 // This is a C++ constructor declaration.
8987 assert(DC
->isRecord() &&
8988 "Constructors can only be declared in a member context");
8990 R
= SemaRef
.CheckConstructorDeclarator(D
, R
, SC
);
8991 return CXXConstructorDecl::Create(
8992 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
8993 TInfo
, ExplicitSpecifier
, SemaRef
.getCurFPFeatures().isFPConstrained(),
8994 isInline
, /*isImplicitlyDeclared=*/false, ConstexprKind
,
8995 InheritedConstructor(), TrailingRequiresClause
);
8997 } else if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
8998 // This is a C++ destructor declaration.
8999 if (DC
->isRecord()) {
9000 R
= SemaRef
.CheckDestructorDeclarator(D
, R
, SC
);
9001 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
9002 CXXDestructorDecl
*NewDD
= CXXDestructorDecl::Create(
9003 SemaRef
.Context
, Record
, D
.getBeginLoc(), NameInfo
, R
, TInfo
,
9004 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9005 /*isImplicitlyDeclared=*/false, ConstexprKind
,
9006 TrailingRequiresClause
);
9007 // User defined destructors start as not selected if the class definition is still
9009 if (Record
->isBeingDefined())
9010 NewDD
->setIneligibleOrNotSelected(true);
9012 // If the destructor needs an implicit exception specification, set it
9013 // now. FIXME: It'd be nice to be able to create the right type to start
9014 // with, but the type needs to reference the destructor declaration.
9015 if (SemaRef
.getLangOpts().CPlusPlus11
)
9016 SemaRef
.AdjustDestructorExceptionSpec(NewDD
);
9018 IsVirtualOkay
= true;
9022 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_destructor_not_member
);
9025 // Create a FunctionDecl to satisfy the function definition parsing
9027 return FunctionDecl::Create(
9028 SemaRef
.Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(), Name
, R
,
9029 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9030 /*hasPrototype=*/true, ConstexprKind
, TrailingRequiresClause
);
9033 } else if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
9034 if (!DC
->isRecord()) {
9035 SemaRef
.Diag(D
.getIdentifierLoc(),
9036 diag::err_conv_function_not_member
);
9040 SemaRef
.CheckConversionDeclarator(D
, R
, SC
);
9041 if (D
.isInvalidType())
9044 IsVirtualOkay
= true;
9045 return CXXConversionDecl::Create(
9046 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9047 TInfo
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9048 ExplicitSpecifier
, ConstexprKind
, SourceLocation(),
9049 TrailingRequiresClause
);
9051 } else if (Name
.getNameKind() == DeclarationName::CXXDeductionGuideName
) {
9052 if (TrailingRequiresClause
)
9053 SemaRef
.Diag(TrailingRequiresClause
->getBeginLoc(),
9054 diag::err_trailing_requires_clause_on_deduction_guide
)
9055 << TrailingRequiresClause
->getSourceRange();
9056 SemaRef
.CheckDeductionGuideDeclarator(D
, R
, SC
);
9058 return CXXDeductionGuideDecl::Create(SemaRef
.Context
, DC
, D
.getBeginLoc(),
9059 ExplicitSpecifier
, NameInfo
, R
, TInfo
,
9061 } else if (DC
->isRecord()) {
9062 // If the name of the function is the same as the name of the record,
9063 // then this must be an invalid constructor that has a return type.
9064 // (The parser checks for a return type and makes the declarator a
9065 // constructor if it has no return type).
9066 if (Name
.getAsIdentifierInfo() &&
9067 Name
.getAsIdentifierInfo() == cast
<CXXRecordDecl
>(DC
)->getIdentifier()){
9068 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_constructor_return_type
)
9069 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
9070 << SourceRange(D
.getIdentifierLoc());
9074 // This is a C++ method declaration.
9075 CXXMethodDecl
*Ret
= CXXMethodDecl::Create(
9076 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9077 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9078 ConstexprKind
, SourceLocation(), TrailingRequiresClause
);
9079 IsVirtualOkay
= !Ret
->isStatic();
9083 SemaRef
.getLangOpts().CPlusPlus
&& D
.getDeclSpec().isFriendSpecified();
9084 if (!isFriend
&& SemaRef
.CurContext
->isRecord())
9087 // Determine whether the function was written with a
9088 // prototype. This true when:
9089 // - we're in C++ (where every function has a prototype),
9090 return FunctionDecl::Create(
9091 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
9092 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9093 true /*HasPrototype*/, ConstexprKind
, TrailingRequiresClause
);
9097 enum OpenCLParamType
{
9101 InvalidAddrSpacePtrKernelParam
,
9106 static bool isOpenCLSizeDependentType(ASTContext
&C
, QualType Ty
) {
9107 // Size dependent types are just typedefs to normal integer types
9108 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9109 // integers other than by their names.
9110 StringRef SizeTypeNames
[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9112 // Remove typedefs one by one until we reach a typedef
9113 // for a size dependent type.
9114 QualType DesugaredTy
= Ty
;
9116 ArrayRef
<StringRef
> Names(SizeTypeNames
);
9117 auto Match
= llvm::find(Names
, DesugaredTy
.getUnqualifiedType().getAsString());
9118 if (Names
.end() != Match
)
9122 DesugaredTy
= Ty
.getSingleStepDesugaredType(C
);
9123 } while (DesugaredTy
!= Ty
);
9128 static OpenCLParamType
getOpenCLKernelParameterType(Sema
&S
, QualType PT
) {
9129 if (PT
->isDependentType())
9130 return InvalidKernelParam
;
9132 if (PT
->isPointerType() || PT
->isReferenceType()) {
9133 QualType PointeeType
= PT
->getPointeeType();
9134 if (PointeeType
.getAddressSpace() == LangAS::opencl_generic
||
9135 PointeeType
.getAddressSpace() == LangAS::opencl_private
||
9136 PointeeType
.getAddressSpace() == LangAS::Default
)
9137 return InvalidAddrSpacePtrKernelParam
;
9139 if (PointeeType
->isPointerType()) {
9140 // This is a pointer to pointer parameter.
9141 // Recursively check inner type.
9142 OpenCLParamType ParamKind
= getOpenCLKernelParameterType(S
, PointeeType
);
9143 if (ParamKind
== InvalidAddrSpacePtrKernelParam
||
9144 ParamKind
== InvalidKernelParam
)
9147 return PtrPtrKernelParam
;
9150 // C++ for OpenCL v1.0 s2.4:
9151 // Moreover the types used in parameters of the kernel functions must be:
9152 // Standard layout types for pointer parameters. The same applies to
9153 // reference if an implementation supports them in kernel parameters.
9154 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9155 !S
.getOpenCLOptions().isAvailableOption(
9156 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts()) &&
9157 !PointeeType
->isAtomicType() && !PointeeType
->isVoidType() &&
9158 !PointeeType
->isStandardLayoutType())
9159 return InvalidKernelParam
;
9161 return PtrKernelParam
;
9164 // OpenCL v1.2 s6.9.k:
9165 // Arguments to kernel functions in a program cannot be declared with the
9166 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9167 // uintptr_t or a struct and/or union that contain fields declared to be one
9168 // of these built-in scalar types.
9169 if (isOpenCLSizeDependentType(S
.getASTContext(), PT
))
9170 return InvalidKernelParam
;
9172 if (PT
->isImageType())
9173 return PtrKernelParam
;
9175 if (PT
->isBooleanType() || PT
->isEventT() || PT
->isReserveIDT())
9176 return InvalidKernelParam
;
9178 // OpenCL extension spec v1.2 s9.5:
9179 // This extension adds support for half scalar and vector types as built-in
9180 // types that can be used for arithmetic operations, conversions etc.
9181 if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S
.getLangOpts()) &&
9183 return InvalidKernelParam
;
9185 // Look into an array argument to check if it has a forbidden type.
9186 if (PT
->isArrayType()) {
9187 const Type
*UnderlyingTy
= PT
->getPointeeOrArrayElementType();
9188 // Call ourself to check an underlying type of an array. Since the
9189 // getPointeeOrArrayElementType returns an innermost type which is not an
9190 // array, this recursive call only happens once.
9191 return getOpenCLKernelParameterType(S
, QualType(UnderlyingTy
, 0));
9194 // C++ for OpenCL v1.0 s2.4:
9195 // Moreover the types used in parameters of the kernel functions must be:
9196 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9197 // types) for parameters passed by value;
9198 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9199 !S
.getOpenCLOptions().isAvailableOption(
9200 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts()) &&
9201 !PT
->isOpenCLSpecificType() && !PT
.isPODType(S
.Context
))
9202 return InvalidKernelParam
;
9204 if (PT
->isRecordType())
9205 return RecordKernelParam
;
9207 return ValidKernelParam
;
9210 static void checkIsValidOpenCLKernelParameter(
9214 llvm::SmallPtrSetImpl
<const Type
*> &ValidTypes
) {
9215 QualType PT
= Param
->getType();
9217 // Cache the valid types we encounter to avoid rechecking structs that are
9219 if (ValidTypes
.count(PT
.getTypePtr()))
9222 switch (getOpenCLKernelParameterType(S
, PT
)) {
9223 case PtrPtrKernelParam
:
9224 // OpenCL v3.0 s6.11.a:
9225 // A kernel function argument cannot be declared as a pointer to a pointer
9226 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9227 if (S
.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9228 S
.Diag(Param
->getLocation(), diag::err_opencl_ptrptr_kernel_param
);
9233 ValidTypes
.insert(PT
.getTypePtr());
9236 case InvalidAddrSpacePtrKernelParam
:
9237 // OpenCL v1.0 s6.5:
9238 // __kernel function arguments declared to be a pointer of a type can point
9239 // to one of the following address spaces only : __global, __local or
9241 S
.Diag(Param
->getLocation(), diag::err_kernel_arg_address_space
);
9245 // OpenCL v1.2 s6.9.k:
9246 // Arguments to kernel functions in a program cannot be declared with the
9247 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9248 // uintptr_t or a struct and/or union that contain fields declared to be
9249 // one of these built-in scalar types.
9251 case InvalidKernelParam
:
9252 // OpenCL v1.2 s6.8 n:
9253 // A kernel function argument cannot be declared
9255 // Do not diagnose half type since it is diagnosed as invalid argument
9256 // type for any function elsewhere.
9257 if (!PT
->isHalfType()) {
9258 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9260 // Explain what typedefs are involved.
9261 const TypedefType
*Typedef
= nullptr;
9262 while ((Typedef
= PT
->getAs
<TypedefType
>())) {
9263 SourceLocation Loc
= Typedef
->getDecl()->getLocation();
9264 // SourceLocation may be invalid for a built-in type.
9266 S
.Diag(Loc
, diag::note_entity_declared_at
) << PT
;
9267 PT
= Typedef
->desugar();
9274 case PtrKernelParam
:
9275 case ValidKernelParam
:
9276 ValidTypes
.insert(PT
.getTypePtr());
9279 case RecordKernelParam
:
9283 // Track nested structs we will inspect
9284 SmallVector
<const Decl
*, 4> VisitStack
;
9286 // Track where we are in the nested structs. Items will migrate from
9287 // VisitStack to HistoryStack as we do the DFS for bad field.
9288 SmallVector
<const FieldDecl
*, 4> HistoryStack
;
9289 HistoryStack
.push_back(nullptr);
9291 // At this point we already handled everything except of a RecordType or
9292 // an ArrayType of a RecordType.
9293 assert((PT
->isArrayType() || PT
->isRecordType()) && "Unexpected type.");
9294 const RecordType
*RecTy
=
9295 PT
->getPointeeOrArrayElementType()->getAs
<RecordType
>();
9296 const RecordDecl
*OrigRecDecl
= RecTy
->getDecl();
9298 VisitStack
.push_back(RecTy
->getDecl());
9299 assert(VisitStack
.back() && "First decl null?");
9302 const Decl
*Next
= VisitStack
.pop_back_val();
9304 assert(!HistoryStack
.empty());
9305 // Found a marker, we have gone up a level
9306 if (const FieldDecl
*Hist
= HistoryStack
.pop_back_val())
9307 ValidTypes
.insert(Hist
->getType().getTypePtr());
9312 // Adds everything except the original parameter declaration (which is not a
9313 // field itself) to the history stack.
9314 const RecordDecl
*RD
;
9315 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(Next
)) {
9316 HistoryStack
.push_back(Field
);
9318 QualType FieldTy
= Field
->getType();
9319 // Other field types (known to be valid or invalid) are handled while we
9320 // walk around RecordDecl::fields().
9321 assert((FieldTy
->isArrayType() || FieldTy
->isRecordType()) &&
9322 "Unexpected type.");
9323 const Type
*FieldRecTy
= FieldTy
->getPointeeOrArrayElementType();
9325 RD
= FieldRecTy
->castAs
<RecordType
>()->getDecl();
9327 RD
= cast
<RecordDecl
>(Next
);
9330 // Add a null marker so we know when we've gone back up a level
9331 VisitStack
.push_back(nullptr);
9333 for (const auto *FD
: RD
->fields()) {
9334 QualType QT
= FD
->getType();
9336 if (ValidTypes
.count(QT
.getTypePtr()))
9339 OpenCLParamType ParamType
= getOpenCLKernelParameterType(S
, QT
);
9340 if (ParamType
== ValidKernelParam
)
9343 if (ParamType
== RecordKernelParam
) {
9344 VisitStack
.push_back(FD
);
9348 // OpenCL v1.2 s6.9.p:
9349 // Arguments to kernel functions that are declared to be a struct or union
9350 // do not allow OpenCL objects to be passed as elements of the struct or
9352 if (ParamType
== PtrKernelParam
|| ParamType
== PtrPtrKernelParam
||
9353 ParamType
== InvalidAddrSpacePtrKernelParam
) {
9354 S
.Diag(Param
->getLocation(),
9355 diag::err_record_with_pointers_kernel_param
)
9356 << PT
->isUnionType()
9359 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9362 S
.Diag(OrigRecDecl
->getLocation(), diag::note_within_field_of_type
)
9363 << OrigRecDecl
->getDeclName();
9365 // We have an error, now let's go back up through history and show where
9366 // the offending field came from
9367 for (ArrayRef
<const FieldDecl
*>::const_iterator
9368 I
= HistoryStack
.begin() + 1,
9369 E
= HistoryStack
.end();
9371 const FieldDecl
*OuterField
= *I
;
9372 S
.Diag(OuterField
->getLocation(), diag::note_within_field_of_type
)
9373 << OuterField
->getType();
9376 S
.Diag(FD
->getLocation(), diag::note_illegal_field_declared_here
)
9377 << QT
->isPointerType()
9382 } while (!VisitStack
.empty());
9385 /// Find the DeclContext in which a tag is implicitly declared if we see an
9386 /// elaborated type specifier in the specified context, and lookup finds
9388 static DeclContext
*getTagInjectionContext(DeclContext
*DC
) {
9389 while (!DC
->isFileContext() && !DC
->isFunctionOrMethod())
9390 DC
= DC
->getParent();
9394 /// Find the Scope in which a tag is implicitly declared if we see an
9395 /// elaborated type specifier in the specified context, and lookup finds
9397 static Scope
*getTagInjectionScope(Scope
*S
, const LangOptions
&LangOpts
) {
9398 while (S
->isClassScope() ||
9399 (LangOpts
.CPlusPlus
&&
9400 S
->isFunctionPrototypeScope()) ||
9401 ((S
->getFlags() & Scope::DeclScope
) == 0) ||
9402 (S
->getEntity() && S
->getEntity()->isTransparentContext()))
9407 /// Determine whether a declaration matches a known function in namespace std.
9408 static bool isStdBuiltin(ASTContext
&Ctx
, FunctionDecl
*FD
,
9409 unsigned BuiltinID
) {
9410 switch (BuiltinID
) {
9411 case Builtin::BI__GetExceptionInfo
:
9412 // No type checking whatsoever.
9413 return Ctx
.getTargetInfo().getCXXABI().isMicrosoft();
9415 case Builtin::BIaddressof
:
9416 case Builtin::BI__addressof
:
9417 case Builtin::BIforward
:
9418 case Builtin::BImove
:
9419 case Builtin::BImove_if_noexcept
:
9420 case Builtin::BIas_const
: {
9421 // Ensure that we don't treat the algorithm
9422 // OutputIt std::move(InputIt, InputIt, OutputIt)
9423 // as the builtin std::move.
9424 const auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
9425 return FPT
->getNumParams() == 1 && !FPT
->isVariadic();
9434 Sema::ActOnFunctionDeclarator(Scope
*S
, Declarator
&D
, DeclContext
*DC
,
9435 TypeSourceInfo
*TInfo
, LookupResult
&Previous
,
9436 MultiTemplateParamsArg TemplateParamListsRef
,
9438 QualType R
= TInfo
->getType();
9440 assert(R
->isFunctionType());
9441 if (R
.getCanonicalType()->castAs
<FunctionType
>()->getCmseNSCallAttr())
9442 Diag(D
.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call
);
9444 SmallVector
<TemplateParameterList
*, 4> TemplateParamLists
;
9445 llvm::append_range(TemplateParamLists
, TemplateParamListsRef
);
9446 if (TemplateParameterList
*Invented
= D
.getInventedTemplateParameterList()) {
9447 if (!TemplateParamLists
.empty() &&
9448 Invented
->getDepth() == TemplateParamLists
.back()->getDepth())
9449 TemplateParamLists
.back() = Invented
;
9451 TemplateParamLists
.push_back(Invented
);
9454 // TODO: consider using NameInfo for diagnostic.
9455 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
9456 DeclarationName Name
= NameInfo
.getName();
9457 StorageClass SC
= getFunctionStorageClass(*this, D
);
9459 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
9460 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
9461 diag::err_invalid_thread
)
9462 << DeclSpec::getSpecifierName(TSCS
);
9464 if (D
.isFirstDeclarationOfMember())
9465 adjustMemberFunctionCC(R
, D
.isStaticMember(), D
.isCtorOrDtor(),
9466 D
.getIdentifierLoc());
9468 bool isFriend
= false;
9469 FunctionTemplateDecl
*FunctionTemplate
= nullptr;
9470 bool isMemberSpecialization
= false;
9471 bool isFunctionTemplateSpecialization
= false;
9473 bool isDependentClassScopeExplicitSpecialization
= false;
9474 bool HasExplicitTemplateArgs
= false;
9475 TemplateArgumentListInfo TemplateArgs
;
9477 bool isVirtualOkay
= false;
9479 DeclContext
*OriginalDC
= DC
;
9480 bool IsLocalExternDecl
= adjustContextForLocalExternDecl(DC
);
9482 FunctionDecl
*NewFD
= CreateNewFunctionDecl(*this, D
, DC
, R
, TInfo
, SC
,
9484 if (!NewFD
) return nullptr;
9486 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer())
9487 NewFD
->setTopLevelDeclInObjCContainer();
9489 // Set the lexical context. If this is a function-scope declaration, or has a
9490 // C++ scope specifier, or is the object of a friend declaration, the lexical
9491 // context will be different from the semantic context.
9492 NewFD
->setLexicalDeclContext(CurContext
);
9494 if (IsLocalExternDecl
)
9495 NewFD
->setLocalExternDecl();
9497 if (getLangOpts().CPlusPlus
) {
9498 // The rules for implicit inlines changed in C++20 for methods and friends
9499 // with an in-class definition (when such a definition is not attached to
9500 // the global module). User-specified 'inline' overrides this (set when
9501 // the function decl is created above).
9502 // FIXME: We need a better way to separate C++ standard and clang modules.
9503 bool ImplicitInlineCXX20
= !getLangOpts().CPlusPlusModules
||
9504 !NewFD
->getOwningModule() ||
9505 NewFD
->getOwningModule()->isGlobalModule() ||
9506 NewFD
->getOwningModule()->isHeaderLikeModule();
9507 bool isInline
= D
.getDeclSpec().isInlineSpecified();
9508 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
9509 bool hasExplicit
= D
.getDeclSpec().hasExplicitSpecifier();
9510 isFriend
= D
.getDeclSpec().isFriendSpecified();
9511 if (isFriend
&& !isInline
&& D
.isFunctionDefinition()) {
9512 // Pre-C++20 [class.friend]p5
9513 // A function can be defined in a friend declaration of a
9514 // class . . . . Such a function is implicitly inline.
9515 // Post C++20 [class.friend]p7
9516 // Such a function is implicitly an inline function if it is attached
9517 // to the global module.
9518 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
9521 // If this is a method defined in an __interface, and is not a constructor
9522 // or an overloaded operator, then set the pure flag (isVirtual will already
9524 if (const CXXRecordDecl
*Parent
=
9525 dyn_cast
<CXXRecordDecl
>(NewFD
->getDeclContext())) {
9526 if (Parent
->isInterface() && cast
<CXXMethodDecl
>(NewFD
)->isUserProvided())
9527 NewFD
->setPure(true);
9529 // C++ [class.union]p2
9530 // A union can have member functions, but not virtual functions.
9531 if (isVirtual
&& Parent
->isUnion()) {
9532 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union
);
9533 NewFD
->setInvalidDecl();
9535 if ((Parent
->isClass() || Parent
->isStruct()) &&
9536 Parent
->hasAttr
<SYCLSpecialClassAttr
>() &&
9537 NewFD
->getKind() == Decl::Kind::CXXMethod
&& NewFD
->getIdentifier() &&
9538 NewFD
->getName() == "__init" && D
.isFunctionDefinition()) {
9539 if (auto *Def
= Parent
->getDefinition())
9540 Def
->setInitMethod(true);
9544 SetNestedNameSpecifier(*this, NewFD
, D
);
9545 isMemberSpecialization
= false;
9546 isFunctionTemplateSpecialization
= false;
9547 if (D
.isInvalidType())
9548 NewFD
->setInvalidDecl();
9550 // Match up the template parameter lists with the scope specifier, then
9551 // determine whether we have a template or a template specialization.
9552 bool Invalid
= false;
9553 TemplateParameterList
*TemplateParams
=
9554 MatchTemplateParametersToScopeSpecifier(
9555 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
9556 D
.getCXXScopeSpec(),
9557 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9558 ? D
.getName().TemplateId
9560 TemplateParamLists
, isFriend
, isMemberSpecialization
,
9562 if (TemplateParams
) {
9563 // Check that we can declare a template here.
9564 if (CheckTemplateDeclScope(S
, TemplateParams
))
9565 NewFD
->setInvalidDecl();
9567 if (TemplateParams
->size() > 0) {
9568 // This is a function template
9570 // A destructor cannot be a template.
9571 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
9572 Diag(NewFD
->getLocation(), diag::err_destructor_template
);
9573 NewFD
->setInvalidDecl();
9576 // If we're adding a template to a dependent context, we may need to
9577 // rebuilding some of the types used within the template parameter list,
9578 // now that we know what the current instantiation is.
9579 if (DC
->isDependentContext()) {
9580 ContextRAII
SavedContext(*this, DC
);
9581 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams
))
9585 FunctionTemplate
= FunctionTemplateDecl::Create(Context
, DC
,
9586 NewFD
->getLocation(),
9587 Name
, TemplateParams
,
9589 FunctionTemplate
->setLexicalDeclContext(CurContext
);
9590 NewFD
->setDescribedFunctionTemplate(FunctionTemplate
);
9592 // For source fidelity, store the other template param lists.
9593 if (TemplateParamLists
.size() > 1) {
9594 NewFD
->setTemplateParameterListsInfo(Context
,
9595 ArrayRef
<TemplateParameterList
*>(TemplateParamLists
)
9599 // This is a function template specialization.
9600 isFunctionTemplateSpecialization
= true;
9601 // For source fidelity, store all the template param lists.
9602 if (TemplateParamLists
.size() > 0)
9603 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9605 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9607 // We want to remove the "template<>", found here.
9608 SourceRange RemoveRange
= TemplateParams
->getSourceRange();
9610 // If we remove the template<> and the name is not a
9611 // template-id, we're actually silently creating a problem:
9612 // the friend declaration will refer to an untemplated decl,
9613 // and clearly the user wants a template specialization. So
9614 // we need to insert '<>' after the name.
9615 SourceLocation InsertLoc
;
9616 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
9617 InsertLoc
= D
.getName().getSourceRange().getEnd();
9618 InsertLoc
= getLocForEndOfToken(InsertLoc
);
9621 Diag(D
.getIdentifierLoc(), diag::err_template_spec_decl_friend
)
9622 << Name
<< RemoveRange
9623 << FixItHint::CreateRemoval(RemoveRange
)
9624 << FixItHint::CreateInsertion(InsertLoc
, "<>");
9629 // Check that we can declare a template here.
9630 if (!TemplateParamLists
.empty() && isMemberSpecialization
&&
9631 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
9632 NewFD
->setInvalidDecl();
9634 // All template param lists were matched against the scope specifier:
9635 // this is NOT (an explicit specialization of) a template.
9636 if (TemplateParamLists
.size() > 0)
9637 // For source fidelity, store all the template param lists.
9638 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9642 NewFD
->setInvalidDecl();
9643 if (FunctionTemplate
)
9644 FunctionTemplate
->setInvalidDecl();
9647 // C++ [dcl.fct.spec]p5:
9648 // The virtual specifier shall only be used in declarations of
9649 // nonstatic class member functions that appear within a
9650 // member-specification of a class declaration; see 10.3.
9652 if (isVirtual
&& !NewFD
->isInvalidDecl()) {
9653 if (!isVirtualOkay
) {
9654 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9655 diag::err_virtual_non_function
);
9656 } else if (!CurContext
->isRecord()) {
9657 // 'virtual' was specified outside of the class.
9658 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9659 diag::err_virtual_out_of_class
)
9660 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9661 } else if (NewFD
->getDescribedFunctionTemplate()) {
9662 // C++ [temp.mem]p3:
9663 // A member function template shall not be virtual.
9664 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9665 diag::err_virtual_member_function_template
)
9666 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9668 // Okay: Add virtual to the method.
9669 NewFD
->setVirtualAsWritten(true);
9672 if (getLangOpts().CPlusPlus14
&&
9673 NewFD
->getReturnType()->isUndeducedType())
9674 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual
);
9677 if (getLangOpts().CPlusPlus14
&&
9678 (NewFD
->isDependentContext() ||
9679 (isFriend
&& CurContext
->isDependentContext())) &&
9680 NewFD
->getReturnType()->isUndeducedType()) {
9681 // If the function template is referenced directly (for instance, as a
9682 // member of the current instantiation), pretend it has a dependent type.
9683 // This is not really justified by the standard, but is the only sane
9685 // FIXME: For a friend function, we have not marked the function as being
9686 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9687 const FunctionProtoType
*FPT
=
9688 NewFD
->getType()->castAs
<FunctionProtoType
>();
9689 QualType Result
= SubstAutoTypeDependent(FPT
->getReturnType());
9690 NewFD
->setType(Context
.getFunctionType(Result
, FPT
->getParamTypes(),
9691 FPT
->getExtProtoInfo()));
9694 // C++ [dcl.fct.spec]p3:
9695 // The inline specifier shall not appear on a block scope function
9697 if (isInline
&& !NewFD
->isInvalidDecl()) {
9698 if (CurContext
->isFunctionOrMethod()) {
9699 // 'inline' is not allowed on block scope function declaration.
9700 Diag(D
.getDeclSpec().getInlineSpecLoc(),
9701 diag::err_inline_declaration_block_scope
) << Name
9702 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
9706 // C++ [dcl.fct.spec]p6:
9707 // The explicit specifier shall be used only in the declaration of a
9708 // constructor or conversion function within its class definition;
9709 // see 12.3.1 and 12.3.2.
9710 if (hasExplicit
&& !NewFD
->isInvalidDecl() &&
9711 !isa
<CXXDeductionGuideDecl
>(NewFD
)) {
9712 if (!CurContext
->isRecord()) {
9713 // 'explicit' was specified outside of the class.
9714 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
9715 diag::err_explicit_out_of_class
)
9716 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
9717 } else if (!isa
<CXXConstructorDecl
>(NewFD
) &&
9718 !isa
<CXXConversionDecl
>(NewFD
)) {
9719 // 'explicit' was specified on a function that wasn't a constructor
9720 // or conversion function.
9721 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
9722 diag::err_explicit_non_ctor_or_conv_function
)
9723 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
9727 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
9728 if (ConstexprKind
!= ConstexprSpecKind::Unspecified
) {
9729 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9730 // are implicitly inline.
9731 NewFD
->setImplicitlyInline();
9733 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9734 // be either constructors or to return a literal type. Therefore,
9735 // destructors cannot be declared constexpr.
9736 if (isa
<CXXDestructorDecl
>(NewFD
) &&
9737 (!getLangOpts().CPlusPlus20
||
9738 ConstexprKind
== ConstexprSpecKind::Consteval
)) {
9739 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor
)
9740 << static_cast<int>(ConstexprKind
);
9741 NewFD
->setConstexprKind(getLangOpts().CPlusPlus20
9742 ? ConstexprSpecKind::Unspecified
9743 : ConstexprSpecKind::Constexpr
);
9745 // C++20 [dcl.constexpr]p2: An allocation function, or a
9746 // deallocation function shall not be declared with the consteval
9748 if (ConstexprKind
== ConstexprSpecKind::Consteval
&&
9749 (NewFD
->getOverloadedOperator() == OO_New
||
9750 NewFD
->getOverloadedOperator() == OO_Array_New
||
9751 NewFD
->getOverloadedOperator() == OO_Delete
||
9752 NewFD
->getOverloadedOperator() == OO_Array_Delete
)) {
9753 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
9754 diag::err_invalid_consteval_decl_kind
)
9756 NewFD
->setConstexprKind(ConstexprSpecKind::Constexpr
);
9760 // If __module_private__ was specified, mark the function accordingly.
9761 if (D
.getDeclSpec().isModulePrivateSpecified()) {
9762 if (isFunctionTemplateSpecialization
) {
9763 SourceLocation ModulePrivateLoc
9764 = D
.getDeclSpec().getModulePrivateSpecLoc();
9765 Diag(ModulePrivateLoc
, diag::err_module_private_specialization
)
9767 << FixItHint::CreateRemoval(ModulePrivateLoc
);
9769 NewFD
->setModulePrivate();
9770 if (FunctionTemplate
)
9771 FunctionTemplate
->setModulePrivate();
9776 if (FunctionTemplate
) {
9777 FunctionTemplate
->setObjectOfFriendDecl();
9778 FunctionTemplate
->setAccess(AS_public
);
9780 NewFD
->setObjectOfFriendDecl();
9781 NewFD
->setAccess(AS_public
);
9784 // If a function is defined as defaulted or deleted, mark it as such now.
9785 // We'll do the relevant checks on defaulted / deleted functions later.
9786 switch (D
.getFunctionDefinitionKind()) {
9787 case FunctionDefinitionKind::Declaration
:
9788 case FunctionDefinitionKind::Definition
:
9791 case FunctionDefinitionKind::Defaulted
:
9792 NewFD
->setDefaulted();
9795 case FunctionDefinitionKind::Deleted
:
9796 NewFD
->setDeletedAsWritten();
9800 if (isa
<CXXMethodDecl
>(NewFD
) && DC
== CurContext
&&
9801 D
.isFunctionDefinition() && !isInline
) {
9802 // Pre C++20 [class.mfct]p2:
9803 // A member function may be defined (8.4) in its class definition, in
9804 // which case it is an inline member function (7.1.2)
9805 // Post C++20 [class.mfct]p1:
9806 // If a member function is attached to the global module and is defined
9807 // in its class definition, it is inline.
9808 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
9811 if (SC
== SC_Static
&& isa
<CXXMethodDecl
>(NewFD
) &&
9812 !CurContext
->isRecord()) {
9813 // C++ [class.static]p1:
9814 // A data or function member of a class may be declared static
9815 // in a class definition, in which case it is a static member of
9818 // Complain about the 'static' specifier if it's on an out-of-line
9819 // member function definition.
9821 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9822 // member function template declaration and class member template
9823 // declaration (MSVC versions before 2015), warn about this.
9824 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9825 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
9826 cast
<CXXRecordDecl
>(DC
)->getDescribedClassTemplate()) ||
9827 (getLangOpts().MSVCCompat
&& NewFD
->getDescribedFunctionTemplate()))
9828 ? diag::ext_static_out_of_line
: diag::err_static_out_of_line
)
9829 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
9832 // C++11 [except.spec]p15:
9833 // A deallocation function with no exception-specification is treated
9834 // as if it were specified with noexcept(true).
9835 const FunctionProtoType
*FPT
= R
->getAs
<FunctionProtoType
>();
9836 if ((Name
.getCXXOverloadedOperator() == OO_Delete
||
9837 Name
.getCXXOverloadedOperator() == OO_Array_Delete
) &&
9838 getLangOpts().CPlusPlus11
&& FPT
&& !FPT
->hasExceptionSpec())
9839 NewFD
->setType(Context
.getFunctionType(
9840 FPT
->getReturnType(), FPT
->getParamTypes(),
9841 FPT
->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept
)));
9843 // C++20 [dcl.inline]/7
9844 // If an inline function or variable that is attached to a named module
9845 // is declared in a definition domain, it shall be defined in that
9847 // So, if the current declaration does not have a definition, we must
9848 // check at the end of the TU (or when the PMF starts) to see that we
9849 // have a definition at that point.
9850 if (isInline
&& !D
.isFunctionDefinition() && getLangOpts().CPlusPlus20
&&
9851 NewFD
->hasOwningModule() &&
9852 NewFD
->getOwningModule()->isModulePurview()) {
9853 PendingInlineFuncDecls
.insert(NewFD
);
9857 // Filter out previous declarations that don't match the scope.
9858 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewFD
),
9859 D
.getCXXScopeSpec().isNotEmpty() ||
9860 isMemberSpecialization
||
9861 isFunctionTemplateSpecialization
);
9863 // Handle GNU asm-label extension (encoded as an attribute).
9864 if (Expr
*E
= (Expr
*) D
.getAsmLabel()) {
9865 // The parser guarantees this is a string.
9866 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
9867 NewFD
->addAttr(AsmLabelAttr::Create(Context
, SE
->getString(),
9868 /*IsLiteralLabel=*/true,
9869 SE
->getStrTokenLoc(0)));
9870 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
9871 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
9872 ExtnameUndeclaredIdentifiers
.find(NewFD
->getIdentifier());
9873 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
9874 if (isDeclExternC(NewFD
)) {
9875 NewFD
->addAttr(I
->second
);
9876 ExtnameUndeclaredIdentifiers
.erase(I
);
9878 Diag(NewFD
->getLocation(), diag::warn_redefine_extname_not_applied
)
9879 << /*Variable*/0 << NewFD
;
9883 // Copy the parameter declarations from the declarator D to the function
9884 // declaration NewFD, if they are available. First scavenge them into Params.
9885 SmallVector
<ParmVarDecl
*, 16> Params
;
9887 if (D
.isFunctionDeclarator(FTIIdx
)) {
9888 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getTypeObject(FTIIdx
).Fun
;
9890 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9891 // function that takes no arguments, not a function that takes a
9892 // single void argument.
9893 // We let through "const void" here because Sema::GetTypeForDeclarator
9894 // already checks for that case.
9895 if (FTIHasNonVoidParameters(FTI
) && FTI
.Params
[0].Param
) {
9896 for (unsigned i
= 0, e
= FTI
.NumParams
; i
!= e
; ++i
) {
9897 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.Params
[i
].Param
);
9898 assert(Param
->getDeclContext() != NewFD
&& "Was set before ?");
9899 Param
->setDeclContext(NewFD
);
9900 Params
.push_back(Param
);
9902 if (Param
->isInvalidDecl())
9903 NewFD
->setInvalidDecl();
9907 if (!getLangOpts().CPlusPlus
) {
9908 // In C, find all the tag declarations from the prototype and move them
9909 // into the function DeclContext. Remove them from the surrounding tag
9910 // injection context of the function, which is typically but not always
9912 DeclContext
*PrototypeTagContext
=
9913 getTagInjectionContext(NewFD
->getLexicalDeclContext());
9914 for (NamedDecl
*NonParmDecl
: FTI
.getDeclsInPrototype()) {
9915 auto *TD
= dyn_cast
<TagDecl
>(NonParmDecl
);
9917 // We don't want to reparent enumerators. Look at their parent enum
9920 if (auto *ECD
= dyn_cast
<EnumConstantDecl
>(NonParmDecl
))
9921 TD
= cast
<EnumDecl
>(ECD
->getDeclContext());
9925 DeclContext
*TagDC
= TD
->getLexicalDeclContext();
9926 if (!TagDC
->containsDecl(TD
))
9928 TagDC
->removeDecl(TD
);
9929 TD
->setDeclContext(NewFD
);
9932 // Preserve the lexical DeclContext if it is not the surrounding tag
9933 // injection context of the FD. In this example, the semantic context of
9934 // E will be f and the lexical context will be S, while both the
9935 // semantic and lexical contexts of S will be f:
9936 // void f(struct S { enum E { a } f; } s);
9937 if (TagDC
!= PrototypeTagContext
)
9938 TD
->setLexicalDeclContext(TagDC
);
9941 } else if (const FunctionProtoType
*FT
= R
->getAs
<FunctionProtoType
>()) {
9942 // When we're declaring a function with a typedef, typeof, etc as in the
9943 // following example, we'll need to synthesize (unnamed)
9944 // parameters for use in the declaration.
9947 // typedef void fn(int);
9951 // Synthesize a parameter for each argument type.
9952 for (const auto &AI
: FT
->param_types()) {
9953 ParmVarDecl
*Param
=
9954 BuildParmVarDeclForTypedef(NewFD
, D
.getIdentifierLoc(), AI
);
9955 Param
->setScopeInfo(0, Params
.size());
9956 Params
.push_back(Param
);
9959 assert(R
->isFunctionNoProtoType() && NewFD
->getNumParams() == 0 &&
9960 "Should not need args for typedef of non-prototype fn");
9963 // Finally, we know we have the right number of parameters, install them.
9964 NewFD
->setParams(Params
);
9966 if (D
.getDeclSpec().isNoreturnSpecified())
9967 NewFD
->addAttr(C11NoReturnAttr::Create(Context
,
9968 D
.getDeclSpec().getNoreturnSpecLoc(),
9969 AttributeCommonInfo::AS_Keyword
));
9971 // Functions returning a variably modified type violate C99 6.7.5.2p2
9972 // because all functions have linkage.
9973 if (!NewFD
->isInvalidDecl() &&
9974 NewFD
->getReturnType()->isVariablyModifiedType()) {
9975 Diag(NewFD
->getLocation(), diag::err_vm_func_decl
);
9976 NewFD
->setInvalidDecl();
9979 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9980 if (PragmaClangTextSection
.Valid
&& D
.isFunctionDefinition() &&
9981 !NewFD
->hasAttr
<SectionAttr
>())
9982 NewFD
->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9983 Context
, PragmaClangTextSection
.SectionName
,
9984 PragmaClangTextSection
.PragmaLocation
, AttributeCommonInfo::AS_Pragma
));
9986 // Apply an implicit SectionAttr if #pragma code_seg is active.
9987 if (CodeSegStack
.CurrentValue
&& D
.isFunctionDefinition() &&
9988 !NewFD
->hasAttr
<SectionAttr
>()) {
9989 NewFD
->addAttr(SectionAttr::CreateImplicit(
9990 Context
, CodeSegStack
.CurrentValue
->getString(),
9991 CodeSegStack
.CurrentPragmaLocation
, AttributeCommonInfo::AS_Pragma
,
9992 SectionAttr::Declspec_allocate
));
9993 if (UnifySection(CodeSegStack
.CurrentValue
->getString(),
9994 ASTContext::PSF_Implicit
| ASTContext::PSF_Execute
|
9995 ASTContext::PSF_Read
,
9997 NewFD
->dropAttr
<SectionAttr
>();
10000 // Apply an implicit CodeSegAttr from class declspec or
10001 // apply an implicit SectionAttr from #pragma code_seg if active.
10002 if (!NewFD
->hasAttr
<CodeSegAttr
>()) {
10003 if (Attr
*SAttr
= getImplicitCodeSegOrSectionAttrForFunction(NewFD
,
10004 D
.isFunctionDefinition())) {
10005 NewFD
->addAttr(SAttr
);
10009 // Handle attributes.
10010 ProcessDeclAttributes(S
, NewFD
, D
);
10012 if (getLangOpts().OpenCL
) {
10013 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10014 // type declaration will generate a compilation error.
10015 LangAS AddressSpace
= NewFD
->getReturnType().getAddressSpace();
10016 if (AddressSpace
!= LangAS::Default
) {
10017 Diag(NewFD
->getLocation(),
10018 diag::err_opencl_return_value_with_address_space
);
10019 NewFD
->setInvalidDecl();
10023 if (getLangOpts().HLSL
) {
10024 auto &TargetInfo
= getASTContext().getTargetInfo();
10025 // Skip operator overload which not identifier.
10026 // Also make sure NewFD is in translation-unit scope.
10027 if (!NewFD
->isInvalidDecl() && Name
.isIdentifier() &&
10028 NewFD
->getName() == TargetInfo
.getTargetOpts().HLSLEntry
&&
10029 S
->getDepth() == 0) {
10030 CheckHLSLEntryPoint(NewFD
);
10031 if (!NewFD
->isInvalidDecl()) {
10032 auto TripleShaderType
= TargetInfo
.getTriple().getEnvironment();
10033 AttributeCommonInfo
AL(NewFD
->getBeginLoc());
10034 HLSLShaderAttr::ShaderType ShaderType
= (HLSLShaderAttr::ShaderType
)(
10035 TripleShaderType
- (uint32_t)llvm::Triple::Pixel
);
10036 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10038 if (HLSLShaderAttr
*Attr
= mergeHLSLShaderAttr(NewFD
, AL
, ShaderType
))
10039 NewFD
->addAttr(Attr
);
10044 if (!getLangOpts().CPlusPlus
) {
10045 // Perform semantic checking on the function declaration.
10046 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10047 CheckMain(NewFD
, D
.getDeclSpec());
10049 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10050 CheckMSVCRTEntryPoint(NewFD
);
10052 if (!NewFD
->isInvalidDecl())
10053 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10054 isMemberSpecialization
,
10055 D
.isFunctionDefinition()));
10056 else if (!Previous
.empty())
10057 // Recover gracefully from an invalid redeclaration.
10058 D
.setRedeclaration(true);
10059 assert((NewFD
->isInvalidDecl() || !D
.isRedeclaration() ||
10060 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10061 "previous declaration set still overloaded");
10063 // Diagnose no-prototype function declarations with calling conventions that
10064 // don't support variadic calls. Only do this in C and do it after merging
10065 // possibly prototyped redeclarations.
10066 const FunctionType
*FT
= NewFD
->getType()->castAs
<FunctionType
>();
10067 if (isa
<FunctionNoProtoType
>(FT
) && !D
.isFunctionDefinition()) {
10068 CallingConv CC
= FT
->getExtInfo().getCC();
10069 if (!supportsVariadicCall(CC
)) {
10070 // Windows system headers sometimes accidentally use stdcall without
10071 // (void) parameters, so we relax this to a warning.
10073 CC
== CC_X86StdCall
? diag::warn_cconv_knr
: diag::err_cconv_knr
;
10074 Diag(NewFD
->getLocation(), DiagID
)
10075 << FunctionType::getNameForCallConv(CC
);
10079 if (NewFD
->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10080 NewFD
->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10081 checkNonTrivialCUnion(NewFD
->getReturnType(),
10082 NewFD
->getReturnTypeSourceRange().getBegin(),
10083 NTCUC_FunctionReturn
, NTCUK_Destruct
|NTCUK_Copy
);
10085 // C++11 [replacement.functions]p3:
10086 // The program's definitions shall not be specified as inline.
10088 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10090 // Suppress the diagnostic if the function is __attribute__((used)), since
10091 // that forces an external definition to be emitted.
10092 if (D
.getDeclSpec().isInlineSpecified() &&
10093 NewFD
->isReplaceableGlobalAllocationFunction() &&
10094 !NewFD
->hasAttr
<UsedAttr
>())
10095 Diag(D
.getDeclSpec().getInlineSpecLoc(),
10096 diag::ext_operator_new_delete_declared_inline
)
10097 << NewFD
->getDeclName();
10099 // If the declarator is a template-id, translate the parser's template
10100 // argument list into our AST format.
10101 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
10102 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
10103 TemplateArgs
.setLAngleLoc(TemplateId
->LAngleLoc
);
10104 TemplateArgs
.setRAngleLoc(TemplateId
->RAngleLoc
);
10105 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
10106 TemplateId
->NumArgs
);
10107 translateTemplateArguments(TemplateArgsPtr
,
10110 HasExplicitTemplateArgs
= true;
10112 if (NewFD
->isInvalidDecl()) {
10113 HasExplicitTemplateArgs
= false;
10114 } else if (FunctionTemplate
) {
10115 // Function template with explicit template arguments.
10116 Diag(D
.getIdentifierLoc(), diag::err_function_template_partial_spec
)
10117 << SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
);
10119 HasExplicitTemplateArgs
= false;
10121 assert((isFunctionTemplateSpecialization
||
10122 D
.getDeclSpec().isFriendSpecified()) &&
10123 "should have a 'template<>' for this decl");
10124 // "friend void foo<>(int);" is an implicit specialization decl.
10125 isFunctionTemplateSpecialization
= true;
10127 } else if (isFriend
&& isFunctionTemplateSpecialization
) {
10128 // This combination is only possible in a recovery case; the user
10129 // wrote something like:
10130 // template <> friend void foo(int);
10131 // which we're recovering from as if the user had written:
10132 // friend void foo<>(int);
10133 // Go ahead and fake up a template id.
10134 HasExplicitTemplateArgs
= true;
10135 TemplateArgs
.setLAngleLoc(D
.getIdentifierLoc());
10136 TemplateArgs
.setRAngleLoc(D
.getIdentifierLoc());
10139 // We do not add HD attributes to specializations here because
10140 // they may have different constexpr-ness compared to their
10141 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10142 // may end up with different effective targets. Instead, a
10143 // specialization inherits its target attributes from its template
10144 // in the CheckFunctionTemplateSpecialization() call below.
10145 if (getLangOpts().CUDA
&& !isFunctionTemplateSpecialization
)
10146 maybeAddCUDAHostDeviceAttrs(NewFD
, Previous
);
10148 // If it's a friend (and only if it's a friend), it's possible
10149 // that either the specialized function type or the specialized
10150 // template is dependent, and therefore matching will fail. In
10151 // this case, don't check the specialization yet.
10152 if (isFunctionTemplateSpecialization
&& isFriend
&&
10153 (NewFD
->getType()->isDependentType() || DC
->isDependentContext() ||
10154 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10155 TemplateArgs
.arguments()))) {
10156 assert(HasExplicitTemplateArgs
&&
10157 "friend function specialization without template args");
10158 if (CheckDependentFunctionTemplateSpecialization(NewFD
, TemplateArgs
,
10160 NewFD
->setInvalidDecl();
10161 } else if (isFunctionTemplateSpecialization
) {
10162 if (CurContext
->isDependentContext() && CurContext
->isRecord()
10164 isDependentClassScopeExplicitSpecialization
= true;
10165 } else if (!NewFD
->isInvalidDecl() &&
10166 CheckFunctionTemplateSpecialization(
10167 NewFD
, (HasExplicitTemplateArgs
? &TemplateArgs
: nullptr),
10169 NewFD
->setInvalidDecl();
10171 // C++ [dcl.stc]p1:
10172 // A storage-class-specifier shall not be specified in an explicit
10173 // specialization (14.7.3)
10174 FunctionTemplateSpecializationInfo
*Info
=
10175 NewFD
->getTemplateSpecializationInfo();
10176 if (Info
&& SC
!= SC_None
) {
10177 if (SC
!= Info
->getTemplate()->getTemplatedDecl()->getStorageClass())
10178 Diag(NewFD
->getLocation(),
10179 diag::err_explicit_specialization_inconsistent_storage_class
)
10181 << FixItHint::CreateRemoval(
10182 D
.getDeclSpec().getStorageClassSpecLoc());
10185 Diag(NewFD
->getLocation(),
10186 diag::ext_explicit_specialization_storage_class
)
10187 << FixItHint::CreateRemoval(
10188 D
.getDeclSpec().getStorageClassSpecLoc());
10190 } else if (isMemberSpecialization
&& isa
<CXXMethodDecl
>(NewFD
)) {
10191 if (CheckMemberSpecialization(NewFD
, Previous
))
10192 NewFD
->setInvalidDecl();
10195 // Perform semantic checking on the function declaration.
10196 if (!isDependentClassScopeExplicitSpecialization
) {
10197 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10198 CheckMain(NewFD
, D
.getDeclSpec());
10200 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10201 CheckMSVCRTEntryPoint(NewFD
);
10203 if (!NewFD
->isInvalidDecl())
10204 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10205 isMemberSpecialization
,
10206 D
.isFunctionDefinition()));
10207 else if (!Previous
.empty())
10208 // Recover gracefully from an invalid redeclaration.
10209 D
.setRedeclaration(true);
10212 assert((NewFD
->isInvalidDecl() || !D
.isRedeclaration() ||
10213 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10214 "previous declaration set still overloaded");
10216 NamedDecl
*PrincipalDecl
= (FunctionTemplate
10217 ? cast
<NamedDecl
>(FunctionTemplate
)
10220 if (isFriend
&& NewFD
->getPreviousDecl()) {
10221 AccessSpecifier Access
= AS_public
;
10222 if (!NewFD
->isInvalidDecl())
10223 Access
= NewFD
->getPreviousDecl()->getAccess();
10225 NewFD
->setAccess(Access
);
10226 if (FunctionTemplate
) FunctionTemplate
->setAccess(Access
);
10229 if (NewFD
->isOverloadedOperator() && !DC
->isRecord() &&
10230 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
10231 PrincipalDecl
->setNonMemberOperator();
10233 // If we have a function template, check the template parameter
10234 // list. This will check and merge default template arguments.
10235 if (FunctionTemplate
) {
10236 FunctionTemplateDecl
*PrevTemplate
=
10237 FunctionTemplate
->getPreviousDecl();
10238 CheckTemplateParameterList(FunctionTemplate
->getTemplateParameters(),
10239 PrevTemplate
? PrevTemplate
->getTemplateParameters()
10241 D
.getDeclSpec().isFriendSpecified()
10242 ? (D
.isFunctionDefinition()
10243 ? TPC_FriendFunctionTemplateDefinition
10244 : TPC_FriendFunctionTemplate
)
10245 : (D
.getCXXScopeSpec().isSet() &&
10246 DC
&& DC
->isRecord() &&
10247 DC
->isDependentContext())
10248 ? TPC_ClassTemplateMember
10249 : TPC_FunctionTemplate
);
10252 if (NewFD
->isInvalidDecl()) {
10253 // Ignore all the rest of this.
10254 } else if (!D
.isRedeclaration()) {
10255 struct ActOnFDArgs ExtraArgs
= { S
, D
, TemplateParamLists
,
10257 // Fake up an access specifier if it's supposed to be a class member.
10258 if (isa
<CXXRecordDecl
>(NewFD
->getDeclContext()))
10259 NewFD
->setAccess(AS_public
);
10261 // Qualified decls generally require a previous declaration.
10262 if (D
.getCXXScopeSpec().isSet()) {
10263 // ...with the major exception of templated-scope or
10264 // dependent-scope friend declarations.
10266 // TODO: we currently also suppress this check in dependent
10267 // contexts because (1) the parameter depth will be off when
10268 // matching friend templates and (2) we might actually be
10269 // selecting a friend based on a dependent factor. But there
10270 // are situations where these conditions don't apply and we
10271 // can actually do this check immediately.
10273 // Unless the scope is dependent, it's always an error if qualified
10274 // redeclaration lookup found nothing at all. Diagnose that now;
10275 // nothing will diagnose that error later.
10277 (D
.getCXXScopeSpec().getScopeRep()->isDependent() ||
10278 (!Previous
.empty() && CurContext
->isDependentContext()))) {
10280 } else if (NewFD
->isCPUDispatchMultiVersion() ||
10281 NewFD
->isCPUSpecificMultiVersion()) {
10282 // ignore this, we allow the redeclaration behavior here to create new
10283 // versions of the function.
10285 // The user tried to provide an out-of-line definition for a
10286 // function that is a member of a class or namespace, but there
10287 // was no such member function declared (C++ [class.mfct]p2,
10288 // C++ [namespace.memdef]p2). For example:
10294 // void X::f() { } // ill-formed
10296 // Complain about this problem, and attempt to suggest close
10297 // matches (e.g., those that differ only in cv-qualifiers and
10298 // whether the parameter types are references).
10300 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10301 *this, Previous
, NewFD
, ExtraArgs
, false, nullptr)) {
10302 AddToScope
= ExtraArgs
.AddToScope
;
10307 // Unqualified local friend declarations are required to resolve
10309 } else if (isFriend
&& cast
<CXXRecordDecl
>(CurContext
)->isLocalClass()) {
10310 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10311 *this, Previous
, NewFD
, ExtraArgs
, true, S
)) {
10312 AddToScope
= ExtraArgs
.AddToScope
;
10316 } else if (!D
.isFunctionDefinition() &&
10317 isa
<CXXMethodDecl
>(NewFD
) && NewFD
->isOutOfLine() &&
10318 !isFriend
&& !isFunctionTemplateSpecialization
&&
10319 !isMemberSpecialization
) {
10320 // An out-of-line member function declaration must also be a
10321 // definition (C++ [class.mfct]p2).
10322 // Note that this is not the case for explicit specializations of
10323 // function templates or member functions of class templates, per
10324 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10325 // extension for compatibility with old SWIG code which likes to
10327 Diag(NewFD
->getLocation(), diag::ext_out_of_line_declaration
)
10328 << D
.getCXXScopeSpec().getRange();
10332 // If this is the first declaration of a library builtin function, add
10333 // attributes as appropriate.
10334 if (!D
.isRedeclaration()) {
10335 if (IdentifierInfo
*II
= Previous
.getLookupName().getAsIdentifierInfo()) {
10336 if (unsigned BuiltinID
= II
->getBuiltinID()) {
10337 bool InStdNamespace
= Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
);
10338 if (!InStdNamespace
&&
10339 NewFD
->getDeclContext()->getRedeclContext()->isFileContext()) {
10340 if (NewFD
->getLanguageLinkage() == CLanguageLinkage
) {
10341 // Validate the type matches unless this builtin is specified as
10342 // matching regardless of its declared type.
10343 if (Context
.BuiltinInfo
.allowTypeMismatch(BuiltinID
)) {
10344 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10346 ASTContext::GetBuiltinTypeError Error
;
10347 LookupNecessaryTypesForBuiltin(S
, BuiltinID
);
10348 QualType BuiltinType
= Context
.GetBuiltinType(BuiltinID
, Error
);
10350 if (!Error
&& !BuiltinType
.isNull() &&
10351 Context
.hasSameFunctionTypeIgnoringExceptionSpec(
10352 NewFD
->getType(), BuiltinType
))
10353 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10356 } else if (InStdNamespace
&& NewFD
->isInStdNamespace() &&
10357 isStdBuiltin(Context
, NewFD
, BuiltinID
)) {
10358 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10364 ProcessPragmaWeak(S
, NewFD
);
10365 checkAttributesAfterMerging(*this, *NewFD
);
10367 AddKnownFunctionAttributes(NewFD
);
10369 if (NewFD
->hasAttr
<OverloadableAttr
>() &&
10370 !NewFD
->getType()->getAs
<FunctionProtoType
>()) {
10371 Diag(NewFD
->getLocation(),
10372 diag::err_attribute_overloadable_no_prototype
)
10374 NewFD
->dropAttr
<OverloadableAttr
>();
10377 // If there's a #pragma GCC visibility in scope, and this isn't a class
10378 // member, set the visibility of this function.
10379 if (!DC
->isRecord() && NewFD
->isExternallyVisible())
10380 AddPushedVisibilityAttribute(NewFD
);
10382 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10383 // marking the function.
10384 AddCFAuditedAttribute(NewFD
);
10386 // If this is a function definition, check if we have to apply any
10387 // attributes (i.e. optnone and no_builtin) due to a pragma.
10388 if (D
.isFunctionDefinition()) {
10389 AddRangeBasedOptnone(NewFD
);
10390 AddImplicitMSFunctionNoBuiltinAttr(NewFD
);
10391 AddSectionMSAllocText(NewFD
);
10392 ModifyFnAttributesMSPragmaOptimize(NewFD
);
10395 // If this is the first declaration of an extern C variable, update
10396 // the map of such variables.
10397 if (NewFD
->isFirstDecl() && !NewFD
->isInvalidDecl() &&
10398 isIncompleteDeclExternC(*this, NewFD
))
10399 RegisterLocallyScopedExternCDecl(NewFD
, S
);
10401 // Set this FunctionDecl's range up to the right paren.
10402 NewFD
->setRangeEnd(D
.getSourceRange().getEnd());
10404 if (D
.isRedeclaration() && !Previous
.empty()) {
10405 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
10406 checkDLLAttributeRedeclaration(*this, Prev
, NewFD
,
10407 isMemberSpecialization
||
10408 isFunctionTemplateSpecialization
,
10409 D
.isFunctionDefinition());
10412 if (getLangOpts().CUDA
) {
10413 IdentifierInfo
*II
= NewFD
->getIdentifier();
10414 if (II
&& II
->isStr(getCudaConfigureFuncName()) &&
10415 !NewFD
->isInvalidDecl() &&
10416 NewFD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10417 if (!R
->castAs
<FunctionType
>()->getReturnType()->isScalarType())
10418 Diag(NewFD
->getLocation(), diag::err_config_scalar_return
)
10419 << getCudaConfigureFuncName();
10420 Context
.setcudaConfigureCallDecl(NewFD
);
10423 // Variadic functions, other than a *declaration* of printf, are not allowed
10424 // in device-side CUDA code, unless someone passed
10425 // -fcuda-allow-variadic-functions.
10426 if (!getLangOpts().CUDAAllowVariadicFunctions
&& NewFD
->isVariadic() &&
10427 (NewFD
->hasAttr
<CUDADeviceAttr
>() ||
10428 NewFD
->hasAttr
<CUDAGlobalAttr
>()) &&
10429 !(II
&& II
->isStr("printf") && NewFD
->isExternC() &&
10430 !D
.isFunctionDefinition())) {
10431 Diag(NewFD
->getLocation(), diag::err_variadic_device_fn
);
10435 MarkUnusedFileScopedDecl(NewFD
);
10439 if (getLangOpts().OpenCL
&& NewFD
->hasAttr
<OpenCLKernelAttr
>()) {
10440 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10441 if (SC
== SC_Static
) {
10442 Diag(D
.getIdentifierLoc(), diag::err_static_kernel
);
10443 D
.setInvalidType();
10446 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10447 if (!NewFD
->getReturnType()->isVoidType()) {
10448 SourceRange RTRange
= NewFD
->getReturnTypeSourceRange();
10449 Diag(D
.getIdentifierLoc(), diag::err_expected_kernel_void_return_type
)
10450 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "void")
10452 D
.setInvalidType();
10455 llvm::SmallPtrSet
<const Type
*, 16> ValidTypes
;
10456 for (auto *Param
: NewFD
->parameters())
10457 checkIsValidOpenCLKernelParameter(*this, D
, Param
, ValidTypes
);
10459 if (getLangOpts().OpenCLCPlusPlus
) {
10460 if (DC
->isRecord()) {
10461 Diag(D
.getIdentifierLoc(), diag::err_method_kernel
);
10462 D
.setInvalidType();
10464 if (FunctionTemplate
) {
10465 Diag(D
.getIdentifierLoc(), diag::err_template_kernel
);
10466 D
.setInvalidType();
10471 if (getLangOpts().CPlusPlus
) {
10472 if (FunctionTemplate
) {
10473 if (NewFD
->isInvalidDecl())
10474 FunctionTemplate
->setInvalidDecl();
10475 return FunctionTemplate
;
10478 if (isMemberSpecialization
&& !NewFD
->isInvalidDecl())
10479 CompleteMemberSpecialization(NewFD
, Previous
);
10482 for (const ParmVarDecl
*Param
: NewFD
->parameters()) {
10483 QualType PT
= Param
->getType();
10485 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10487 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10488 if(const PipeType
*PipeTy
= PT
->getAs
<PipeType
>()) {
10489 QualType ElemTy
= PipeTy
->getElementType();
10490 if (ElemTy
->isReferenceType() || ElemTy
->isPointerType()) {
10491 Diag(Param
->getTypeSpecStartLoc(), diag::err_reference_pipe_type
);
10492 D
.setInvalidType();
10498 // Here we have an function template explicit specialization at class scope.
10499 // The actual specialization will be postponed to template instatiation
10500 // time via the ClassScopeFunctionSpecializationDecl node.
10501 if (isDependentClassScopeExplicitSpecialization
) {
10502 ClassScopeFunctionSpecializationDecl
*NewSpec
=
10503 ClassScopeFunctionSpecializationDecl::Create(
10504 Context
, CurContext
, NewFD
->getLocation(),
10505 cast
<CXXMethodDecl
>(NewFD
),
10506 HasExplicitTemplateArgs
, TemplateArgs
);
10507 CurContext
->addDecl(NewSpec
);
10508 AddToScope
= false;
10511 // Diagnose availability attributes. Availability cannot be used on functions
10512 // that are run during load/unload.
10513 if (const auto *attr
= NewFD
->getAttr
<AvailabilityAttr
>()) {
10514 if (NewFD
->hasAttr
<ConstructorAttr
>()) {
10515 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10517 NewFD
->dropAttr
<AvailabilityAttr
>();
10519 if (NewFD
->hasAttr
<DestructorAttr
>()) {
10520 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10522 NewFD
->dropAttr
<AvailabilityAttr
>();
10526 // Diagnose no_builtin attribute on function declaration that are not a
10528 // FIXME: We should really be doing this in
10529 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10530 // the FunctionDecl and at this point of the code
10531 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10532 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10533 if (const auto *NBA
= NewFD
->getAttr
<NoBuiltinAttr
>())
10534 switch (D
.getFunctionDefinitionKind()) {
10535 case FunctionDefinitionKind::Defaulted
:
10536 case FunctionDefinitionKind::Deleted
:
10537 Diag(NBA
->getLocation(),
10538 diag::err_attribute_no_builtin_on_defaulted_deleted_function
)
10539 << NBA
->getSpelling();
10541 case FunctionDefinitionKind::Declaration
:
10542 Diag(NBA
->getLocation(), diag::err_attribute_no_builtin_on_non_definition
)
10543 << NBA
->getSpelling();
10545 case FunctionDefinitionKind::Definition
:
10552 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10553 /// when __declspec(code_seg) "is applied to a class, all member functions of
10554 /// the class and nested classes -- this includes compiler-generated special
10555 /// member functions -- are put in the specified segment."
10556 /// The actual behavior is a little more complicated. The Microsoft compiler
10557 /// won't check outer classes if there is an active value from #pragma code_seg.
10558 /// The CodeSeg is always applied from the direct parent but only from outer
10559 /// classes when the #pragma code_seg stack is empty. See:
10560 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10561 /// available since MS has removed the page.
10562 static Attr
*getImplicitCodeSegAttrFromClass(Sema
&S
, const FunctionDecl
*FD
) {
10563 const auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
);
10566 const CXXRecordDecl
*Parent
= Method
->getParent();
10567 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10568 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10569 NewAttr
->setImplicit(true);
10573 // The Microsoft compiler won't check outer classes for the CodeSeg
10574 // when the #pragma code_seg stack is active.
10575 if (S
.CodeSegStack
.CurrentValue
)
10578 while ((Parent
= dyn_cast
<CXXRecordDecl
>(Parent
->getParent()))) {
10579 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10580 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10581 NewAttr
->setImplicit(true);
10588 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10589 /// containing class. Otherwise it will return implicit SectionAttr if the
10590 /// function is a definition and there is an active value on CodeSegStack
10591 /// (from the current #pragma code-seg value).
10593 /// \param FD Function being declared.
10594 /// \param IsDefinition Whether it is a definition or just a declaration.
10595 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10596 /// nullptr if no attribute should be added.
10597 Attr
*Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl
*FD
,
10598 bool IsDefinition
) {
10599 if (Attr
*A
= getImplicitCodeSegAttrFromClass(*this, FD
))
10601 if (!FD
->hasAttr
<SectionAttr
>() && IsDefinition
&&
10602 CodeSegStack
.CurrentValue
)
10603 return SectionAttr::CreateImplicit(
10604 getASTContext(), CodeSegStack
.CurrentValue
->getString(),
10605 CodeSegStack
.CurrentPragmaLocation
, AttributeCommonInfo::AS_Pragma
,
10606 SectionAttr::Declspec_allocate
);
10610 /// Determines if we can perform a correct type check for \p D as a
10611 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10612 /// best-effort check.
10614 /// \param NewD The new declaration.
10615 /// \param OldD The old declaration.
10616 /// \param NewT The portion of the type of the new declaration to check.
10617 /// \param OldT The portion of the type of the old declaration to check.
10618 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl
*NewD
, ValueDecl
*OldD
,
10619 QualType NewT
, QualType OldT
) {
10620 if (!NewD
->getLexicalDeclContext()->isDependentContext())
10623 // For dependently-typed local extern declarations and friends, we can't
10624 // perform a correct type check in general until instantiation:
10627 // template<typename T> void g() { T f(); }
10629 // (valid if g() is only instantiated with T = int).
10630 if (NewT
->isDependentType() &&
10631 (NewD
->isLocalExternDecl() || NewD
->getFriendObjectKind()))
10634 // Similarly, if the previous declaration was a dependent local extern
10635 // declaration, we don't really know its type yet.
10636 if (OldT
->isDependentType() && OldD
->isLocalExternDecl())
10642 /// Checks if the new declaration declared in dependent context must be
10643 /// put in the same redeclaration chain as the specified declaration.
10645 /// \param D Declaration that is checked.
10646 /// \param PrevDecl Previous declaration found with proper lookup method for the
10647 /// same declaration name.
10648 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10651 bool Sema::shouldLinkDependentDeclWithPrevious(Decl
*D
, Decl
*PrevDecl
) {
10652 if (!D
->getLexicalDeclContext()->isDependentContext())
10655 // Don't chain dependent friend function definitions until instantiation, to
10656 // permit cases like
10659 // template<typename T> class C1 { friend void func() {} };
10660 // template<typename T> class C2 { friend void func() {} };
10662 // ... which is valid if only one of C1 and C2 is ever instantiated.
10664 // FIXME: This need only apply to function definitions. For now, we proxy
10665 // this by checking for a file-scope function. We do not want this to apply
10666 // to friend declarations nominating member functions, because that gets in
10667 // the way of access checks.
10668 if (D
->getFriendObjectKind() && D
->getDeclContext()->isFileContext())
10671 auto *VD
= dyn_cast
<ValueDecl
>(D
);
10672 auto *PrevVD
= dyn_cast
<ValueDecl
>(PrevDecl
);
10673 return !VD
|| !PrevVD
||
10674 canFullyTypeCheckRedeclaration(VD
, PrevVD
, VD
->getType(),
10675 PrevVD
->getType());
10678 /// Check the target attribute of the function for MultiVersion
10681 /// Returns true if there was an error, false otherwise.
10682 static bool CheckMultiVersionValue(Sema
&S
, const FunctionDecl
*FD
) {
10683 const auto *TA
= FD
->getAttr
<TargetAttr
>();
10684 assert(TA
&& "MultiVersion Candidate requires a target attribute");
10685 ParsedTargetAttr ParseInfo
= TA
->parse();
10686 const TargetInfo
&TargetInfo
= S
.Context
.getTargetInfo();
10687 enum ErrType
{ Feature
= 0, Architecture
= 1 };
10689 if (!ParseInfo
.Architecture
.empty() &&
10690 !TargetInfo
.validateCpuIs(ParseInfo
.Architecture
)) {
10691 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10692 << Architecture
<< ParseInfo
.Architecture
;
10696 for (const auto &Feat
: ParseInfo
.Features
) {
10697 auto BareFeat
= StringRef
{Feat
}.substr(1);
10698 if (Feat
[0] == '-') {
10699 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10700 << Feature
<< ("no-" + BareFeat
).str();
10704 if (!TargetInfo
.validateCpuSupports(BareFeat
) ||
10705 !TargetInfo
.isValidFeatureName(BareFeat
)) {
10706 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10707 << Feature
<< BareFeat
;
10714 // Provide a white-list of attributes that are allowed to be combined with
10715 // multiversion functions.
10716 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind
,
10717 MultiVersionKind MVKind
) {
10718 // Note: this list/diagnosis must match the list in
10719 // checkMultiversionAttributesAllSame.
10724 return MVKind
== MultiVersionKind::Target
;
10725 case attr::NonNull
:
10726 case attr::NoThrow
:
10731 static bool checkNonMultiVersionCompatAttributes(Sema
&S
,
10732 const FunctionDecl
*FD
,
10733 const FunctionDecl
*CausedFD
,
10734 MultiVersionKind MVKind
) {
10735 const auto Diagnose
= [FD
, CausedFD
, MVKind
](Sema
&S
, const Attr
*A
) {
10736 S
.Diag(FD
->getLocation(), diag::err_multiversion_disallowed_other_attr
)
10737 << static_cast<unsigned>(MVKind
) << A
;
10739 S
.Diag(CausedFD
->getLocation(), diag::note_multiversioning_caused_here
);
10743 for (const Attr
*A
: FD
->attrs()) {
10744 switch (A
->getKind()) {
10745 case attr::CPUDispatch
:
10746 case attr::CPUSpecific
:
10747 if (MVKind
!= MultiVersionKind::CPUDispatch
&&
10748 MVKind
!= MultiVersionKind::CPUSpecific
)
10749 return Diagnose(S
, A
);
10752 if (MVKind
!= MultiVersionKind::Target
)
10753 return Diagnose(S
, A
);
10755 case attr::TargetClones
:
10756 if (MVKind
!= MultiVersionKind::TargetClones
)
10757 return Diagnose(S
, A
);
10760 if (!AttrCompatibleWithMultiVersion(A
->getKind(), MVKind
))
10761 return Diagnose(S
, A
);
10768 bool Sema::areMultiversionVariantFunctionsCompatible(
10769 const FunctionDecl
*OldFD
, const FunctionDecl
*NewFD
,
10770 const PartialDiagnostic
&NoProtoDiagID
,
10771 const PartialDiagnosticAt
&NoteCausedDiagIDAt
,
10772 const PartialDiagnosticAt
&NoSupportDiagIDAt
,
10773 const PartialDiagnosticAt
&DiffDiagIDAt
, bool TemplatesSupported
,
10774 bool ConstexprSupported
, bool CLinkageMayDiffer
) {
10775 enum DoesntSupport
{
10782 DefaultedFuncs
= 6,
10783 ConstexprFuncs
= 7,
10784 ConstevalFuncs
= 8,
10793 LanguageLinkage
= 5,
10796 if (NoProtoDiagID
.getDiagID() != 0 && OldFD
&&
10797 !OldFD
->getType()->getAs
<FunctionProtoType
>()) {
10798 Diag(OldFD
->getLocation(), NoProtoDiagID
);
10799 Diag(NoteCausedDiagIDAt
.first
, NoteCausedDiagIDAt
.second
);
10803 if (NoProtoDiagID
.getDiagID() != 0 &&
10804 !NewFD
->getType()->getAs
<FunctionProtoType
>())
10805 return Diag(NewFD
->getLocation(), NoProtoDiagID
);
10807 if (!TemplatesSupported
&&
10808 NewFD
->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate
)
10809 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10812 if (const auto *NewCXXFD
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
10813 if (NewCXXFD
->isVirtual())
10814 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10817 if (isa
<CXXConstructorDecl
>(NewCXXFD
))
10818 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10821 if (isa
<CXXDestructorDecl
>(NewCXXFD
))
10822 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10826 if (NewFD
->isDeleted())
10827 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10830 if (NewFD
->isDefaulted())
10831 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10834 if (!ConstexprSupported
&& NewFD
->isConstexpr())
10835 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10836 << (NewFD
->isConsteval() ? ConstevalFuncs
: ConstexprFuncs
);
10838 QualType NewQType
= Context
.getCanonicalType(NewFD
->getType());
10839 const auto *NewType
= cast
<FunctionType
>(NewQType
);
10840 QualType NewReturnType
= NewType
->getReturnType();
10842 if (NewReturnType
->isUndeducedType())
10843 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
10846 // Ensure the return type is identical.
10848 QualType OldQType
= Context
.getCanonicalType(OldFD
->getType());
10849 const auto *OldType
= cast
<FunctionType
>(OldQType
);
10850 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
10851 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
10853 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC())
10854 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << CallingConv
;
10856 QualType OldReturnType
= OldType
->getReturnType();
10858 if (OldReturnType
!= NewReturnType
)
10859 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ReturnType
;
10861 if (OldFD
->getConstexprKind() != NewFD
->getConstexprKind())
10862 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ConstexprSpec
;
10864 if (OldFD
->isInlineSpecified() != NewFD
->isInlineSpecified())
10865 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << InlineSpec
;
10867 if (OldFD
->getFormalLinkage() != NewFD
->getFormalLinkage())
10868 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << Linkage
;
10870 if (!CLinkageMayDiffer
&& OldFD
->isExternC() != NewFD
->isExternC())
10871 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << LanguageLinkage
;
10873 if (CheckEquivalentExceptionSpec(
10874 OldFD
->getType()->getAs
<FunctionProtoType
>(), OldFD
->getLocation(),
10875 NewFD
->getType()->getAs
<FunctionProtoType
>(), NewFD
->getLocation()))
10881 static bool CheckMultiVersionAdditionalRules(Sema
&S
, const FunctionDecl
*OldFD
,
10882 const FunctionDecl
*NewFD
,
10884 MultiVersionKind MVKind
) {
10885 if (!S
.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10886 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_supported
);
10888 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
10892 bool IsCPUSpecificCPUDispatchMVKind
=
10893 MVKind
== MultiVersionKind::CPUDispatch
||
10894 MVKind
== MultiVersionKind::CPUSpecific
;
10896 if (CausesMV
&& OldFD
&&
10897 checkNonMultiVersionCompatAttributes(S
, OldFD
, NewFD
, MVKind
))
10900 if (checkNonMultiVersionCompatAttributes(S
, NewFD
, nullptr, MVKind
))
10903 // Only allow transition to MultiVersion if it hasn't been used.
10904 if (OldFD
&& CausesMV
&& OldFD
->isUsed(false))
10905 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
10907 return S
.areMultiversionVariantFunctionsCompatible(
10908 OldFD
, NewFD
, S
.PDiag(diag::err_multiversion_noproto
),
10909 PartialDiagnosticAt(NewFD
->getLocation(),
10910 S
.PDiag(diag::note_multiversioning_caused_here
)),
10911 PartialDiagnosticAt(NewFD
->getLocation(),
10912 S
.PDiag(diag::err_multiversion_doesnt_support
)
10913 << static_cast<unsigned>(MVKind
)),
10914 PartialDiagnosticAt(NewFD
->getLocation(),
10915 S
.PDiag(diag::err_multiversion_diff
)),
10916 /*TemplatesSupported=*/false,
10917 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind
,
10918 /*CLinkageMayDiffer=*/false);
10921 /// Check the validity of a multiversion function declaration that is the
10922 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10924 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10926 /// Returns true if there was an error, false otherwise.
10927 static bool CheckMultiVersionFirstFunction(Sema
&S
, FunctionDecl
*FD
,
10928 MultiVersionKind MVKind
,
10929 const TargetAttr
*TA
) {
10930 assert(MVKind
!= MultiVersionKind::None
&&
10931 "Function lacks multiversion attribute");
10933 // Target only causes MV if it is default, otherwise this is a normal
10935 if (MVKind
== MultiVersionKind::Target
&& !TA
->isDefaultVersion())
10938 if (MVKind
== MultiVersionKind::Target
&& CheckMultiVersionValue(S
, FD
)) {
10939 FD
->setInvalidDecl();
10943 if (CheckMultiVersionAdditionalRules(S
, nullptr, FD
, true, MVKind
)) {
10944 FD
->setInvalidDecl();
10948 FD
->setIsMultiVersion();
10952 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl
*FD
) {
10953 for (const Decl
*D
= FD
->getPreviousDecl(); D
; D
= D
->getPreviousDecl()) {
10954 if (D
->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None
)
10961 static bool CheckTargetCausesMultiVersioning(
10962 Sema
&S
, FunctionDecl
*OldFD
, FunctionDecl
*NewFD
, const TargetAttr
*NewTA
,
10963 bool &Redeclaration
, NamedDecl
*&OldDecl
, LookupResult
&Previous
) {
10964 const auto *OldTA
= OldFD
->getAttr
<TargetAttr
>();
10965 ParsedTargetAttr NewParsed
= NewTA
->parse();
10966 // Sort order doesn't matter, it just needs to be consistent.
10967 llvm::sort(NewParsed
.Features
);
10969 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10970 // to change, this is a simple redeclaration.
10971 if (!NewTA
->isDefaultVersion() &&
10972 (!OldTA
|| OldTA
->getFeaturesStr() == NewTA
->getFeaturesStr()))
10975 // Otherwise, this decl causes MultiVersioning.
10976 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
, true,
10977 MultiVersionKind::Target
)) {
10978 NewFD
->setInvalidDecl();
10982 if (CheckMultiVersionValue(S
, NewFD
)) {
10983 NewFD
->setInvalidDecl();
10987 // If this is 'default', permit the forward declaration.
10988 if (!OldFD
->isMultiVersion() && !OldTA
&& NewTA
->isDefaultVersion()) {
10989 Redeclaration
= true;
10991 OldFD
->setIsMultiVersion();
10992 NewFD
->setIsMultiVersion();
10996 if (CheckMultiVersionValue(S
, OldFD
)) {
10997 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
10998 NewFD
->setInvalidDecl();
11002 ParsedTargetAttr OldParsed
= OldTA
->parse(std::less
<std::string
>());
11004 if (OldParsed
== NewParsed
) {
11005 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11006 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11007 NewFD
->setInvalidDecl();
11011 for (const auto *FD
: OldFD
->redecls()) {
11012 const auto *CurTA
= FD
->getAttr
<TargetAttr
>();
11013 // We allow forward declarations before ANY multiversioning attributes, but
11014 // nothing after the fact.
11015 if (PreviousDeclsHaveMultiVersionAttribute(FD
) &&
11016 (!CurTA
|| CurTA
->isInherited())) {
11017 S
.Diag(FD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11019 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
11020 NewFD
->setInvalidDecl();
11025 OldFD
->setIsMultiVersion();
11026 NewFD
->setIsMultiVersion();
11027 Redeclaration
= false;
11033 static bool MultiVersionTypesCompatible(MultiVersionKind Old
,
11034 MultiVersionKind New
) {
11035 if (Old
== New
|| Old
== MultiVersionKind::None
||
11036 New
== MultiVersionKind::None
)
11039 return (Old
== MultiVersionKind::CPUDispatch
&&
11040 New
== MultiVersionKind::CPUSpecific
) ||
11041 (Old
== MultiVersionKind::CPUSpecific
&&
11042 New
== MultiVersionKind::CPUDispatch
);
11045 /// Check the validity of a new function declaration being added to an existing
11046 /// multiversioned declaration collection.
11047 static bool CheckMultiVersionAdditionalDecl(
11048 Sema
&S
, FunctionDecl
*OldFD
, FunctionDecl
*NewFD
,
11049 MultiVersionKind NewMVKind
, const TargetAttr
*NewTA
,
11050 const CPUDispatchAttr
*NewCPUDisp
, const CPUSpecificAttr
*NewCPUSpec
,
11051 const TargetClonesAttr
*NewClones
, bool &Redeclaration
, NamedDecl
*&OldDecl
,
11052 LookupResult
&Previous
) {
11054 MultiVersionKind OldMVKind
= OldFD
->getMultiVersionKind();
11055 // Disallow mixing of multiversioning types.
11056 if (!MultiVersionTypesCompatible(OldMVKind
, NewMVKind
)) {
11057 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_types_mixed
);
11058 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11059 NewFD
->setInvalidDecl();
11063 ParsedTargetAttr NewParsed
;
11065 NewParsed
= NewTA
->parse();
11066 llvm::sort(NewParsed
.Features
);
11069 bool UseMemberUsingDeclRules
=
11070 S
.CurContext
->isRecord() && !NewFD
->getFriendObjectKind();
11072 bool MayNeedOverloadableChecks
=
11073 AllowOverloadingOfFunction(Previous
, S
.Context
, NewFD
);
11075 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11076 // of a previous member of the MultiVersion set.
11077 for (NamedDecl
*ND
: Previous
) {
11078 FunctionDecl
*CurFD
= ND
->getAsFunction();
11079 if (!CurFD
|| CurFD
->isInvalidDecl())
11081 if (MayNeedOverloadableChecks
&&
11082 S
.IsOverload(NewFD
, CurFD
, UseMemberUsingDeclRules
))
11085 switch (NewMVKind
) {
11086 case MultiVersionKind::None
:
11087 assert(OldMVKind
== MultiVersionKind::TargetClones
&&
11088 "Only target_clones can be omitted in subsequent declarations");
11090 case MultiVersionKind::Target
: {
11091 const auto *CurTA
= CurFD
->getAttr
<TargetAttr
>();
11092 if (CurTA
->getFeaturesStr() == NewTA
->getFeaturesStr()) {
11093 NewFD
->setIsMultiVersion();
11094 Redeclaration
= true;
11099 ParsedTargetAttr CurParsed
= CurTA
->parse(std::less
<std::string
>());
11100 if (CurParsed
== NewParsed
) {
11101 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11102 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11103 NewFD
->setInvalidDecl();
11108 case MultiVersionKind::TargetClones
: {
11109 const auto *CurClones
= CurFD
->getAttr
<TargetClonesAttr
>();
11110 Redeclaration
= true;
11112 NewFD
->setIsMultiVersion();
11114 if (CurClones
&& NewClones
&&
11115 (CurClones
->featuresStrs_size() != NewClones
->featuresStrs_size() ||
11116 !std::equal(CurClones
->featuresStrs_begin(),
11117 CurClones
->featuresStrs_end(),
11118 NewClones
->featuresStrs_begin()))) {
11119 S
.Diag(NewFD
->getLocation(), diag::err_target_clone_doesnt_match
);
11120 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11121 NewFD
->setInvalidDecl();
11127 case MultiVersionKind::CPUSpecific
:
11128 case MultiVersionKind::CPUDispatch
: {
11129 const auto *CurCPUSpec
= CurFD
->getAttr
<CPUSpecificAttr
>();
11130 const auto *CurCPUDisp
= CurFD
->getAttr
<CPUDispatchAttr
>();
11131 // Handle CPUDispatch/CPUSpecific versions.
11132 // Only 1 CPUDispatch function is allowed, this will make it go through
11133 // the redeclaration errors.
11134 if (NewMVKind
== MultiVersionKind::CPUDispatch
&&
11135 CurFD
->hasAttr
<CPUDispatchAttr
>()) {
11136 if (CurCPUDisp
->cpus_size() == NewCPUDisp
->cpus_size() &&
11138 CurCPUDisp
->cpus_begin(), CurCPUDisp
->cpus_end(),
11139 NewCPUDisp
->cpus_begin(),
11140 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11141 return Cur
->getName() == New
->getName();
11143 NewFD
->setIsMultiVersion();
11144 Redeclaration
= true;
11149 // If the declarations don't match, this is an error condition.
11150 S
.Diag(NewFD
->getLocation(), diag::err_cpu_dispatch_mismatch
);
11151 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11152 NewFD
->setInvalidDecl();
11155 if (NewMVKind
== MultiVersionKind::CPUSpecific
&& CurCPUSpec
) {
11156 if (CurCPUSpec
->cpus_size() == NewCPUSpec
->cpus_size() &&
11158 CurCPUSpec
->cpus_begin(), CurCPUSpec
->cpus_end(),
11159 NewCPUSpec
->cpus_begin(),
11160 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11161 return Cur
->getName() == New
->getName();
11163 NewFD
->setIsMultiVersion();
11164 Redeclaration
= true;
11169 // Only 1 version of CPUSpecific is allowed for each CPU.
11170 for (const IdentifierInfo
*CurII
: CurCPUSpec
->cpus()) {
11171 for (const IdentifierInfo
*NewII
: NewCPUSpec
->cpus()) {
11172 if (CurII
== NewII
) {
11173 S
.Diag(NewFD
->getLocation(), diag::err_cpu_specific_multiple_defs
)
11175 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11176 NewFD
->setInvalidDecl();
11187 // Else, this is simply a non-redecl case. Checking the 'value' is only
11188 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11189 // handled in the attribute adding step.
11190 if (NewMVKind
== MultiVersionKind::Target
&&
11191 CheckMultiVersionValue(S
, NewFD
)) {
11192 NewFD
->setInvalidDecl();
11196 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
,
11197 !OldFD
->isMultiVersion(), NewMVKind
)) {
11198 NewFD
->setInvalidDecl();
11202 // Permit forward declarations in the case where these two are compatible.
11203 if (!OldFD
->isMultiVersion()) {
11204 OldFD
->setIsMultiVersion();
11205 NewFD
->setIsMultiVersion();
11206 Redeclaration
= true;
11211 NewFD
->setIsMultiVersion();
11212 Redeclaration
= false;
11218 /// Check the validity of a mulitversion function declaration.
11219 /// Also sets the multiversion'ness' of the function itself.
11221 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11223 /// Returns true if there was an error, false otherwise.
11224 static bool CheckMultiVersionFunction(Sema
&S
, FunctionDecl
*NewFD
,
11225 bool &Redeclaration
, NamedDecl
*&OldDecl
,
11226 LookupResult
&Previous
) {
11227 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11228 const auto *NewCPUDisp
= NewFD
->getAttr
<CPUDispatchAttr
>();
11229 const auto *NewCPUSpec
= NewFD
->getAttr
<CPUSpecificAttr
>();
11230 const auto *NewClones
= NewFD
->getAttr
<TargetClonesAttr
>();
11231 MultiVersionKind MVKind
= NewFD
->getMultiVersionKind();
11233 // Main isn't allowed to become a multiversion function, however it IS
11234 // permitted to have 'main' be marked with the 'target' optimization hint.
11235 if (NewFD
->isMain()) {
11236 if (MVKind
!= MultiVersionKind::None
&&
11237 !(MVKind
== MultiVersionKind::Target
&& !NewTA
->isDefaultVersion())) {
11238 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_allowed_on_main
);
11239 NewFD
->setInvalidDecl();
11245 if (!OldDecl
|| !OldDecl
->getAsFunction() ||
11246 OldDecl
->getDeclContext()->getRedeclContext() !=
11247 NewFD
->getDeclContext()->getRedeclContext()) {
11248 // If there's no previous declaration, AND this isn't attempting to cause
11249 // multiversioning, this isn't an error condition.
11250 if (MVKind
== MultiVersionKind::None
)
11252 return CheckMultiVersionFirstFunction(S
, NewFD
, MVKind
, NewTA
);
11255 FunctionDecl
*OldFD
= OldDecl
->getAsFunction();
11257 if (!OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
)
11260 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11261 // for target_clones.
11262 if (OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
&&
11263 OldFD
->getMultiVersionKind() != MultiVersionKind::TargetClones
) {
11264 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11265 << (OldFD
->getMultiVersionKind() != MultiVersionKind::Target
);
11266 NewFD
->setInvalidDecl();
11270 if (!OldFD
->isMultiVersion()) {
11272 case MultiVersionKind::Target
:
11273 return CheckTargetCausesMultiVersioning(S
, OldFD
, NewFD
, NewTA
,
11274 Redeclaration
, OldDecl
, Previous
);
11275 case MultiVersionKind::TargetClones
:
11276 if (OldFD
->isUsed(false)) {
11277 NewFD
->setInvalidDecl();
11278 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
11280 OldFD
->setIsMultiVersion();
11282 case MultiVersionKind::CPUDispatch
:
11283 case MultiVersionKind::CPUSpecific
:
11284 case MultiVersionKind::None
:
11289 // At this point, we have a multiversion function decl (in OldFD) AND an
11290 // appropriate attribute in the current function decl. Resolve that these are
11291 // still compatible with previous declarations.
11292 return CheckMultiVersionAdditionalDecl(S
, OldFD
, NewFD
, MVKind
, NewTA
,
11293 NewCPUDisp
, NewCPUSpec
, NewClones
,
11294 Redeclaration
, OldDecl
, Previous
);
11297 /// Perform semantic checking of a new function declaration.
11299 /// Performs semantic analysis of the new function declaration
11300 /// NewFD. This routine performs all semantic checking that does not
11301 /// require the actual declarator involved in the declaration, and is
11302 /// used both for the declaration of functions as they are parsed
11303 /// (called via ActOnDeclarator) and for the declaration of functions
11304 /// that have been instantiated via C++ template instantiation (called
11305 /// via InstantiateDecl).
11307 /// \param IsMemberSpecialization whether this new function declaration is
11308 /// a member specialization (that replaces any definition provided by the
11309 /// previous declaration).
11311 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11313 /// \returns true if the function declaration is a redeclaration.
11314 bool Sema::CheckFunctionDeclaration(Scope
*S
, FunctionDecl
*NewFD
,
11315 LookupResult
&Previous
,
11316 bool IsMemberSpecialization
,
11318 assert(!NewFD
->getReturnType()->isVariablyModifiedType() &&
11319 "Variably modified return types are not handled here");
11321 // Determine whether the type of this function should be merged with
11322 // a previous visible declaration. This never happens for functions in C++,
11323 // and always happens in C if the previous declaration was visible.
11324 bool MergeTypeWithPrevious
= !getLangOpts().CPlusPlus
&&
11325 !Previous
.isShadowed();
11327 bool Redeclaration
= false;
11328 NamedDecl
*OldDecl
= nullptr;
11329 bool MayNeedOverloadableChecks
= false;
11331 // Merge or overload the declaration with an existing declaration of
11332 // the same name, if appropriate.
11333 if (!Previous
.empty()) {
11334 // Determine whether NewFD is an overload of PrevDecl or
11335 // a declaration that requires merging. If it's an overload,
11336 // there's no more work to do here; we'll just add the new
11337 // function to the scope.
11338 if (!AllowOverloadingOfFunction(Previous
, Context
, NewFD
)) {
11339 NamedDecl
*Candidate
= Previous
.getRepresentativeDecl();
11340 if (shouldLinkPossiblyHiddenDecl(Candidate
, NewFD
)) {
11341 Redeclaration
= true;
11342 OldDecl
= Candidate
;
11345 MayNeedOverloadableChecks
= true;
11346 switch (CheckOverload(S
, NewFD
, Previous
, OldDecl
,
11347 /*NewIsUsingDecl*/ false)) {
11349 Redeclaration
= true;
11352 case Ovl_NonFunction
:
11353 Redeclaration
= true;
11357 Redeclaration
= false;
11363 // Check for a previous extern "C" declaration with this name.
11364 if (!Redeclaration
&&
11365 checkForConflictWithNonVisibleExternC(*this, NewFD
, Previous
)) {
11366 if (!Previous
.empty()) {
11367 // This is an extern "C" declaration with the same name as a previous
11368 // declaration, and thus redeclares that entity...
11369 Redeclaration
= true;
11370 OldDecl
= Previous
.getFoundDecl();
11371 MergeTypeWithPrevious
= false;
11373 // ... except in the presence of __attribute__((overloadable)).
11374 if (OldDecl
->hasAttr
<OverloadableAttr
>() ||
11375 NewFD
->hasAttr
<OverloadableAttr
>()) {
11376 if (IsOverload(NewFD
, cast
<FunctionDecl
>(OldDecl
), false)) {
11377 MayNeedOverloadableChecks
= true;
11378 Redeclaration
= false;
11385 if (CheckMultiVersionFunction(*this, NewFD
, Redeclaration
, OldDecl
, Previous
))
11386 return Redeclaration
;
11388 // PPC MMA non-pointer types are not allowed as function return types.
11389 if (Context
.getTargetInfo().getTriple().isPPC64() &&
11390 CheckPPCMMAType(NewFD
->getReturnType(), NewFD
->getLocation())) {
11391 NewFD
->setInvalidDecl();
11394 // C++11 [dcl.constexpr]p8:
11395 // A constexpr specifier for a non-static member function that is not
11396 // a constructor declares that member function to be const.
11398 // This needs to be delayed until we know whether this is an out-of-line
11399 // definition of a static member function.
11401 // This rule is not present in C++1y, so we produce a backwards
11402 // compatibility warning whenever it happens in C++11.
11403 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
11404 if (!getLangOpts().CPlusPlus14
&& MD
&& MD
->isConstexpr() &&
11405 !MD
->isStatic() && !isa
<CXXConstructorDecl
>(MD
) &&
11406 !isa
<CXXDestructorDecl
>(MD
) && !MD
->getMethodQualifiers().hasConst()) {
11407 CXXMethodDecl
*OldMD
= nullptr;
11409 OldMD
= dyn_cast_or_null
<CXXMethodDecl
>(OldDecl
->getAsFunction());
11410 if (!OldMD
|| !OldMD
->isStatic()) {
11411 const FunctionProtoType
*FPT
=
11412 MD
->getType()->castAs
<FunctionProtoType
>();
11413 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
11414 EPI
.TypeQuals
.addConst();
11415 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
11416 FPT
->getParamTypes(), EPI
));
11418 // Warn that we did this, if we're not performing template instantiation.
11419 // In that case, we'll have warned already when the template was defined.
11420 if (!inTemplateInstantiation()) {
11421 SourceLocation AddConstLoc
;
11422 if (FunctionTypeLoc FTL
= MD
->getTypeSourceInfo()->getTypeLoc()
11423 .IgnoreParens().getAs
<FunctionTypeLoc
>())
11424 AddConstLoc
= getLocForEndOfToken(FTL
.getRParenLoc());
11426 Diag(MD
->getLocation(), diag::warn_cxx14_compat_constexpr_not_const
)
11427 << FixItHint::CreateInsertion(AddConstLoc
, " const");
11432 if (Redeclaration
) {
11433 // NewFD and OldDecl represent declarations that need to be
11435 if (MergeFunctionDecl(NewFD
, OldDecl
, S
, MergeTypeWithPrevious
,
11437 NewFD
->setInvalidDecl();
11438 return Redeclaration
;
11442 Previous
.addDecl(OldDecl
);
11444 if (FunctionTemplateDecl
*OldTemplateDecl
=
11445 dyn_cast
<FunctionTemplateDecl
>(OldDecl
)) {
11446 auto *OldFD
= OldTemplateDecl
->getTemplatedDecl();
11447 FunctionTemplateDecl
*NewTemplateDecl
11448 = NewFD
->getDescribedFunctionTemplate();
11449 assert(NewTemplateDecl
&& "Template/non-template mismatch");
11451 // The call to MergeFunctionDecl above may have created some state in
11452 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11453 // can add it as a redeclaration.
11454 NewTemplateDecl
->mergePrevDecl(OldTemplateDecl
);
11456 NewFD
->setPreviousDeclaration(OldFD
);
11457 if (NewFD
->isCXXClassMember()) {
11458 NewFD
->setAccess(OldTemplateDecl
->getAccess());
11459 NewTemplateDecl
->setAccess(OldTemplateDecl
->getAccess());
11462 // If this is an explicit specialization of a member that is a function
11463 // template, mark it as a member specialization.
11464 if (IsMemberSpecialization
&&
11465 NewTemplateDecl
->getInstantiatedFromMemberTemplate()) {
11466 NewTemplateDecl
->setMemberSpecialization();
11467 assert(OldTemplateDecl
->isMemberSpecialization());
11468 // Explicit specializations of a member template do not inherit deleted
11469 // status from the parent member template that they are specializing.
11470 if (OldFD
->isDeleted()) {
11471 // FIXME: This assert will not hold in the presence of modules.
11472 assert(OldFD
->getCanonicalDecl() == OldFD
);
11473 // FIXME: We need an update record for this AST mutation.
11474 OldFD
->setDeletedAsWritten(false);
11479 if (shouldLinkDependentDeclWithPrevious(NewFD
, OldDecl
)) {
11480 auto *OldFD
= cast
<FunctionDecl
>(OldDecl
);
11481 // This needs to happen first so that 'inline' propagates.
11482 NewFD
->setPreviousDeclaration(OldFD
);
11483 if (NewFD
->isCXXClassMember())
11484 NewFD
->setAccess(OldFD
->getAccess());
11487 } else if (!getLangOpts().CPlusPlus
&& MayNeedOverloadableChecks
&&
11488 !NewFD
->getAttr
<OverloadableAttr
>()) {
11489 assert((Previous
.empty() ||
11490 llvm::any_of(Previous
,
11491 [](const NamedDecl
*ND
) {
11492 return ND
->hasAttr
<OverloadableAttr
>();
11494 "Non-redecls shouldn't happen without overloadable present");
11496 auto OtherUnmarkedIter
= llvm::find_if(Previous
, [](const NamedDecl
*ND
) {
11497 const auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
11498 return FD
&& !FD
->hasAttr
<OverloadableAttr
>();
11501 if (OtherUnmarkedIter
!= Previous
.end()) {
11502 Diag(NewFD
->getLocation(),
11503 diag::err_attribute_overloadable_multiple_unmarked_overloads
);
11504 Diag((*OtherUnmarkedIter
)->getLocation(),
11505 diag::note_attribute_overloadable_prev_overload
)
11508 NewFD
->addAttr(OverloadableAttr::CreateImplicit(Context
));
11512 if (LangOpts
.OpenMP
)
11513 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD
);
11515 // Semantic checking for this function declaration (in isolation).
11517 if (getLangOpts().CPlusPlus
) {
11518 // C++-specific checks.
11519 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(NewFD
)) {
11520 CheckConstructor(Constructor
);
11521 } else if (CXXDestructorDecl
*Destructor
=
11522 dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
11523 // We check here for invalid destructor names.
11524 // If we have a friend destructor declaration that is dependent, we can't
11525 // diagnose right away because cases like this are still valid:
11526 // template <class T> struct A { friend T::X::~Y(); };
11527 // struct B { struct Y { ~Y(); }; using X = Y; };
11528 // template struct A<B>;
11529 if (NewFD
->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None
||
11530 !Destructor
->getThisType()->isDependentType()) {
11531 CXXRecordDecl
*Record
= Destructor
->getParent();
11532 QualType ClassType
= Context
.getTypeDeclType(Record
);
11534 DeclarationName Name
= Context
.DeclarationNames
.getCXXDestructorName(
11535 Context
.getCanonicalType(ClassType
));
11536 if (NewFD
->getDeclName() != Name
) {
11537 Diag(NewFD
->getLocation(), diag::err_destructor_name
);
11538 NewFD
->setInvalidDecl();
11539 return Redeclaration
;
11542 } else if (auto *Guide
= dyn_cast
<CXXDeductionGuideDecl
>(NewFD
)) {
11543 if (auto *TD
= Guide
->getDescribedFunctionTemplate())
11544 CheckDeductionGuideTemplate(TD
);
11546 // A deduction guide is not on the list of entities that can be
11547 // explicitly specialized.
11548 if (Guide
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
11549 Diag(Guide
->getBeginLoc(), diag::err_deduction_guide_specialized
)
11550 << /*explicit specialization*/ 1;
11553 // Find any virtual functions that this function overrides.
11554 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
11555 if (!Method
->isFunctionTemplateSpecialization() &&
11556 !Method
->getDescribedFunctionTemplate() &&
11557 Method
->isCanonicalDecl()) {
11558 AddOverriddenMethods(Method
->getParent(), Method
);
11560 if (Method
->isVirtual() && NewFD
->getTrailingRequiresClause())
11561 // C++2a [class.virtual]p6
11562 // A virtual method shall not have a requires-clause.
11563 Diag(NewFD
->getTrailingRequiresClause()->getBeginLoc(),
11564 diag::err_constrained_virtual_method
);
11566 if (Method
->isStatic())
11567 checkThisInStaticMemberFunctionType(Method
);
11570 // C++20: dcl.decl.general p4:
11571 // The optional requires-clause ([temp.pre]) in an init-declarator or
11572 // member-declarator shall be present only if the declarator declares a
11573 // templated function ([dcl.fct]).
11574 if (Expr
*TRC
= NewFD
->getTrailingRequiresClause()) {
11575 if (!NewFD
->isTemplated() && !NewFD
->isTemplateInstantiation())
11576 Diag(TRC
->getBeginLoc(), diag::err_constrained_non_templated_function
);
11579 if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(NewFD
))
11580 ActOnConversionDeclarator(Conversion
);
11582 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11583 if (NewFD
->isOverloadedOperator() &&
11584 CheckOverloadedOperatorDeclaration(NewFD
)) {
11585 NewFD
->setInvalidDecl();
11586 return Redeclaration
;
11589 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11590 if (NewFD
->getLiteralIdentifier() &&
11591 CheckLiteralOperatorDeclaration(NewFD
)) {
11592 NewFD
->setInvalidDecl();
11593 return Redeclaration
;
11596 // In C++, check default arguments now that we have merged decls. Unless
11597 // the lexical context is the class, because in this case this is done
11598 // during delayed parsing anyway.
11599 if (!CurContext
->isRecord())
11600 CheckCXXDefaultArguments(NewFD
);
11602 // If this function is declared as being extern "C", then check to see if
11603 // the function returns a UDT (class, struct, or union type) that is not C
11604 // compatible, and if it does, warn the user.
11605 // But, issue any diagnostic on the first declaration only.
11606 if (Previous
.empty() && NewFD
->isExternC()) {
11607 QualType R
= NewFD
->getReturnType();
11608 if (R
->isIncompleteType() && !R
->isVoidType())
11609 Diag(NewFD
->getLocation(), diag::warn_return_value_udt_incomplete
)
11611 else if (!R
.isPODType(Context
) && !R
->isVoidType() &&
11612 !R
->isObjCObjectPointerType())
11613 Diag(NewFD
->getLocation(), diag::warn_return_value_udt
) << NewFD
<< R
;
11616 // C++1z [dcl.fct]p6:
11617 // [...] whether the function has a non-throwing exception-specification
11618 // [is] part of the function type
11620 // This results in an ABI break between C++14 and C++17 for functions whose
11621 // declared type includes an exception-specification in a parameter or
11622 // return type. (Exception specifications on the function itself are OK in
11623 // most cases, and exception specifications are not permitted in most other
11624 // contexts where they could make it into a mangling.)
11625 if (!getLangOpts().CPlusPlus17
&& !NewFD
->getPrimaryTemplate()) {
11626 auto HasNoexcept
= [&](QualType T
) -> bool {
11627 // Strip off declarator chunks that could be between us and a function
11628 // type. We don't need to look far, exception specifications are very
11629 // restricted prior to C++17.
11630 if (auto *RT
= T
->getAs
<ReferenceType
>())
11631 T
= RT
->getPointeeType();
11632 else if (T
->isAnyPointerType())
11633 T
= T
->getPointeeType();
11634 else if (auto *MPT
= T
->getAs
<MemberPointerType
>())
11635 T
= MPT
->getPointeeType();
11636 if (auto *FPT
= T
->getAs
<FunctionProtoType
>())
11637 if (FPT
->isNothrow())
11642 auto *FPT
= NewFD
->getType()->castAs
<FunctionProtoType
>();
11643 bool AnyNoexcept
= HasNoexcept(FPT
->getReturnType());
11644 for (QualType T
: FPT
->param_types())
11645 AnyNoexcept
|= HasNoexcept(T
);
11647 Diag(NewFD
->getLocation(),
11648 diag::warn_cxx17_compat_exception_spec_in_signature
)
11652 if (!Redeclaration
&& LangOpts
.CUDA
)
11653 checkCUDATargetOverload(NewFD
, Previous
);
11655 return Redeclaration
;
11658 void Sema::CheckMain(FunctionDecl
* FD
, const DeclSpec
& DS
) {
11659 // C++11 [basic.start.main]p3:
11660 // A program that [...] declares main to be inline, static or
11661 // constexpr is ill-formed.
11662 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11663 // appear in a declaration of main.
11664 // static main is not an error under C99, but we should warn about it.
11665 // We accept _Noreturn main as an extension.
11666 if (FD
->getStorageClass() == SC_Static
)
11667 Diag(DS
.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11668 ? diag::err_static_main
: diag::warn_static_main
)
11669 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
11670 if (FD
->isInlineSpecified())
11671 Diag(DS
.getInlineSpecLoc(), diag::err_inline_main
)
11672 << FixItHint::CreateRemoval(DS
.getInlineSpecLoc());
11673 if (DS
.isNoreturnSpecified()) {
11674 SourceLocation NoreturnLoc
= DS
.getNoreturnSpecLoc();
11675 SourceRange
NoreturnRange(NoreturnLoc
, getLocForEndOfToken(NoreturnLoc
));
11676 Diag(NoreturnLoc
, diag::ext_noreturn_main
);
11677 Diag(NoreturnLoc
, diag::note_main_remove_noreturn
)
11678 << FixItHint::CreateRemoval(NoreturnRange
);
11680 if (FD
->isConstexpr()) {
11681 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_main
)
11682 << FD
->isConsteval()
11683 << FixItHint::CreateRemoval(DS
.getConstexprSpecLoc());
11684 FD
->setConstexprKind(ConstexprSpecKind::Unspecified
);
11687 if (getLangOpts().OpenCL
) {
11688 Diag(FD
->getLocation(), diag::err_opencl_no_main
)
11689 << FD
->hasAttr
<OpenCLKernelAttr
>();
11690 FD
->setInvalidDecl();
11694 // Functions named main in hlsl are default entries, but don't have specific
11695 // signatures they are required to conform to.
11696 if (getLangOpts().HLSL
)
11699 QualType T
= FD
->getType();
11700 assert(T
->isFunctionType() && "function decl is not of function type");
11701 const FunctionType
* FT
= T
->castAs
<FunctionType
>();
11703 // Set default calling convention for main()
11704 if (FT
->getCallConv() != CC_C
) {
11705 FT
= Context
.adjustFunctionType(FT
, FT
->getExtInfo().withCallingConv(CC_C
));
11706 FD
->setType(QualType(FT
, 0));
11707 T
= Context
.getCanonicalType(FD
->getType());
11710 if (getLangOpts().GNUMode
&& !getLangOpts().CPlusPlus
) {
11711 // In C with GNU extensions we allow main() to have non-integer return
11712 // type, but we should warn about the extension, and we disable the
11713 // implicit-return-zero rule.
11715 // GCC in C mode accepts qualified 'int'.
11716 if (Context
.hasSameUnqualifiedType(FT
->getReturnType(), Context
.IntTy
))
11717 FD
->setHasImplicitReturnZero(true);
11719 Diag(FD
->getTypeSpecStartLoc(), diag::ext_main_returns_nonint
);
11720 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
11721 if (RTRange
.isValid())
11722 Diag(RTRange
.getBegin(), diag::note_main_change_return_type
)
11723 << FixItHint::CreateReplacement(RTRange
, "int");
11726 // In C and C++, main magically returns 0 if you fall off the end;
11727 // set the flag which tells us that.
11728 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11730 // All the standards say that main() should return 'int'.
11731 if (Context
.hasSameType(FT
->getReturnType(), Context
.IntTy
))
11732 FD
->setHasImplicitReturnZero(true);
11734 // Otherwise, this is just a flat-out error.
11735 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
11736 Diag(FD
->getTypeSpecStartLoc(), diag::err_main_returns_nonint
)
11737 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "int")
11739 FD
->setInvalidDecl(true);
11743 // Treat protoless main() as nullary.
11744 if (isa
<FunctionNoProtoType
>(FT
)) return;
11746 const FunctionProtoType
* FTP
= cast
<const FunctionProtoType
>(FT
);
11747 unsigned nparams
= FTP
->getNumParams();
11748 assert(FD
->getNumParams() == nparams
);
11750 bool HasExtraParameters
= (nparams
> 3);
11752 if (FTP
->isVariadic()) {
11753 Diag(FD
->getLocation(), diag::ext_variadic_main
);
11754 // FIXME: if we had information about the location of the ellipsis, we
11755 // could add a FixIt hint to remove it as a parameter.
11758 // Darwin passes an undocumented fourth argument of type char**. If
11759 // other platforms start sprouting these, the logic below will start
11761 if (nparams
== 4 && Context
.getTargetInfo().getTriple().isOSDarwin())
11762 HasExtraParameters
= false;
11764 if (HasExtraParameters
) {
11765 Diag(FD
->getLocation(), diag::err_main_surplus_args
) << nparams
;
11766 FD
->setInvalidDecl(true);
11770 // FIXME: a lot of the following diagnostics would be improved
11771 // if we had some location information about types.
11774 Context
.getPointerType(Context
.getPointerType(Context
.CharTy
));
11775 QualType Expected
[] = { Context
.IntTy
, CharPP
, CharPP
, CharPP
};
11777 for (unsigned i
= 0; i
< nparams
; ++i
) {
11778 QualType AT
= FTP
->getParamType(i
);
11780 bool mismatch
= true;
11782 if (Context
.hasSameUnqualifiedType(AT
, Expected
[i
]))
11784 else if (Expected
[i
] == CharPP
) {
11785 // As an extension, the following forms are okay:
11787 // char const * const *
11790 QualifierCollector qs
;
11791 const PointerType
* PT
;
11792 if ((PT
= qs
.strip(AT
)->getAs
<PointerType
>()) &&
11793 (PT
= qs
.strip(PT
->getPointeeType())->getAs
<PointerType
>()) &&
11794 Context
.hasSameType(QualType(qs
.strip(PT
->getPointeeType()), 0),
11797 mismatch
= !qs
.empty();
11802 Diag(FD
->getLocation(), diag::err_main_arg_wrong
) << i
<< Expected
[i
];
11803 // TODO: suggest replacing given type with expected type
11804 FD
->setInvalidDecl(true);
11808 if (nparams
== 1 && !FD
->isInvalidDecl()) {
11809 Diag(FD
->getLocation(), diag::warn_main_one_arg
);
11812 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
11813 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
11814 FD
->setInvalidDecl();
11818 static bool isDefaultStdCall(FunctionDecl
*FD
, Sema
&S
) {
11820 // Default calling convention for main and wmain is __cdecl
11821 if (FD
->getName() == "main" || FD
->getName() == "wmain")
11824 // Default calling convention for MinGW is __cdecl
11825 const llvm::Triple
&T
= S
.Context
.getTargetInfo().getTriple();
11826 if (T
.isWindowsGNUEnvironment())
11829 // Default calling convention for WinMain, wWinMain and DllMain
11830 // is __stdcall on 32 bit Windows
11831 if (T
.isOSWindows() && T
.getArch() == llvm::Triple::x86
)
11837 void Sema::CheckMSVCRTEntryPoint(FunctionDecl
*FD
) {
11838 QualType T
= FD
->getType();
11839 assert(T
->isFunctionType() && "function decl is not of function type");
11840 const FunctionType
*FT
= T
->castAs
<FunctionType
>();
11842 // Set an implicit return of 'zero' if the function can return some integral,
11843 // enumeration, pointer or nullptr type.
11844 if (FT
->getReturnType()->isIntegralOrEnumerationType() ||
11845 FT
->getReturnType()->isAnyPointerType() ||
11846 FT
->getReturnType()->isNullPtrType())
11847 // DllMain is exempt because a return value of zero means it failed.
11848 if (FD
->getName() != "DllMain")
11849 FD
->setHasImplicitReturnZero(true);
11851 // Explicity specified calling conventions are applied to MSVC entry points
11852 if (!hasExplicitCallingConv(T
)) {
11853 if (isDefaultStdCall(FD
, *this)) {
11854 if (FT
->getCallConv() != CC_X86StdCall
) {
11855 FT
= Context
.adjustFunctionType(
11856 FT
, FT
->getExtInfo().withCallingConv(CC_X86StdCall
));
11857 FD
->setType(QualType(FT
, 0));
11859 } else if (FT
->getCallConv() != CC_C
) {
11860 FT
= Context
.adjustFunctionType(FT
,
11861 FT
->getExtInfo().withCallingConv(CC_C
));
11862 FD
->setType(QualType(FT
, 0));
11866 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
11867 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
11868 FD
->setInvalidDecl();
11872 void Sema::CheckHLSLEntryPoint(FunctionDecl
*FD
) {
11873 auto &TargetInfo
= getASTContext().getTargetInfo();
11874 auto const Triple
= TargetInfo
.getTriple();
11875 switch (Triple
.getEnvironment()) {
11877 // FIXME: check all shader profiles.
11879 case llvm::Triple::EnvironmentType::Compute
:
11880 if (!FD
->hasAttr
<HLSLNumThreadsAttr
>()) {
11881 Diag(FD
->getLocation(), diag::err_hlsl_missing_numthreads
)
11882 << Triple
.getEnvironmentName();
11883 FD
->setInvalidDecl();
11888 for (const auto *Param
: FD
->parameters()) {
11889 if (!Param
->hasAttr
<HLSLAnnotationAttr
>()) {
11890 // FIXME: Handle struct parameters where annotations are on struct fields.
11891 Diag(FD
->getLocation(), diag::err_hlsl_missing_semantic_annotation
);
11892 Diag(Param
->getLocation(), diag::note_previous_decl
) << Param
;
11893 FD
->setInvalidDecl();
11896 // FIXME: Verify return type semantic annotation.
11899 bool Sema::CheckForConstantInitializer(Expr
*Init
, QualType DclT
) {
11900 // FIXME: Need strict checking. In C89, we need to check for
11901 // any assignment, increment, decrement, function-calls, or
11902 // commas outside of a sizeof. In C99, it's the same list,
11903 // except that the aforementioned are allowed in unevaluated
11904 // expressions. Everything else falls under the
11905 // "may accept other forms of constant expressions" exception.
11907 // Regular C++ code will not end up here (exceptions: language extensions,
11908 // OpenCL C++ etc), so the constant expression rules there don't matter.
11909 if (Init
->isValueDependent()) {
11910 assert(Init
->containsErrors() &&
11911 "Dependent code should only occur in error-recovery path.");
11914 const Expr
*Culprit
;
11915 if (Init
->isConstantInitializer(Context
, false, &Culprit
))
11917 Diag(Culprit
->getExprLoc(), diag::err_init_element_not_constant
)
11918 << Culprit
->getSourceRange();
11923 // Visits an initialization expression to see if OrigDecl is evaluated in
11924 // its own initialization and throws a warning if it does.
11925 class SelfReferenceChecker
11926 : public EvaluatedExprVisitor
<SelfReferenceChecker
> {
11931 bool isReferenceType
;
11934 llvm::SmallVector
<unsigned, 4> InitFieldIndex
;
11937 typedef EvaluatedExprVisitor
<SelfReferenceChecker
> Inherited
;
11939 SelfReferenceChecker(Sema
&S
, Decl
*OrigDecl
) : Inherited(S
.Context
),
11940 S(S
), OrigDecl(OrigDecl
) {
11942 isRecordType
= false;
11943 isReferenceType
= false;
11944 isInitList
= false;
11945 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(OrigDecl
)) {
11946 isPODType
= VD
->getType().isPODType(S
.Context
);
11947 isRecordType
= VD
->getType()->isRecordType();
11948 isReferenceType
= VD
->getType()->isReferenceType();
11952 // For most expressions, just call the visitor. For initializer lists,
11953 // track the index of the field being initialized since fields are
11954 // initialized in order allowing use of previously initialized fields.
11955 void CheckExpr(Expr
*E
) {
11956 InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(E
);
11962 // Track and increment the index here.
11964 InitFieldIndex
.push_back(0);
11965 for (auto *Child
: InitList
->children()) {
11966 CheckExpr(cast
<Expr
>(Child
));
11967 ++InitFieldIndex
.back();
11969 InitFieldIndex
.pop_back();
11972 // Returns true if MemberExpr is checked and no further checking is needed.
11973 // Returns false if additional checking is required.
11974 bool CheckInitListMemberExpr(MemberExpr
*E
, bool CheckReference
) {
11975 llvm::SmallVector
<FieldDecl
*, 4> Fields
;
11977 bool ReferenceField
= false;
11979 // Get the field members used.
11980 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
11981 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
11984 Fields
.push_back(FD
);
11985 if (FD
->getType()->isReferenceType())
11986 ReferenceField
= true;
11987 Base
= ME
->getBase()->IgnoreParenImpCasts();
11990 // Keep checking only if the base Decl is the same.
11991 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
);
11992 if (!DRE
|| DRE
->getDecl() != OrigDecl
)
11995 // A reference field can be bound to an unininitialized field.
11996 if (CheckReference
&& !ReferenceField
)
11999 // Convert FieldDecls to their index number.
12000 llvm::SmallVector
<unsigned, 4> UsedFieldIndex
;
12001 for (const FieldDecl
*I
: llvm::reverse(Fields
))
12002 UsedFieldIndex
.push_back(I
->getFieldIndex());
12004 // See if a warning is needed by checking the first difference in index
12005 // numbers. If field being used has index less than the field being
12006 // initialized, then the use is safe.
12007 for (auto UsedIter
= UsedFieldIndex
.begin(),
12008 UsedEnd
= UsedFieldIndex
.end(),
12009 OrigIter
= InitFieldIndex
.begin(),
12010 OrigEnd
= InitFieldIndex
.end();
12011 UsedIter
!= UsedEnd
&& OrigIter
!= OrigEnd
; ++UsedIter
, ++OrigIter
) {
12012 if (*UsedIter
< *OrigIter
)
12014 if (*UsedIter
> *OrigIter
)
12018 // TODO: Add a different warning which will print the field names.
12019 HandleDeclRefExpr(DRE
);
12023 // For most expressions, the cast is directly above the DeclRefExpr.
12024 // For conditional operators, the cast can be outside the conditional
12025 // operator if both expressions are DeclRefExpr's.
12026 void HandleValue(Expr
*E
) {
12027 E
= E
->IgnoreParens();
12028 if (DeclRefExpr
* DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
12029 HandleDeclRefExpr(DRE
);
12033 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
12034 Visit(CO
->getCond());
12035 HandleValue(CO
->getTrueExpr());
12036 HandleValue(CO
->getFalseExpr());
12040 if (BinaryConditionalOperator
*BCO
=
12041 dyn_cast
<BinaryConditionalOperator
>(E
)) {
12042 Visit(BCO
->getCond());
12043 HandleValue(BCO
->getFalseExpr());
12047 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
12048 HandleValue(OVE
->getSourceExpr());
12052 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
12053 if (BO
->getOpcode() == BO_Comma
) {
12054 Visit(BO
->getLHS());
12055 HandleValue(BO
->getRHS());
12060 if (isa
<MemberExpr
>(E
)) {
12062 if (CheckInitListMemberExpr(cast
<MemberExpr
>(E
),
12063 false /*CheckReference*/))
12067 Expr
*Base
= E
->IgnoreParenImpCasts();
12068 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12069 // Check for static member variables and don't warn on them.
12070 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12072 Base
= ME
->getBase()->IgnoreParenImpCasts();
12074 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
))
12075 HandleDeclRefExpr(DRE
);
12082 // Reference types not handled in HandleValue are handled here since all
12083 // uses of references are bad, not just r-value uses.
12084 void VisitDeclRefExpr(DeclRefExpr
*E
) {
12085 if (isReferenceType
)
12086 HandleDeclRefExpr(E
);
12089 void VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
12090 if (E
->getCastKind() == CK_LValueToRValue
) {
12091 HandleValue(E
->getSubExpr());
12095 Inherited::VisitImplicitCastExpr(E
);
12098 void VisitMemberExpr(MemberExpr
*E
) {
12100 if (CheckInitListMemberExpr(E
, true /*CheckReference*/))
12104 // Don't warn on arrays since they can be treated as pointers.
12105 if (E
->getType()->canDecayToPointerType()) return;
12107 // Warn when a non-static method call is followed by non-static member
12108 // field accesses, which is followed by a DeclRefExpr.
12109 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl());
12110 bool Warn
= (MD
&& !MD
->isStatic());
12111 Expr
*Base
= E
->getBase()->IgnoreParenImpCasts();
12112 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12113 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12115 Base
= ME
->getBase()->IgnoreParenImpCasts();
12118 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
)) {
12120 HandleDeclRefExpr(DRE
);
12124 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12125 // Visit that expression.
12129 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
12130 Expr
*Callee
= E
->getCallee();
12132 if (isa
<UnresolvedLookupExpr
>(Callee
))
12133 return Inherited::VisitCXXOperatorCallExpr(E
);
12136 for (auto Arg
: E
->arguments())
12137 HandleValue(Arg
->IgnoreParenImpCasts());
12140 void VisitUnaryOperator(UnaryOperator
*E
) {
12141 // For POD record types, addresses of its own members are well-defined.
12142 if (E
->getOpcode() == UO_AddrOf
&& isRecordType
&&
12143 isa
<MemberExpr
>(E
->getSubExpr()->IgnoreParens())) {
12145 HandleValue(E
->getSubExpr());
12149 if (E
->isIncrementDecrementOp()) {
12150 HandleValue(E
->getSubExpr());
12154 Inherited::VisitUnaryOperator(E
);
12157 void VisitObjCMessageExpr(ObjCMessageExpr
*E
) {}
12159 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
12160 if (E
->getConstructor()->isCopyConstructor()) {
12161 Expr
*ArgExpr
= E
->getArg(0);
12162 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(ArgExpr
))
12163 if (ILE
->getNumInits() == 1)
12164 ArgExpr
= ILE
->getInit(0);
12165 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
12166 if (ICE
->getCastKind() == CK_NoOp
)
12167 ArgExpr
= ICE
->getSubExpr();
12168 HandleValue(ArgExpr
);
12171 Inherited::VisitCXXConstructExpr(E
);
12174 void VisitCallExpr(CallExpr
*E
) {
12175 // Treat std::move as a use.
12176 if (E
->isCallToStdMove()) {
12177 HandleValue(E
->getArg(0));
12181 Inherited::VisitCallExpr(E
);
12184 void VisitBinaryOperator(BinaryOperator
*E
) {
12185 if (E
->isCompoundAssignmentOp()) {
12186 HandleValue(E
->getLHS());
12187 Visit(E
->getRHS());
12191 Inherited::VisitBinaryOperator(E
);
12194 // A custom visitor for BinaryConditionalOperator is needed because the
12195 // regular visitor would check the condition and true expression separately
12196 // but both point to the same place giving duplicate diagnostics.
12197 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
12198 Visit(E
->getCond());
12199 Visit(E
->getFalseExpr());
12202 void HandleDeclRefExpr(DeclRefExpr
*DRE
) {
12203 Decl
* ReferenceDecl
= DRE
->getDecl();
12204 if (OrigDecl
!= ReferenceDecl
) return;
12206 if (isReferenceType
) {
12207 diag
= diag::warn_uninit_self_reference_in_reference_init
;
12208 } else if (cast
<VarDecl
>(OrigDecl
)->isStaticLocal()) {
12209 diag
= diag::warn_static_self_reference_in_init
;
12210 } else if (isa
<TranslationUnitDecl
>(OrigDecl
->getDeclContext()) ||
12211 isa
<NamespaceDecl
>(OrigDecl
->getDeclContext()) ||
12212 DRE
->getDecl()->getType()->isRecordType()) {
12213 diag
= diag::warn_uninit_self_reference_in_init
;
12215 // Local variables will be handled by the CFG analysis.
12219 S
.DiagRuntimeBehavior(DRE
->getBeginLoc(), DRE
,
12221 << DRE
->getDecl() << OrigDecl
->getLocation()
12222 << DRE
->getSourceRange());
12226 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12227 static void CheckSelfReference(Sema
&S
, Decl
* OrigDecl
, Expr
*E
,
12229 // Parameters arguments are occassionially constructed with itself,
12230 // for instance, in recursive functions. Skip them.
12231 if (isa
<ParmVarDecl
>(OrigDecl
))
12234 E
= E
->IgnoreParens();
12236 // Skip checking T a = a where T is not a record or reference type.
12237 // Doing so is a way to silence uninitialized warnings.
12238 if (!DirectInit
&& !cast
<VarDecl
>(OrigDecl
)->getType()->isRecordType())
12239 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
12240 if (ICE
->getCastKind() == CK_LValueToRValue
)
12241 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ICE
->getSubExpr()))
12242 if (DRE
->getDecl() == OrigDecl
)
12245 SelfReferenceChecker(S
, OrigDecl
).CheckExpr(E
);
12247 } // end anonymous namespace
12250 // Simple wrapper to add the name of a variable or (if no variable is
12251 // available) a DeclarationName into a diagnostic.
12252 struct VarDeclOrName
{
12254 DeclarationName Name
;
12256 friend const Sema::SemaDiagnosticBuilder
&
12257 operator<<(const Sema::SemaDiagnosticBuilder
&Diag
, VarDeclOrName VN
) {
12258 return VN
.VDecl
? Diag
<< VN
.VDecl
: Diag
<< VN
.Name
;
12261 } // end anonymous namespace
12263 QualType
Sema::deduceVarTypeFromInitializer(VarDecl
*VDecl
,
12264 DeclarationName Name
, QualType Type
,
12265 TypeSourceInfo
*TSI
,
12266 SourceRange Range
, bool DirectInit
,
12268 bool IsInitCapture
= !VDecl
;
12269 assert((!VDecl
|| !VDecl
->isInitCapture()) &&
12270 "init captures are expected to be deduced prior to initialization");
12272 VarDeclOrName VN
{VDecl
, Name
};
12274 DeducedType
*Deduced
= Type
->getContainedDeducedType();
12275 assert(Deduced
&& "deduceVarTypeFromInitializer for non-deduced type");
12277 // C++11 [dcl.spec.auto]p3
12279 assert(VDecl
&& "no init for init capture deduction?");
12281 // Except for class argument deduction, and then for an initializing
12282 // declaration only, i.e. no static at class scope or extern.
12283 if (!isa
<DeducedTemplateSpecializationType
>(Deduced
) ||
12284 VDecl
->hasExternalStorage() ||
12285 VDecl
->isStaticDataMember()) {
12286 Diag(VDecl
->getLocation(), diag::err_auto_var_requires_init
)
12287 << VDecl
->getDeclName() << Type
;
12292 ArrayRef
<Expr
*> DeduceInits
;
12294 DeduceInits
= Init
;
12297 if (auto *PL
= dyn_cast_or_null
<ParenListExpr
>(Init
))
12298 DeduceInits
= PL
->exprs();
12301 if (isa
<DeducedTemplateSpecializationType
>(Deduced
)) {
12302 assert(VDecl
&& "non-auto type for init capture deduction?");
12303 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
12304 InitializationKind Kind
= InitializationKind::CreateForInit(
12305 VDecl
->getLocation(), DirectInit
, Init
);
12306 // FIXME: Initialization should not be taking a mutable list of inits.
12307 SmallVector
<Expr
*, 8> InitsCopy(DeduceInits
.begin(), DeduceInits
.end());
12308 return DeduceTemplateSpecializationFromInitializer(TSI
, Entity
, Kind
,
12313 if (auto *IL
= dyn_cast
<InitListExpr
>(Init
))
12314 DeduceInits
= IL
->inits();
12317 // Deduction only works if we have exactly one source expression.
12318 if (DeduceInits
.empty()) {
12319 // It isn't possible to write this directly, but it is possible to
12320 // end up in this situation with "auto x(some_pack...);"
12321 Diag(Init
->getBeginLoc(), IsInitCapture
12322 ? diag::err_init_capture_no_expression
12323 : diag::err_auto_var_init_no_expression
)
12324 << VN
<< Type
<< Range
;
12328 if (DeduceInits
.size() > 1) {
12329 Diag(DeduceInits
[1]->getBeginLoc(),
12330 IsInitCapture
? diag::err_init_capture_multiple_expressions
12331 : diag::err_auto_var_init_multiple_expressions
)
12332 << VN
<< Type
<< Range
;
12336 Expr
*DeduceInit
= DeduceInits
[0];
12337 if (DirectInit
&& isa
<InitListExpr
>(DeduceInit
)) {
12338 Diag(Init
->getBeginLoc(), IsInitCapture
12339 ? diag::err_init_capture_paren_braces
12340 : diag::err_auto_var_init_paren_braces
)
12341 << isa
<InitListExpr
>(Init
) << VN
<< Type
<< Range
;
12345 // Expressions default to 'id' when we're in a debugger.
12346 bool DefaultedAnyToId
= false;
12347 if (getLangOpts().DebuggerCastResultToId
&&
12348 Init
->getType() == Context
.UnknownAnyTy
&& !IsInitCapture
) {
12349 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
12350 if (Result
.isInvalid()) {
12353 Init
= Result
.get();
12354 DefaultedAnyToId
= true;
12357 // C++ [dcl.decomp]p1:
12358 // If the assignment-expression [...] has array type A and no ref-qualifier
12359 // is present, e has type cv A
12360 if (VDecl
&& isa
<DecompositionDecl
>(VDecl
) &&
12361 Context
.hasSameUnqualifiedType(Type
, Context
.getAutoDeductType()) &&
12362 DeduceInit
->getType()->isConstantArrayType())
12363 return Context
.getQualifiedType(DeduceInit
->getType(),
12364 Type
.getQualifiers());
12366 QualType DeducedType
;
12367 TemplateDeductionInfo
Info(DeduceInit
->getExprLoc());
12368 TemplateDeductionResult Result
=
12369 DeduceAutoType(TSI
->getTypeLoc(), DeduceInit
, DeducedType
, Info
);
12370 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
) {
12371 if (!IsInitCapture
)
12372 DiagnoseAutoDeductionFailure(VDecl
, DeduceInit
);
12373 else if (isa
<InitListExpr
>(Init
))
12374 Diag(Range
.getBegin(),
12375 diag::err_init_capture_deduction_failure_from_init_list
)
12377 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12378 : DeduceInit
->getType())
12379 << DeduceInit
->getSourceRange();
12381 Diag(Range
.getBegin(), diag::err_init_capture_deduction_failure
)
12382 << VN
<< TSI
->getType()
12383 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12384 : DeduceInit
->getType())
12385 << DeduceInit
->getSourceRange();
12388 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12389 // 'id' instead of a specific object type prevents most of our usual
12391 // We only want to warn outside of template instantiations, though:
12392 // inside a template, the 'id' could have come from a parameter.
12393 if (!inTemplateInstantiation() && !DefaultedAnyToId
&& !IsInitCapture
&&
12394 !DeducedType
.isNull() && DeducedType
->isObjCIdType()) {
12395 SourceLocation Loc
= TSI
->getTypeLoc().getBeginLoc();
12396 Diag(Loc
, diag::warn_auto_var_is_id
) << VN
<< Range
;
12399 return DeducedType
;
12402 bool Sema::DeduceVariableDeclarationType(VarDecl
*VDecl
, bool DirectInit
,
12404 assert(!Init
|| !Init
->containsErrors());
12405 QualType DeducedType
= deduceVarTypeFromInitializer(
12406 VDecl
, VDecl
->getDeclName(), VDecl
->getType(), VDecl
->getTypeSourceInfo(),
12407 VDecl
->getSourceRange(), DirectInit
, Init
);
12408 if (DeducedType
.isNull()) {
12409 VDecl
->setInvalidDecl();
12413 VDecl
->setType(DeducedType
);
12414 assert(VDecl
->isLinkageValid());
12416 // In ARC, infer lifetime.
12417 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(VDecl
))
12418 VDecl
->setInvalidDecl();
12420 if (getLangOpts().OpenCL
)
12421 deduceOpenCLAddressSpace(VDecl
);
12423 // If this is a redeclaration, check that the type we just deduced matches
12424 // the previously declared type.
12425 if (VarDecl
*Old
= VDecl
->getPreviousDecl()) {
12426 // We never need to merge the type, because we cannot form an incomplete
12427 // array of auto, nor deduce such a type.
12428 MergeVarDeclTypes(VDecl
, Old
, /*MergeTypeWithPrevious*/ false);
12431 // Check the deduced type is valid for a variable declaration.
12432 CheckVariableDeclarationType(VDecl
);
12433 return VDecl
->isInvalidDecl();
12436 void Sema::checkNonTrivialCUnionInInitializer(const Expr
*Init
,
12437 SourceLocation Loc
) {
12438 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(Init
))
12439 Init
= EWC
->getSubExpr();
12441 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
))
12442 Init
= CE
->getSubExpr();
12444 QualType InitType
= Init
->getType();
12445 assert((InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12446 InitType
.hasNonTrivialToPrimitiveCopyCUnion()) &&
12447 "shouldn't be called if type doesn't have a non-trivial C struct");
12448 if (auto *ILE
= dyn_cast
<InitListExpr
>(Init
)) {
12449 for (auto *I
: ILE
->inits()) {
12450 if (!I
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12451 !I
->getType().hasNonTrivialToPrimitiveCopyCUnion())
12453 SourceLocation SL
= I
->getExprLoc();
12454 checkNonTrivialCUnionInInitializer(I
, SL
.isValid() ? SL
: Loc
);
12459 if (isa
<ImplicitValueInitExpr
>(Init
)) {
12460 if (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12461 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_DefaultInitializedObject
,
12464 // Assume all other explicit initializers involving copying some existing
12466 // TODO: ignore any explicit initializers where we can guarantee
12468 if (InitType
.hasNonTrivialToPrimitiveCopyCUnion())
12469 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_CopyInit
, NTCUK_Copy
);
12475 bool shouldIgnoreForRecordTriviality(const FieldDecl
*FD
) {
12476 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12477 // in the source code or implicitly by the compiler if it is in a union
12478 // defined in a system header and has non-trivial ObjC ownership
12479 // qualifications. We don't want those fields to participate in determining
12480 // whether the containing union is non-trivial.
12481 return FD
->hasAttr
<UnavailableAttr
>();
12484 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12485 : DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
12488 DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
12491 DiagNonTrivalCUnionDefaultInitializeVisitor(
12492 QualType OrigTy
, SourceLocation OrigLoc
,
12493 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
12494 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12496 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK
, QualType QT
,
12497 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12498 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12499 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12500 InNonTrivialUnion
);
12501 return Super::visitWithKind(PDIK
, QT
, FD
, InNonTrivialUnion
);
12504 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12505 bool InNonTrivialUnion
) {
12506 if (InNonTrivialUnion
)
12507 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12508 << 1 << 0 << QT
<< FD
->getName();
12511 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12512 if (InNonTrivialUnion
)
12513 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12514 << 1 << 0 << QT
<< FD
->getName();
12517 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12518 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12519 if (RD
->isUnion()) {
12520 if (OrigLoc
.isValid()) {
12521 bool IsUnion
= false;
12522 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12523 IsUnion
= OrigRD
->isUnion();
12524 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12525 << 0 << OrigTy
<< IsUnion
<< UseContext
;
12526 // Reset OrigLoc so that this diagnostic is emitted only once.
12527 OrigLoc
= SourceLocation();
12529 InNonTrivialUnion
= true;
12532 if (InNonTrivialUnion
)
12533 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12534 << 0 << 0 << QT
.getUnqualifiedType() << "";
12536 for (const FieldDecl
*FD
: RD
->fields())
12537 if (!shouldIgnoreForRecordTriviality(FD
))
12538 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12541 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12543 // The non-trivial C union type or the struct/union type that contains a
12544 // non-trivial C union.
12546 SourceLocation OrigLoc
;
12547 Sema::NonTrivialCUnionContext UseContext
;
12551 struct DiagNonTrivalCUnionDestructedTypeVisitor
12552 : DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void> {
12554 DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void>;
12556 DiagNonTrivalCUnionDestructedTypeVisitor(
12557 QualType OrigTy
, SourceLocation OrigLoc
,
12558 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
12559 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12561 void visitWithKind(QualType::DestructionKind DK
, QualType QT
,
12562 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12563 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12564 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12565 InNonTrivialUnion
);
12566 return Super::visitWithKind(DK
, QT
, FD
, InNonTrivialUnion
);
12569 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12570 bool InNonTrivialUnion
) {
12571 if (InNonTrivialUnion
)
12572 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12573 << 1 << 1 << QT
<< FD
->getName();
12576 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12577 if (InNonTrivialUnion
)
12578 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12579 << 1 << 1 << QT
<< FD
->getName();
12582 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12583 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12584 if (RD
->isUnion()) {
12585 if (OrigLoc
.isValid()) {
12586 bool IsUnion
= false;
12587 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12588 IsUnion
= OrigRD
->isUnion();
12589 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12590 << 1 << OrigTy
<< IsUnion
<< UseContext
;
12591 // Reset OrigLoc so that this diagnostic is emitted only once.
12592 OrigLoc
= SourceLocation();
12594 InNonTrivialUnion
= true;
12597 if (InNonTrivialUnion
)
12598 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12599 << 0 << 1 << QT
.getUnqualifiedType() << "";
12601 for (const FieldDecl
*FD
: RD
->fields())
12602 if (!shouldIgnoreForRecordTriviality(FD
))
12603 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12606 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12607 void visitCXXDestructor(QualType QT
, const FieldDecl
*FD
,
12608 bool InNonTrivialUnion
) {}
12610 // The non-trivial C union type or the struct/union type that contains a
12611 // non-trivial C union.
12613 SourceLocation OrigLoc
;
12614 Sema::NonTrivialCUnionContext UseContext
;
12618 struct DiagNonTrivalCUnionCopyVisitor
12619 : CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void> {
12620 using Super
= CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void>;
12622 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy
, SourceLocation OrigLoc
,
12623 Sema::NonTrivialCUnionContext UseContext
,
12625 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12627 void visitWithKind(QualType::PrimitiveCopyKind PCK
, QualType QT
,
12628 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12629 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12630 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12631 InNonTrivialUnion
);
12632 return Super::visitWithKind(PCK
, QT
, FD
, InNonTrivialUnion
);
12635 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12636 bool InNonTrivialUnion
) {
12637 if (InNonTrivialUnion
)
12638 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12639 << 1 << 2 << QT
<< FD
->getName();
12642 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12643 if (InNonTrivialUnion
)
12644 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12645 << 1 << 2 << QT
<< FD
->getName();
12648 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12649 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12650 if (RD
->isUnion()) {
12651 if (OrigLoc
.isValid()) {
12652 bool IsUnion
= false;
12653 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12654 IsUnion
= OrigRD
->isUnion();
12655 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12656 << 2 << OrigTy
<< IsUnion
<< UseContext
;
12657 // Reset OrigLoc so that this diagnostic is emitted only once.
12658 OrigLoc
= SourceLocation();
12660 InNonTrivialUnion
= true;
12663 if (InNonTrivialUnion
)
12664 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12665 << 0 << 2 << QT
.getUnqualifiedType() << "";
12667 for (const FieldDecl
*FD
: RD
->fields())
12668 if (!shouldIgnoreForRecordTriviality(FD
))
12669 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12672 void preVisit(QualType::PrimitiveCopyKind PCK
, QualType QT
,
12673 const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12674 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12675 void visitVolatileTrivial(QualType QT
, const FieldDecl
*FD
,
12676 bool InNonTrivialUnion
) {}
12678 // The non-trivial C union type or the struct/union type that contains a
12679 // non-trivial C union.
12681 SourceLocation OrigLoc
;
12682 Sema::NonTrivialCUnionContext UseContext
;
12688 void Sema::checkNonTrivialCUnion(QualType QT
, SourceLocation Loc
,
12689 NonTrivialCUnionContext UseContext
,
12690 unsigned NonTrivialKind
) {
12691 assert((QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12692 QT
.hasNonTrivialToPrimitiveDestructCUnion() ||
12693 QT
.hasNonTrivialToPrimitiveCopyCUnion()) &&
12694 "shouldn't be called if type doesn't have a non-trivial C union");
12696 if ((NonTrivialKind
& NTCUK_Init
) &&
12697 QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12698 DiagNonTrivalCUnionDefaultInitializeVisitor(QT
, Loc
, UseContext
, *this)
12699 .visit(QT
, nullptr, false);
12700 if ((NonTrivialKind
& NTCUK_Destruct
) &&
12701 QT
.hasNonTrivialToPrimitiveDestructCUnion())
12702 DiagNonTrivalCUnionDestructedTypeVisitor(QT
, Loc
, UseContext
, *this)
12703 .visit(QT
, nullptr, false);
12704 if ((NonTrivialKind
& NTCUK_Copy
) && QT
.hasNonTrivialToPrimitiveCopyCUnion())
12705 DiagNonTrivalCUnionCopyVisitor(QT
, Loc
, UseContext
, *this)
12706 .visit(QT
, nullptr, false);
12709 /// AddInitializerToDecl - Adds the initializer Init to the
12710 /// declaration dcl. If DirectInit is true, this is C++ direct
12711 /// initialization rather than copy initialization.
12712 void Sema::AddInitializerToDecl(Decl
*RealDecl
, Expr
*Init
, bool DirectInit
) {
12713 // If there is no declaration, there was an error parsing it. Just ignore
12714 // the initializer.
12715 if (!RealDecl
|| RealDecl
->isInvalidDecl()) {
12716 CorrectDelayedTyposInExpr(Init
, dyn_cast_or_null
<VarDecl
>(RealDecl
));
12720 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(RealDecl
)) {
12721 // Pure-specifiers are handled in ActOnPureSpecifier.
12722 Diag(Method
->getLocation(), diag::err_member_function_initialization
)
12723 << Method
->getDeclName() << Init
->getSourceRange();
12724 Method
->setInvalidDecl();
12728 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
12730 assert(!isa
<FieldDecl
>(RealDecl
) && "field init shouldn't get here");
12731 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
12732 RealDecl
->setInvalidDecl();
12736 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12737 if (VDecl
->getType()->isUndeducedType()) {
12738 // Attempt typo correction early so that the type of the init expression can
12739 // be deduced based on the chosen correction if the original init contains a
12741 ExprResult Res
= CorrectDelayedTyposInExpr(Init
, VDecl
);
12742 if (!Res
.isUsable()) {
12743 // There are unresolved typos in Init, just drop them.
12744 // FIXME: improve the recovery strategy to preserve the Init.
12745 RealDecl
->setInvalidDecl();
12748 if (Res
.get()->containsErrors()) {
12749 // Invalidate the decl as we don't know the type for recovery-expr yet.
12750 RealDecl
->setInvalidDecl();
12751 VDecl
->setInit(Res
.get());
12756 if (DeduceVariableDeclarationType(VDecl
, DirectInit
, Init
))
12760 // dllimport cannot be used on variable definitions.
12761 if (VDecl
->hasAttr
<DLLImportAttr
>() && !VDecl
->isStaticDataMember()) {
12762 Diag(VDecl
->getLocation(), diag::err_attribute_dllimport_data_definition
);
12763 VDecl
->setInvalidDecl();
12767 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
12768 // the identifier has external or internal linkage, the declaration shall
12769 // have no initializer for the identifier.
12770 // C++14 [dcl.init]p5 is the same restriction for C++.
12771 if (VDecl
->isLocalVarDecl() && VDecl
->hasExternalStorage()) {
12772 Diag(VDecl
->getLocation(), diag::err_block_extern_cant_init
);
12773 VDecl
->setInvalidDecl();
12777 if (!VDecl
->getType()->isDependentType()) {
12778 // A definition must end up with a complete type, which means it must be
12779 // complete with the restriction that an array type might be completed by
12780 // the initializer; note that later code assumes this restriction.
12781 QualType BaseDeclType
= VDecl
->getType();
12782 if (const ArrayType
*Array
= Context
.getAsIncompleteArrayType(BaseDeclType
))
12783 BaseDeclType
= Array
->getElementType();
12784 if (RequireCompleteType(VDecl
->getLocation(), BaseDeclType
,
12785 diag::err_typecheck_decl_incomplete_type
)) {
12786 RealDecl
->setInvalidDecl();
12790 // The variable can not have an abstract class type.
12791 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
12792 diag::err_abstract_type_in_decl
,
12793 AbstractVariableType
))
12794 VDecl
->setInvalidDecl();
12797 // If adding the initializer will turn this declaration into a definition,
12798 // and we already have a definition for this variable, diagnose or otherwise
12799 // handle the situation.
12800 if (VarDecl
*Def
= VDecl
->getDefinition())
12801 if (Def
!= VDecl
&&
12802 (!VDecl
->isStaticDataMember() || VDecl
->isOutOfLine()) &&
12803 !VDecl
->isThisDeclarationADemotedDefinition() &&
12804 checkVarDeclRedefinition(Def
, VDecl
))
12807 if (getLangOpts().CPlusPlus
) {
12808 // C++ [class.static.data]p4
12809 // If a static data member is of const integral or const
12810 // enumeration type, its declaration in the class definition can
12811 // specify a constant-initializer which shall be an integral
12812 // constant expression (5.19). In that case, the member can appear
12813 // in integral constant expressions. The member shall still be
12814 // defined in a namespace scope if it is used in the program and the
12815 // namespace scope definition shall not contain an initializer.
12817 // We already performed a redefinition check above, but for static
12818 // data members we also need to check whether there was an in-class
12819 // declaration with an initializer.
12820 if (VDecl
->isStaticDataMember() && VDecl
->getCanonicalDecl()->hasInit()) {
12821 Diag(Init
->getExprLoc(), diag::err_static_data_member_reinitialization
)
12822 << VDecl
->getDeclName();
12823 Diag(VDecl
->getCanonicalDecl()->getInit()->getExprLoc(),
12824 diag::note_previous_initializer
)
12829 if (VDecl
->hasLocalStorage())
12830 setFunctionHasBranchProtectedScope();
12832 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
)) {
12833 VDecl
->setInvalidDecl();
12838 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12839 // a kernel function cannot be initialized."
12840 if (VDecl
->getType().getAddressSpace() == LangAS::opencl_local
) {
12841 Diag(VDecl
->getLocation(), diag::err_local_cant_init
);
12842 VDecl
->setInvalidDecl();
12846 // The LoaderUninitialized attribute acts as a definition (of undef).
12847 if (VDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
12848 Diag(VDecl
->getLocation(), diag::err_loader_uninitialized_cant_init
);
12849 VDecl
->setInvalidDecl();
12853 // Get the decls type and save a reference for later, since
12854 // CheckInitializerTypes may change it.
12855 QualType DclT
= VDecl
->getType(), SavT
= DclT
;
12857 // Expressions default to 'id' when we're in a debugger
12858 // and we are assigning it to a variable of Objective-C pointer type.
12859 if (getLangOpts().DebuggerCastResultToId
&& DclT
->isObjCObjectPointerType() &&
12860 Init
->getType() == Context
.UnknownAnyTy
) {
12861 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
12862 if (Result
.isInvalid()) {
12863 VDecl
->setInvalidDecl();
12866 Init
= Result
.get();
12869 // Perform the initialization.
12870 ParenListExpr
*CXXDirectInit
= dyn_cast
<ParenListExpr
>(Init
);
12871 if (!VDecl
->isInvalidDecl()) {
12872 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
12873 InitializationKind Kind
= InitializationKind::CreateForInit(
12874 VDecl
->getLocation(), DirectInit
, Init
);
12876 MultiExprArg Args
= Init
;
12878 Args
= MultiExprArg(CXXDirectInit
->getExprs(),
12879 CXXDirectInit
->getNumExprs());
12881 // Try to correct any TypoExprs in the initialization arguments.
12882 for (size_t Idx
= 0; Idx
< Args
.size(); ++Idx
) {
12883 ExprResult Res
= CorrectDelayedTyposInExpr(
12884 Args
[Idx
], VDecl
, /*RecoverUncorrectedTypos=*/true,
12885 [this, Entity
, Kind
](Expr
*E
) {
12886 InitializationSequence
Init(*this, Entity
, Kind
, MultiExprArg(E
));
12887 return Init
.Failed() ? ExprError() : E
;
12889 if (Res
.isInvalid()) {
12890 VDecl
->setInvalidDecl();
12891 } else if (Res
.get() != Args
[Idx
]) {
12892 Args
[Idx
] = Res
.get();
12895 if (VDecl
->isInvalidDecl())
12898 InitializationSequence
InitSeq(*this, Entity
, Kind
, Args
,
12899 /*TopLevelOfInitList=*/false,
12900 /*TreatUnavailableAsInvalid=*/false);
12901 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Args
, &DclT
);
12902 if (Result
.isInvalid()) {
12903 // If the provided initializer fails to initialize the var decl,
12904 // we attach a recovery expr for better recovery.
12905 auto RecoveryExpr
=
12906 CreateRecoveryExpr(Init
->getBeginLoc(), Init
->getEndLoc(), Args
);
12907 if (RecoveryExpr
.get())
12908 VDecl
->setInit(RecoveryExpr
.get());
12912 Init
= Result
.getAs
<Expr
>();
12915 // Check for self-references within variable initializers.
12916 // Variables declared within a function/method body (except for references)
12917 // are handled by a dataflow analysis.
12918 // This is undefined behavior in C++, but valid in C.
12919 if (getLangOpts().CPlusPlus
)
12920 if (!VDecl
->hasLocalStorage() || VDecl
->getType()->isRecordType() ||
12921 VDecl
->getType()->isReferenceType())
12922 CheckSelfReference(*this, RealDecl
, Init
, DirectInit
);
12924 // If the type changed, it means we had an incomplete type that was
12925 // completed by the initializer. For example:
12926 // int ary[] = { 1, 3, 5 };
12927 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12928 if (!VDecl
->isInvalidDecl() && (DclT
!= SavT
))
12929 VDecl
->setType(DclT
);
12931 if (!VDecl
->isInvalidDecl()) {
12932 checkUnsafeAssigns(VDecl
->getLocation(), VDecl
->getType(), Init
);
12934 if (VDecl
->hasAttr
<BlocksAttr
>())
12935 checkRetainCycles(VDecl
, Init
);
12937 // It is safe to assign a weak reference into a strong variable.
12938 // Although this code can still have problems:
12939 // id x = self.weakProp;
12940 // id y = self.weakProp;
12941 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12942 // paths through the function. This should be revisited if
12943 // -Wrepeated-use-of-weak is made flow-sensitive.
12944 if (FunctionScopeInfo
*FSI
= getCurFunction())
12945 if ((VDecl
->getType().getObjCLifetime() == Qualifiers::OCL_Strong
||
12946 VDecl
->getType().isNonWeakInMRRWithObjCWeak(Context
)) &&
12947 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
12948 Init
->getBeginLoc()))
12949 FSI
->markSafeWeakUse(Init
);
12952 // The initialization is usually a full-expression.
12954 // FIXME: If this is a braced initialization of an aggregate, it is not
12955 // an expression, and each individual field initializer is a separate
12956 // full-expression. For instance, in:
12958 // struct Temp { ~Temp(); };
12959 // struct S { S(Temp); };
12960 // struct T { S a, b; } t = { Temp(), Temp() }
12962 // we should destroy the first Temp before constructing the second.
12963 ExprResult Result
=
12964 ActOnFinishFullExpr(Init
, VDecl
->getLocation(),
12965 /*DiscardedValue*/ false, VDecl
->isConstexpr());
12966 if (Result
.isInvalid()) {
12967 VDecl
->setInvalidDecl();
12970 Init
= Result
.get();
12972 // Attach the initializer to the decl.
12973 VDecl
->setInit(Init
);
12975 if (VDecl
->isLocalVarDecl()) {
12976 // Don't check the initializer if the declaration is malformed.
12977 if (VDecl
->isInvalidDecl()) {
12980 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12981 // This is true even in C++ for OpenCL.
12982 } else if (VDecl
->getType().getAddressSpace() == LangAS::opencl_constant
) {
12983 CheckForConstantInitializer(Init
, DclT
);
12985 // Otherwise, C++ does not restrict the initializer.
12986 } else if (getLangOpts().CPlusPlus
) {
12989 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12990 // static storage duration shall be constant expressions or string literals.
12991 } else if (VDecl
->getStorageClass() == SC_Static
) {
12992 CheckForConstantInitializer(Init
, DclT
);
12994 // C89 is stricter than C99 for aggregate initializers.
12995 // C89 6.5.7p3: All the expressions [...] in an initializer list
12996 // for an object that has aggregate or union type shall be
12997 // constant expressions.
12998 } else if (!getLangOpts().C99
&& VDecl
->getType()->isAggregateType() &&
12999 isa
<InitListExpr
>(Init
)) {
13000 const Expr
*Culprit
;
13001 if (!Init
->isConstantInitializer(Context
, false, &Culprit
)) {
13002 Diag(Culprit
->getExprLoc(),
13003 diag::ext_aggregate_init_not_constant
)
13004 << Culprit
->getSourceRange();
13008 if (auto *E
= dyn_cast
<ExprWithCleanups
>(Init
))
13009 if (auto *BE
= dyn_cast
<BlockExpr
>(E
->getSubExpr()->IgnoreParens()))
13010 if (VDecl
->hasLocalStorage())
13011 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
13012 } else if (VDecl
->isStaticDataMember() && !VDecl
->isInline() &&
13013 VDecl
->getLexicalDeclContext()->isRecord()) {
13014 // This is an in-class initialization for a static data member, e.g.,
13017 // static const int value = 17;
13020 // C++ [class.mem]p4:
13021 // A member-declarator can contain a constant-initializer only
13022 // if it declares a static member (9.4) of const integral or
13023 // const enumeration type, see 9.4.2.
13025 // C++11 [class.static.data]p3:
13026 // If a non-volatile non-inline const static data member is of integral
13027 // or enumeration type, its declaration in the class definition can
13028 // specify a brace-or-equal-initializer in which every initializer-clause
13029 // that is an assignment-expression is a constant expression. A static
13030 // data member of literal type can be declared in the class definition
13031 // with the constexpr specifier; if so, its declaration shall specify a
13032 // brace-or-equal-initializer in which every initializer-clause that is
13033 // an assignment-expression is a constant expression.
13035 // Do nothing on dependent types.
13036 if (DclT
->isDependentType()) {
13038 // Allow any 'static constexpr' members, whether or not they are of literal
13039 // type. We separately check that every constexpr variable is of literal
13041 } else if (VDecl
->isConstexpr()) {
13043 // Require constness.
13044 } else if (!DclT
.isConstQualified()) {
13045 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_non_const
)
13046 << Init
->getSourceRange();
13047 VDecl
->setInvalidDecl();
13049 // We allow integer constant expressions in all cases.
13050 } else if (DclT
->isIntegralOrEnumerationType()) {
13051 // Check whether the expression is a constant expression.
13052 SourceLocation Loc
;
13053 if (getLangOpts().CPlusPlus11
&& DclT
.isVolatileQualified())
13054 // In C++11, a non-constexpr const static data member with an
13055 // in-class initializer cannot be volatile.
13056 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_volatile
);
13057 else if (Init
->isValueDependent())
13058 ; // Nothing to check.
13059 else if (Init
->isIntegerConstantExpr(Context
, &Loc
))
13060 ; // Ok, it's an ICE!
13061 else if (Init
->getType()->isScopedEnumeralType() &&
13062 Init
->isCXX11ConstantExpr(Context
))
13063 ; // Ok, it is a scoped-enum constant expression.
13064 else if (Init
->isEvaluatable(Context
)) {
13065 // If we can constant fold the initializer through heroics, accept it,
13066 // but report this as a use of an extension for -pedantic.
13067 Diag(Loc
, diag::ext_in_class_initializer_non_constant
)
13068 << Init
->getSourceRange();
13070 // Otherwise, this is some crazy unknown case. Report the issue at the
13071 // location provided by the isIntegerConstantExpr failed check.
13072 Diag(Loc
, diag::err_in_class_initializer_non_constant
)
13073 << Init
->getSourceRange();
13074 VDecl
->setInvalidDecl();
13077 // We allow foldable floating-point constants as an extension.
13078 } else if (DclT
->isFloatingType()) { // also permits complex, which is ok
13079 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13080 // it anyway and provide a fixit to add the 'constexpr'.
13081 if (getLangOpts().CPlusPlus11
) {
13082 Diag(VDecl
->getLocation(),
13083 diag::ext_in_class_initializer_float_type_cxx11
)
13084 << DclT
<< Init
->getSourceRange();
13085 Diag(VDecl
->getBeginLoc(),
13086 diag::note_in_class_initializer_float_type_cxx11
)
13087 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13089 Diag(VDecl
->getLocation(), diag::ext_in_class_initializer_float_type
)
13090 << DclT
<< Init
->getSourceRange();
13092 if (!Init
->isValueDependent() && !Init
->isEvaluatable(Context
)) {
13093 Diag(Init
->getExprLoc(), diag::err_in_class_initializer_non_constant
)
13094 << Init
->getSourceRange();
13095 VDecl
->setInvalidDecl();
13099 // Suggest adding 'constexpr' in C++11 for literal types.
13100 } else if (getLangOpts().CPlusPlus11
&& DclT
->isLiteralType(Context
)) {
13101 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_literal_type
)
13102 << DclT
<< Init
->getSourceRange()
13103 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13104 VDecl
->setConstexpr(true);
13107 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_bad_type
)
13108 << DclT
<< Init
->getSourceRange();
13109 VDecl
->setInvalidDecl();
13111 } else if (VDecl
->isFileVarDecl()) {
13112 // In C, extern is typically used to avoid tentative definitions when
13113 // declaring variables in headers, but adding an intializer makes it a
13114 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13115 // In C++, extern is often used to give implictly static const variables
13116 // external linkage, so don't warn in that case. If selectany is present,
13117 // this might be header code intended for C and C++ inclusion, so apply the
13119 if (VDecl
->getStorageClass() == SC_Extern
&&
13120 ((!getLangOpts().CPlusPlus
&& !VDecl
->hasAttr
<SelectAnyAttr
>()) ||
13121 !Context
.getBaseElementType(VDecl
->getType()).isConstQualified()) &&
13122 !(getLangOpts().CPlusPlus
&& VDecl
->isExternC()) &&
13123 !isTemplateInstantiation(VDecl
->getTemplateSpecializationKind()))
13124 Diag(VDecl
->getLocation(), diag::warn_extern_init
);
13126 // In Microsoft C++ mode, a const variable defined in namespace scope has
13127 // external linkage by default if the variable is declared with
13128 // __declspec(dllexport).
13129 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
13130 getLangOpts().CPlusPlus
&& VDecl
->getType().isConstQualified() &&
13131 VDecl
->hasAttr
<DLLExportAttr
>() && VDecl
->getDefinition())
13132 VDecl
->setStorageClass(SC_Extern
);
13134 // C99 6.7.8p4. All file scoped initializers need to be constant.
13135 if (!getLangOpts().CPlusPlus
&& !VDecl
->isInvalidDecl())
13136 CheckForConstantInitializer(Init
, DclT
);
13139 QualType InitType
= Init
->getType();
13140 if (!InitType
.isNull() &&
13141 (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13142 InitType
.hasNonTrivialToPrimitiveCopyCUnion()))
13143 checkNonTrivialCUnionInInitializer(Init
, Init
->getExprLoc());
13145 // We will represent direct-initialization similarly to copy-initialization:
13146 // int x(1); -as-> int x = 1;
13147 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13149 // Clients that want to distinguish between the two forms, can check for
13150 // direct initializer using VarDecl::getInitStyle().
13151 // A major benefit is that clients that don't particularly care about which
13152 // exactly form was it (like the CodeGen) can handle both cases without
13153 // special case code.
13156 // The form of initialization (using parentheses or '=') is generally
13157 // insignificant, but does matter when the entity being initialized has a
13159 if (CXXDirectInit
) {
13160 assert(DirectInit
&& "Call-style initializer must be direct init.");
13161 VDecl
->setInitStyle(VarDecl::CallInit
);
13162 } else if (DirectInit
) {
13163 // This must be list-initialization. No other way is direct-initialization.
13164 VDecl
->setInitStyle(VarDecl::ListInit
);
13167 if (LangOpts
.OpenMP
&&
13168 (LangOpts
.OpenMPIsDevice
|| !LangOpts
.OMPTargetTriples
.empty()) &&
13169 VDecl
->isFileVarDecl())
13170 DeclsToCheckForDeferredDiags
.insert(VDecl
);
13171 CheckCompleteVariableDeclaration(VDecl
);
13174 /// ActOnInitializerError - Given that there was an error parsing an
13175 /// initializer for the given declaration, try to at least re-establish
13176 /// invariants such as whether a variable's type is either dependent or
13178 void Sema::ActOnInitializerError(Decl
*D
) {
13179 // Our main concern here is re-establishing invariants like "a
13180 // variable's type is either dependent or complete".
13181 if (!D
|| D
->isInvalidDecl()) return;
13183 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
13186 // Bindings are not usable if we can't make sense of the initializer.
13187 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
))
13188 for (auto *BD
: DD
->bindings())
13189 BD
->setInvalidDecl();
13191 // Auto types are meaningless if we can't make sense of the initializer.
13192 if (VD
->getType()->isUndeducedType()) {
13193 D
->setInvalidDecl();
13197 QualType Ty
= VD
->getType();
13198 if (Ty
->isDependentType()) return;
13200 // Require a complete type.
13201 if (RequireCompleteType(VD
->getLocation(),
13202 Context
.getBaseElementType(Ty
),
13203 diag::err_typecheck_decl_incomplete_type
)) {
13204 VD
->setInvalidDecl();
13208 // Require a non-abstract type.
13209 if (RequireNonAbstractType(VD
->getLocation(), Ty
,
13210 diag::err_abstract_type_in_decl
,
13211 AbstractVariableType
)) {
13212 VD
->setInvalidDecl();
13216 // Don't bother complaining about constructors or destructors,
13220 void Sema::ActOnUninitializedDecl(Decl
*RealDecl
) {
13221 // If there is no declaration, there was an error parsing it. Just ignore it.
13225 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(RealDecl
)) {
13226 QualType Type
= Var
->getType();
13228 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13229 if (isa
<DecompositionDecl
>(RealDecl
)) {
13230 Diag(Var
->getLocation(), diag::err_decomp_decl_requires_init
) << Var
;
13231 Var
->setInvalidDecl();
13235 if (Type
->isUndeducedType() &&
13236 DeduceVariableDeclarationType(Var
, false, nullptr))
13239 // C++11 [class.static.data]p3: A static data member can be declared with
13240 // the constexpr specifier; if so, its declaration shall specify
13241 // a brace-or-equal-initializer.
13242 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13243 // the definition of a variable [...] or the declaration of a static data
13245 if (Var
->isConstexpr() && !Var
->isThisDeclarationADefinition() &&
13246 !Var
->isThisDeclarationADemotedDefinition()) {
13247 if (Var
->isStaticDataMember()) {
13248 // C++1z removes the relevant rule; the in-class declaration is always
13249 // a definition there.
13250 if (!getLangOpts().CPlusPlus17
&&
13251 !Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
13252 Diag(Var
->getLocation(),
13253 diag::err_constexpr_static_mem_var_requires_init
)
13255 Var
->setInvalidDecl();
13259 Diag(Var
->getLocation(), diag::err_invalid_constexpr_var_decl
);
13260 Var
->setInvalidDecl();
13265 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13267 if (!Var
->isInvalidDecl() &&
13268 Var
->getType().getAddressSpace() == LangAS::opencl_constant
&&
13269 Var
->getStorageClass() != SC_Extern
&& !Var
->getInit()) {
13270 bool HasConstExprDefaultConstructor
= false;
13271 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13272 for (auto *Ctor
: RD
->ctors()) {
13273 if (Ctor
->isConstexpr() && Ctor
->getNumParams() == 0 &&
13274 Ctor
->getMethodQualifiers().getAddressSpace() ==
13275 LangAS::opencl_constant
) {
13276 HasConstExprDefaultConstructor
= true;
13280 if (!HasConstExprDefaultConstructor
) {
13281 Diag(Var
->getLocation(), diag::err_opencl_constant_no_init
);
13282 Var
->setInvalidDecl();
13287 if (!Var
->isInvalidDecl() && RealDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
13288 if (Var
->getStorageClass() == SC_Extern
) {
13289 Diag(Var
->getLocation(), diag::err_loader_uninitialized_extern_decl
)
13291 Var
->setInvalidDecl();
13294 if (RequireCompleteType(Var
->getLocation(), Var
->getType(),
13295 diag::err_typecheck_decl_incomplete_type
)) {
13296 Var
->setInvalidDecl();
13299 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13300 if (!RD
->hasTrivialDefaultConstructor()) {
13301 Diag(Var
->getLocation(), diag::err_loader_uninitialized_trivial_ctor
);
13302 Var
->setInvalidDecl();
13306 // The declaration is unitialized, no need for further checks.
13310 VarDecl::DefinitionKind DefKind
= Var
->isThisDeclarationADefinition();
13311 if (!Var
->isInvalidDecl() && DefKind
!= VarDecl::DeclarationOnly
&&
13312 Var
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13313 checkNonTrivialCUnion(Var
->getType(), Var
->getLocation(),
13314 NTCUC_DefaultInitializedObject
, NTCUK_Init
);
13318 case VarDecl::Definition
:
13319 if (!Var
->isStaticDataMember() || !Var
->getAnyInitializer())
13322 // We have an out-of-line definition of a static data member
13323 // that has an in-class initializer, so we type-check this like
13328 case VarDecl::DeclarationOnly
:
13329 // It's only a declaration.
13331 // Block scope. C99 6.7p7: If an identifier for an object is
13332 // declared with no linkage (C99 6.2.2p6), the type for the
13333 // object shall be complete.
13334 if (!Type
->isDependentType() && Var
->isLocalVarDecl() &&
13335 !Var
->hasLinkage() && !Var
->isInvalidDecl() &&
13336 RequireCompleteType(Var
->getLocation(), Type
,
13337 diag::err_typecheck_decl_incomplete_type
))
13338 Var
->setInvalidDecl();
13340 // Make sure that the type is not abstract.
13341 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13342 RequireNonAbstractType(Var
->getLocation(), Type
,
13343 diag::err_abstract_type_in_decl
,
13344 AbstractVariableType
))
13345 Var
->setInvalidDecl();
13346 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13347 Var
->getStorageClass() == SC_PrivateExtern
) {
13348 Diag(Var
->getLocation(), diag::warn_private_extern
);
13349 Diag(Var
->getLocation(), diag::note_private_extern
);
13352 if (Context
.getTargetInfo().allowDebugInfoForExternalRef() &&
13353 !Var
->isInvalidDecl() && !getLangOpts().CPlusPlus
)
13354 ExternalDeclarations
.push_back(Var
);
13358 case VarDecl::TentativeDefinition
:
13359 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13360 // object that has file scope without an initializer, and without a
13361 // storage-class specifier or with the storage-class specifier "static",
13362 // constitutes a tentative definition. Note: A tentative definition with
13363 // external linkage is valid (C99 6.2.2p5).
13364 if (!Var
->isInvalidDecl()) {
13365 if (const IncompleteArrayType
*ArrayT
13366 = Context
.getAsIncompleteArrayType(Type
)) {
13367 if (RequireCompleteSizedType(
13368 Var
->getLocation(), ArrayT
->getElementType(),
13369 diag::err_array_incomplete_or_sizeless_type
))
13370 Var
->setInvalidDecl();
13371 } else if (Var
->getStorageClass() == SC_Static
) {
13372 // C99 6.9.2p3: If the declaration of an identifier for an object is
13373 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13374 // declared type shall not be an incomplete type.
13375 // NOTE: code such as the following
13376 // static struct s;
13377 // struct s { int a; };
13378 // is accepted by gcc. Hence here we issue a warning instead of
13379 // an error and we do not invalidate the static declaration.
13380 // NOTE: to avoid multiple warnings, only check the first declaration.
13381 if (Var
->isFirstDecl())
13382 RequireCompleteType(Var
->getLocation(), Type
,
13383 diag::ext_typecheck_decl_incomplete_type
);
13387 // Record the tentative definition; we're done.
13388 if (!Var
->isInvalidDecl())
13389 TentativeDefinitions
.push_back(Var
);
13393 // Provide a specific diagnostic for uninitialized variable
13394 // definitions with incomplete array type.
13395 if (Type
->isIncompleteArrayType()) {
13396 if (Var
->isConstexpr())
13397 Diag(Var
->getLocation(), diag::err_constexpr_var_requires_const_init
)
13400 Diag(Var
->getLocation(),
13401 diag::err_typecheck_incomplete_array_needs_initializer
);
13402 Var
->setInvalidDecl();
13406 // Provide a specific diagnostic for uninitialized variable
13407 // definitions with reference type.
13408 if (Type
->isReferenceType()) {
13409 Diag(Var
->getLocation(), diag::err_reference_var_requires_init
)
13410 << Var
<< SourceRange(Var
->getLocation(), Var
->getLocation());
13414 // Do not attempt to type-check the default initializer for a
13415 // variable with dependent type.
13416 if (Type
->isDependentType())
13419 if (Var
->isInvalidDecl())
13422 if (!Var
->hasAttr
<AliasAttr
>()) {
13423 if (RequireCompleteType(Var
->getLocation(),
13424 Context
.getBaseElementType(Type
),
13425 diag::err_typecheck_decl_incomplete_type
)) {
13426 Var
->setInvalidDecl();
13433 // The variable can not have an abstract class type.
13434 if (RequireNonAbstractType(Var
->getLocation(), Type
,
13435 diag::err_abstract_type_in_decl
,
13436 AbstractVariableType
)) {
13437 Var
->setInvalidDecl();
13441 // Check for jumps past the implicit initializer. C++0x
13442 // clarifies that this applies to a "variable with automatic
13443 // storage duration", not a "local variable".
13444 // C++11 [stmt.dcl]p3
13445 // A program that jumps from a point where a variable with automatic
13446 // storage duration is not in scope to a point where it is in scope is
13447 // ill-formed unless the variable has scalar type, class type with a
13448 // trivial default constructor and a trivial destructor, a cv-qualified
13449 // version of one of these types, or an array of one of the preceding
13450 // types and is declared without an initializer.
13451 if (getLangOpts().CPlusPlus
&& Var
->hasLocalStorage()) {
13452 if (const RecordType
*Record
13453 = Context
.getBaseElementType(Type
)->getAs
<RecordType
>()) {
13454 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
->getDecl());
13455 // Mark the function (if we're in one) for further checking even if the
13456 // looser rules of C++11 do not require such checks, so that we can
13457 // diagnose incompatibilities with C++98.
13458 if (!CXXRecord
->isPOD())
13459 setFunctionHasBranchProtectedScope();
13462 // In OpenCL, we can't initialize objects in the __local address space,
13463 // even implicitly, so don't synthesize an implicit initializer.
13464 if (getLangOpts().OpenCL
&&
13465 Var
->getType().getAddressSpace() == LangAS::opencl_local
)
13467 // C++03 [dcl.init]p9:
13468 // If no initializer is specified for an object, and the
13469 // object is of (possibly cv-qualified) non-POD class type (or
13470 // array thereof), the object shall be default-initialized; if
13471 // the object is of const-qualified type, the underlying class
13472 // type shall have a user-declared default
13473 // constructor. Otherwise, if no initializer is specified for
13474 // a non- static object, the object and its subobjects, if
13475 // any, have an indeterminate initial value); if the object
13476 // or any of its subobjects are of const-qualified type, the
13477 // program is ill-formed.
13478 // C++0x [dcl.init]p11:
13479 // If no initializer is specified for an object, the object is
13480 // default-initialized; [...].
13481 InitializedEntity Entity
= InitializedEntity::InitializeVariable(Var
);
13482 InitializationKind Kind
13483 = InitializationKind::CreateDefault(Var
->getLocation());
13485 InitializationSequence
InitSeq(*this, Entity
, Kind
, None
);
13486 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, None
);
13489 Var
->setInit(MaybeCreateExprWithCleanups(Init
.get()));
13490 // This is important for template substitution.
13491 Var
->setInitStyle(VarDecl::CallInit
);
13492 } else if (Init
.isInvalid()) {
13493 // If default-init fails, attach a recovery-expr initializer to track
13494 // that initialization was attempted and failed.
13495 auto RecoveryExpr
=
13496 CreateRecoveryExpr(Var
->getLocation(), Var
->getLocation(), {});
13497 if (RecoveryExpr
.get())
13498 Var
->setInit(RecoveryExpr
.get());
13501 CheckCompleteVariableDeclaration(Var
);
13505 void Sema::ActOnCXXForRangeDecl(Decl
*D
) {
13506 // If there is no declaration, there was an error parsing it. Ignore it.
13510 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
13512 Diag(D
->getLocation(), diag::err_for_range_decl_must_be_var
);
13513 D
->setInvalidDecl();
13517 VD
->setCXXForRangeDecl(true);
13519 // for-range-declaration cannot be given a storage class specifier.
13521 switch (VD
->getStorageClass()) {
13530 case SC_PrivateExtern
:
13541 // for-range-declaration cannot be given a storage class specifier con't.
13542 switch (VD
->getTSCSpec()) {
13543 case TSCS_thread_local
:
13546 case TSCS___thread
:
13547 case TSCS__Thread_local
:
13548 case TSCS_unspecified
:
13553 Diag(VD
->getOuterLocStart(), diag::err_for_range_storage_class
)
13555 D
->setInvalidDecl();
13559 StmtResult
Sema::ActOnCXXForRangeIdentifier(Scope
*S
, SourceLocation IdentLoc
,
13560 IdentifierInfo
*Ident
,
13561 ParsedAttributes
&Attrs
) {
13562 // C++1y [stmt.iter]p1:
13563 // A range-based for statement of the form
13564 // for ( for-range-identifier : for-range-initializer ) statement
13565 // is equivalent to
13566 // for ( auto&& for-range-identifier : for-range-initializer ) statement
13567 DeclSpec
DS(Attrs
.getPool().getFactory());
13569 const char *PrevSpec
;
13571 DS
.SetTypeSpecType(DeclSpec::TST_auto
, IdentLoc
, PrevSpec
, DiagID
,
13572 getPrintingPolicy());
13574 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::ForInit
);
13575 D
.SetIdentifier(Ident
, IdentLoc
);
13576 D
.takeAttributes(Attrs
);
13578 D
.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc
, /*lvalue*/ false),
13580 Decl
*Var
= ActOnDeclarator(S
, D
);
13581 cast
<VarDecl
>(Var
)->setCXXForRangeDecl(true);
13582 FinalizeDeclaration(Var
);
13583 return ActOnDeclStmt(FinalizeDeclaratorGroup(S
, DS
, Var
), IdentLoc
,
13584 Attrs
.Range
.getEnd().isValid() ? Attrs
.Range
.getEnd()
13588 void Sema::CheckCompleteVariableDeclaration(VarDecl
*var
) {
13589 if (var
->isInvalidDecl()) return;
13591 MaybeAddCUDAConstantAttr(var
);
13593 if (getLangOpts().OpenCL
) {
13594 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13596 if (var
->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13598 Diag(var
->getLocation(), diag::err_opencl_invalid_block_declaration
)
13600 var
->setInvalidDecl();
13605 // In Objective-C, don't allow jumps past the implicit initialization of a
13606 // local retaining variable.
13607 if (getLangOpts().ObjC
&&
13608 var
->hasLocalStorage()) {
13609 switch (var
->getType().getObjCLifetime()) {
13610 case Qualifiers::OCL_None
:
13611 case Qualifiers::OCL_ExplicitNone
:
13612 case Qualifiers::OCL_Autoreleasing
:
13615 case Qualifiers::OCL_Weak
:
13616 case Qualifiers::OCL_Strong
:
13617 setFunctionHasBranchProtectedScope();
13622 if (var
->hasLocalStorage() &&
13623 var
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
13624 setFunctionHasBranchProtectedScope();
13626 // Warn about externally-visible variables being defined without a
13627 // prior declaration. We only want to do this for global
13628 // declarations, but we also specifically need to avoid doing it for
13629 // class members because the linkage of an anonymous class can
13630 // change if it's later given a typedef name.
13631 if (var
->isThisDeclarationADefinition() &&
13632 var
->getDeclContext()->getRedeclContext()->isFileContext() &&
13633 var
->isExternallyVisible() && var
->hasLinkage() &&
13634 !var
->isInline() && !var
->getDescribedVarTemplate() &&
13635 !isa
<VarTemplatePartialSpecializationDecl
>(var
) &&
13636 !isTemplateInstantiation(var
->getTemplateSpecializationKind()) &&
13637 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations
,
13638 var
->getLocation())) {
13639 // Find a previous declaration that's not a definition.
13640 VarDecl
*prev
= var
->getPreviousDecl();
13641 while (prev
&& prev
->isThisDeclarationADefinition())
13642 prev
= prev
->getPreviousDecl();
13645 Diag(var
->getLocation(), diag::warn_missing_variable_declarations
) << var
;
13646 Diag(var
->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage
)
13647 << /* variable */ 0;
13651 // Cache the result of checking for constant initialization.
13652 Optional
<bool> CacheHasConstInit
;
13653 const Expr
*CacheCulprit
= nullptr;
13654 auto checkConstInit
= [&]() mutable {
13655 if (!CacheHasConstInit
)
13656 CacheHasConstInit
= var
->getInit()->isConstantInitializer(
13657 Context
, var
->getType()->isReferenceType(), &CacheCulprit
);
13658 return *CacheHasConstInit
;
13661 if (var
->getTLSKind() == VarDecl::TLS_Static
) {
13662 if (var
->getType().isDestructedType()) {
13663 // GNU C++98 edits for __thread, [basic.start.term]p3:
13664 // The type of an object with thread storage duration shall not
13665 // have a non-trivial destructor.
13666 Diag(var
->getLocation(), diag::err_thread_nontrivial_dtor
);
13667 if (getLangOpts().CPlusPlus11
)
13668 Diag(var
->getLocation(), diag::note_use_thread_local
);
13669 } else if (getLangOpts().CPlusPlus
&& var
->hasInit()) {
13670 if (!checkConstInit()) {
13671 // GNU C++98 edits for __thread, [basic.start.init]p4:
13672 // An object of thread storage duration shall not require dynamic
13674 // FIXME: Need strict checking here.
13675 Diag(CacheCulprit
->getExprLoc(), diag::err_thread_dynamic_init
)
13676 << CacheCulprit
->getSourceRange();
13677 if (getLangOpts().CPlusPlus11
)
13678 Diag(var
->getLocation(), diag::note_use_thread_local
);
13684 if (!var
->getType()->isStructureType() && var
->hasInit() &&
13685 isa
<InitListExpr
>(var
->getInit())) {
13686 const auto *ILE
= cast
<InitListExpr
>(var
->getInit());
13687 unsigned NumInits
= ILE
->getNumInits();
13689 for (unsigned I
= 0; I
< NumInits
; ++I
) {
13690 const auto *Init
= ILE
->getInit(I
);
13693 const auto *SL
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
13697 unsigned NumConcat
= SL
->getNumConcatenated();
13698 // Diagnose missing comma in string array initialization.
13699 // Do not warn when all the elements in the initializer are concatenated
13700 // together. Do not warn for macros too.
13701 if (NumConcat
== 2 && !SL
->getBeginLoc().isMacroID()) {
13702 bool OnlyOneMissingComma
= true;
13703 for (unsigned J
= I
+ 1; J
< NumInits
; ++J
) {
13704 const auto *Init
= ILE
->getInit(J
);
13707 const auto *SLJ
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
13708 if (!SLJ
|| SLJ
->getNumConcatenated() > 1) {
13709 OnlyOneMissingComma
= false;
13714 if (OnlyOneMissingComma
) {
13715 SmallVector
<FixItHint
, 1> Hints
;
13716 for (unsigned i
= 0; i
< NumConcat
- 1; ++i
)
13717 Hints
.push_back(FixItHint::CreateInsertion(
13718 PP
.getLocForEndOfToken(SL
->getStrTokenLoc(i
)), ","));
13720 Diag(SL
->getStrTokenLoc(1),
13721 diag::warn_concatenated_literal_array_init
)
13723 Diag(SL
->getBeginLoc(),
13724 diag::note_concatenated_string_literal_silence
);
13726 // In any case, stop now.
13733 QualType type
= var
->getType();
13735 if (var
->hasAttr
<BlocksAttr
>())
13736 getCurFunction()->addByrefBlockVar(var
);
13738 Expr
*Init
= var
->getInit();
13739 bool GlobalStorage
= var
->hasGlobalStorage();
13740 bool IsGlobal
= GlobalStorage
&& !var
->isStaticLocal();
13741 QualType baseType
= Context
.getBaseElementType(type
);
13742 bool HasConstInit
= true;
13744 // Check whether the initializer is sufficiently constant.
13745 if (getLangOpts().CPlusPlus
&& !type
->isDependentType() && Init
&&
13746 !Init
->isValueDependent() &&
13747 (GlobalStorage
|| var
->isConstexpr() ||
13748 var
->mightBeUsableInConstantExpressions(Context
))) {
13749 // If this variable might have a constant initializer or might be usable in
13750 // constant expressions, check whether or not it actually is now. We can't
13751 // do this lazily, because the result might depend on things that change
13752 // later, such as which constexpr functions happen to be defined.
13753 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
13754 if (!getLangOpts().CPlusPlus11
) {
13755 // Prior to C++11, in contexts where a constant initializer is required,
13756 // the set of valid constant initializers is described by syntactic rules
13757 // in [expr.const]p2-6.
13758 // FIXME: Stricter checking for these rules would be useful for constinit /
13759 // -Wglobal-constructors.
13760 HasConstInit
= checkConstInit();
13762 // Compute and cache the constant value, and remember that we have a
13763 // constant initializer.
13764 if (HasConstInit
) {
13765 (void)var
->checkForConstantInitialization(Notes
);
13767 } else if (CacheCulprit
) {
13768 Notes
.emplace_back(CacheCulprit
->getExprLoc(),
13769 PDiag(diag::note_invalid_subexpr_in_const_expr
));
13770 Notes
.back().second
<< CacheCulprit
->getSourceRange();
13773 // Evaluate the initializer to see if it's a constant initializer.
13774 HasConstInit
= var
->checkForConstantInitialization(Notes
);
13777 if (HasConstInit
) {
13778 // FIXME: Consider replacing the initializer with a ConstantExpr.
13779 } else if (var
->isConstexpr()) {
13780 SourceLocation DiagLoc
= var
->getLocation();
13781 // If the note doesn't add any useful information other than a source
13782 // location, fold it into the primary diagnostic.
13783 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
13784 diag::note_invalid_subexpr_in_const_expr
) {
13785 DiagLoc
= Notes
[0].first
;
13788 Diag(DiagLoc
, diag::err_constexpr_var_requires_const_init
)
13789 << var
<< Init
->getSourceRange();
13790 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
13791 Diag(Notes
[I
].first
, Notes
[I
].second
);
13792 } else if (GlobalStorage
&& var
->hasAttr
<ConstInitAttr
>()) {
13793 auto *Attr
= var
->getAttr
<ConstInitAttr
>();
13794 Diag(var
->getLocation(), diag::err_require_constant_init_failed
)
13795 << Init
->getSourceRange();
13796 Diag(Attr
->getLocation(), diag::note_declared_required_constant_init_here
)
13797 << Attr
->getRange() << Attr
->isConstinit();
13798 for (auto &it
: Notes
)
13799 Diag(it
.first
, it
.second
);
13800 } else if (IsGlobal
&&
13801 !getDiagnostics().isIgnored(diag::warn_global_constructor
,
13802 var
->getLocation())) {
13803 // Warn about globals which don't have a constant initializer. Don't
13804 // warn about globals with a non-trivial destructor because we already
13805 // warned about them.
13806 CXXRecordDecl
*RD
= baseType
->getAsCXXRecordDecl();
13807 if (!(RD
&& !RD
->hasTrivialDestructor())) {
13808 // checkConstInit() here permits trivial default initialization even in
13809 // C++11 onwards, where such an initializer is not a constant initializer
13810 // but nonetheless doesn't require a global constructor.
13811 if (!checkConstInit())
13812 Diag(var
->getLocation(), diag::warn_global_constructor
)
13813 << Init
->getSourceRange();
13818 // Apply section attributes and pragmas to global variables.
13819 if (GlobalStorage
&& var
->isThisDeclarationADefinition() &&
13820 !inTemplateInstantiation()) {
13821 PragmaStack
<StringLiteral
*> *Stack
= nullptr;
13822 int SectionFlags
= ASTContext::PSF_Read
;
13823 if (var
->getType().isConstQualified()) {
13825 Stack
= &ConstSegStack
;
13827 Stack
= &BSSSegStack
;
13828 SectionFlags
|= ASTContext::PSF_Write
;
13830 } else if (var
->hasInit() && HasConstInit
) {
13831 Stack
= &DataSegStack
;
13832 SectionFlags
|= ASTContext::PSF_Write
;
13834 Stack
= &BSSSegStack
;
13835 SectionFlags
|= ASTContext::PSF_Write
;
13837 if (const SectionAttr
*SA
= var
->getAttr
<SectionAttr
>()) {
13838 if (SA
->getSyntax() == AttributeCommonInfo::AS_Declspec
)
13839 SectionFlags
|= ASTContext::PSF_Implicit
;
13840 UnifySection(SA
->getName(), SectionFlags
, var
);
13841 } else if (Stack
->CurrentValue
) {
13842 SectionFlags
|= ASTContext::PSF_Implicit
;
13843 auto SectionName
= Stack
->CurrentValue
->getString();
13844 var
->addAttr(SectionAttr::CreateImplicit(
13845 Context
, SectionName
, Stack
->CurrentPragmaLocation
,
13846 AttributeCommonInfo::AS_Pragma
, SectionAttr::Declspec_allocate
));
13847 if (UnifySection(SectionName
, SectionFlags
, var
))
13848 var
->dropAttr
<SectionAttr
>();
13851 // Apply the init_seg attribute if this has an initializer. If the
13852 // initializer turns out to not be dynamic, we'll end up ignoring this
13854 if (CurInitSeg
&& var
->getInit())
13855 var
->addAttr(InitSegAttr::CreateImplicit(Context
, CurInitSeg
->getString(),
13857 AttributeCommonInfo::AS_Pragma
));
13860 // All the following checks are C++ only.
13861 if (!getLangOpts().CPlusPlus
) {
13862 // If this variable must be emitted, add it as an initializer for the
13864 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
13865 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
13869 // Require the destructor.
13870 if (!type
->isDependentType())
13871 if (const RecordType
*recordType
= baseType
->getAs
<RecordType
>())
13872 FinalizeVarWithDestructor(var
, recordType
);
13874 // If this variable must be emitted, add it as an initializer for the current
13876 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
13877 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
13879 // Build the bindings if this is a structured binding declaration.
13880 if (auto *DD
= dyn_cast
<DecompositionDecl
>(var
))
13881 CheckCompleteDecompositionDeclaration(DD
);
13884 /// Check if VD needs to be dllexport/dllimport due to being in a
13885 /// dllexport/import function.
13886 void Sema::CheckStaticLocalForDllExport(VarDecl
*VD
) {
13887 assert(VD
->isStaticLocal());
13889 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
13891 // Find outermost function when VD is in lambda function.
13892 while (FD
&& !getDLLAttr(FD
) &&
13893 !FD
->hasAttr
<DLLExportStaticLocalAttr
>() &&
13894 !FD
->hasAttr
<DLLImportStaticLocalAttr
>()) {
13895 FD
= dyn_cast_or_null
<FunctionDecl
>(FD
->getParentFunctionOrMethod());
13901 // Static locals inherit dll attributes from their function.
13902 if (Attr
*A
= getDLLAttr(FD
)) {
13903 auto *NewAttr
= cast
<InheritableAttr
>(A
->clone(getASTContext()));
13904 NewAttr
->setInherited(true);
13905 VD
->addAttr(NewAttr
);
13906 } else if (Attr
*A
= FD
->getAttr
<DLLExportStaticLocalAttr
>()) {
13907 auto *NewAttr
= DLLExportAttr::CreateImplicit(getASTContext(), *A
);
13908 NewAttr
->setInherited(true);
13909 VD
->addAttr(NewAttr
);
13911 // Export this function to enforce exporting this static variable even
13912 // if it is not used in this compilation unit.
13913 if (!FD
->hasAttr
<DLLExportAttr
>())
13914 FD
->addAttr(NewAttr
);
13916 } else if (Attr
*A
= FD
->getAttr
<DLLImportStaticLocalAttr
>()) {
13917 auto *NewAttr
= DLLImportAttr::CreateImplicit(getASTContext(), *A
);
13918 NewAttr
->setInherited(true);
13919 VD
->addAttr(NewAttr
);
13923 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13924 /// any semantic actions necessary after any initializer has been attached.
13925 void Sema::FinalizeDeclaration(Decl
*ThisDecl
) {
13926 // Note that we are no longer parsing the initializer for this declaration.
13927 ParsingInitForAutoVars
.erase(ThisDecl
);
13929 VarDecl
*VD
= dyn_cast_or_null
<VarDecl
>(ThisDecl
);
13933 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13934 if (VD
->hasGlobalStorage() && VD
->isThisDeclarationADefinition() &&
13935 !inTemplateInstantiation() && !VD
->hasAttr
<SectionAttr
>()) {
13936 if (PragmaClangBSSSection
.Valid
)
13937 VD
->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13938 Context
, PragmaClangBSSSection
.SectionName
,
13939 PragmaClangBSSSection
.PragmaLocation
,
13940 AttributeCommonInfo::AS_Pragma
));
13941 if (PragmaClangDataSection
.Valid
)
13942 VD
->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13943 Context
, PragmaClangDataSection
.SectionName
,
13944 PragmaClangDataSection
.PragmaLocation
,
13945 AttributeCommonInfo::AS_Pragma
));
13946 if (PragmaClangRodataSection
.Valid
)
13947 VD
->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13948 Context
, PragmaClangRodataSection
.SectionName
,
13949 PragmaClangRodataSection
.PragmaLocation
,
13950 AttributeCommonInfo::AS_Pragma
));
13951 if (PragmaClangRelroSection
.Valid
)
13952 VD
->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13953 Context
, PragmaClangRelroSection
.SectionName
,
13954 PragmaClangRelroSection
.PragmaLocation
,
13955 AttributeCommonInfo::AS_Pragma
));
13958 if (auto *DD
= dyn_cast
<DecompositionDecl
>(ThisDecl
)) {
13959 for (auto *BD
: DD
->bindings()) {
13960 FinalizeDeclaration(BD
);
13964 checkAttributesAfterMerging(*this, *VD
);
13966 // Perform TLS alignment check here after attributes attached to the variable
13967 // which may affect the alignment have been processed. Only perform the check
13968 // if the target has a maximum TLS alignment (zero means no constraints).
13969 if (unsigned MaxAlign
= Context
.getTargetInfo().getMaxTLSAlign()) {
13970 // Protect the check so that it's not performed on dependent types and
13971 // dependent alignments (we can't determine the alignment in that case).
13972 if (VD
->getTLSKind() && !VD
->hasDependentAlignment()) {
13973 CharUnits MaxAlignChars
= Context
.toCharUnitsFromBits(MaxAlign
);
13974 if (Context
.getDeclAlign(VD
) > MaxAlignChars
) {
13975 Diag(VD
->getLocation(), diag::err_tls_var_aligned_over_maximum
)
13976 << (unsigned)Context
.getDeclAlign(VD
).getQuantity() << VD
13977 << (unsigned)MaxAlignChars
.getQuantity();
13982 if (VD
->isStaticLocal())
13983 CheckStaticLocalForDllExport(VD
);
13985 // Perform check for initializers of device-side global variables.
13986 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13987 // 7.5). We must also apply the same checks to all __shared__
13988 // variables whether they are local or not. CUDA also allows
13989 // constant initializers for __constant__ and __device__ variables.
13990 if (getLangOpts().CUDA
)
13991 checkAllowedCUDAInitializer(VD
);
13993 // Grab the dllimport or dllexport attribute off of the VarDecl.
13994 const InheritableAttr
*DLLAttr
= getDLLAttr(VD
);
13996 // Imported static data members cannot be defined out-of-line.
13997 if (const auto *IA
= dyn_cast_or_null
<DLLImportAttr
>(DLLAttr
)) {
13998 if (VD
->isStaticDataMember() && VD
->isOutOfLine() &&
13999 VD
->isThisDeclarationADefinition()) {
14000 // We allow definitions of dllimport class template static data members
14002 CXXRecordDecl
*Context
=
14003 cast
<CXXRecordDecl
>(VD
->getFirstDecl()->getDeclContext());
14004 bool IsClassTemplateMember
=
14005 isa
<ClassTemplatePartialSpecializationDecl
>(Context
) ||
14006 Context
->getDescribedClassTemplate();
14008 Diag(VD
->getLocation(),
14009 IsClassTemplateMember
14010 ? diag::warn_attribute_dllimport_static_field_definition
14011 : diag::err_attribute_dllimport_static_field_definition
);
14012 Diag(IA
->getLocation(), diag::note_attribute
);
14013 if (!IsClassTemplateMember
)
14014 VD
->setInvalidDecl();
14018 // dllimport/dllexport variables cannot be thread local, their TLS index
14019 // isn't exported with the variable.
14020 if (DLLAttr
&& VD
->getTLSKind()) {
14021 auto *F
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
14022 if (F
&& getDLLAttr(F
)) {
14023 assert(VD
->isStaticLocal());
14024 // But if this is a static local in a dlimport/dllexport function, the
14025 // function will never be inlined, which means the var would never be
14026 // imported, so having it marked import/export is safe.
14028 Diag(VD
->getLocation(), diag::err_attribute_dll_thread_local
) << VD
14030 VD
->setInvalidDecl();
14034 if (UsedAttr
*Attr
= VD
->getAttr
<UsedAttr
>()) {
14035 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14036 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14038 VD
->dropAttr
<UsedAttr
>();
14041 if (RetainAttr
*Attr
= VD
->getAttr
<RetainAttr
>()) {
14042 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14043 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14045 VD
->dropAttr
<RetainAttr
>();
14049 const DeclContext
*DC
= VD
->getDeclContext();
14050 // If there's a #pragma GCC visibility in scope, and this isn't a class
14051 // member, set the visibility of this variable.
14052 if (DC
->getRedeclContext()->isFileContext() && VD
->isExternallyVisible())
14053 AddPushedVisibilityAttribute(VD
);
14055 // FIXME: Warn on unused var template partial specializations.
14056 if (VD
->isFileVarDecl() && !isa
<VarTemplatePartialSpecializationDecl
>(VD
))
14057 MarkUnusedFileScopedDecl(VD
);
14059 // Now we have parsed the initializer and can update the table of magic
14061 if (!VD
->hasAttr
<TypeTagForDatatypeAttr
>() ||
14062 !VD
->getType()->isIntegralOrEnumerationType())
14065 for (const auto *I
: ThisDecl
->specific_attrs
<TypeTagForDatatypeAttr
>()) {
14066 const Expr
*MagicValueExpr
= VD
->getInit();
14067 if (!MagicValueExpr
) {
14070 Optional
<llvm::APSInt
> MagicValueInt
;
14071 if (!(MagicValueInt
= MagicValueExpr
->getIntegerConstantExpr(Context
))) {
14072 Diag(I
->getRange().getBegin(),
14073 diag::err_type_tag_for_datatype_not_ice
)
14074 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14077 if (MagicValueInt
->getActiveBits() > 64) {
14078 Diag(I
->getRange().getBegin(),
14079 diag::err_type_tag_for_datatype_too_large
)
14080 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14083 uint64_t MagicValue
= MagicValueInt
->getZExtValue();
14084 RegisterTypeTagForDatatype(I
->getArgumentKind(),
14086 I
->getMatchingCType(),
14087 I
->getLayoutCompatible(),
14088 I
->getMustBeNull());
14092 static bool hasDeducedAuto(DeclaratorDecl
*DD
) {
14093 auto *VD
= dyn_cast
<VarDecl
>(DD
);
14094 return VD
&& !VD
->getType()->hasAutoForTrailingReturnType();
14097 Sema::DeclGroupPtrTy
Sema::FinalizeDeclaratorGroup(Scope
*S
, const DeclSpec
&DS
,
14098 ArrayRef
<Decl
*> Group
) {
14099 SmallVector
<Decl
*, 8> Decls
;
14101 if (DS
.isTypeSpecOwned())
14102 Decls
.push_back(DS
.getRepAsDecl());
14104 DeclaratorDecl
*FirstDeclaratorInGroup
= nullptr;
14105 DecompositionDecl
*FirstDecompDeclaratorInGroup
= nullptr;
14106 bool DiagnosedMultipleDecomps
= false;
14107 DeclaratorDecl
*FirstNonDeducedAutoInGroup
= nullptr;
14108 bool DiagnosedNonDeducedAuto
= false;
14110 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14111 if (Decl
*D
= Group
[i
]) {
14112 // For declarators, there are some additional syntactic-ish checks we need
14114 if (auto *DD
= dyn_cast
<DeclaratorDecl
>(D
)) {
14115 if (!FirstDeclaratorInGroup
)
14116 FirstDeclaratorInGroup
= DD
;
14117 if (!FirstDecompDeclaratorInGroup
)
14118 FirstDecompDeclaratorInGroup
= dyn_cast
<DecompositionDecl
>(D
);
14119 if (!FirstNonDeducedAutoInGroup
&& DS
.hasAutoTypeSpec() &&
14120 !hasDeducedAuto(DD
))
14121 FirstNonDeducedAutoInGroup
= DD
;
14123 if (FirstDeclaratorInGroup
!= DD
) {
14124 // A decomposition declaration cannot be combined with any other
14125 // declaration in the same group.
14126 if (FirstDecompDeclaratorInGroup
&& !DiagnosedMultipleDecomps
) {
14127 Diag(FirstDecompDeclaratorInGroup
->getLocation(),
14128 diag::err_decomp_decl_not_alone
)
14129 << FirstDeclaratorInGroup
->getSourceRange()
14130 << DD
->getSourceRange();
14131 DiagnosedMultipleDecomps
= true;
14134 // A declarator that uses 'auto' in any way other than to declare a
14135 // variable with a deduced type cannot be combined with any other
14136 // declarator in the same group.
14137 if (FirstNonDeducedAutoInGroup
&& !DiagnosedNonDeducedAuto
) {
14138 Diag(FirstNonDeducedAutoInGroup
->getLocation(),
14139 diag::err_auto_non_deduced_not_alone
)
14140 << FirstNonDeducedAutoInGroup
->getType()
14141 ->hasAutoForTrailingReturnType()
14142 << FirstDeclaratorInGroup
->getSourceRange()
14143 << DD
->getSourceRange();
14144 DiagnosedNonDeducedAuto
= true;
14149 Decls
.push_back(D
);
14153 if (DeclSpec::isDeclRep(DS
.getTypeSpecType())) {
14154 if (TagDecl
*Tag
= dyn_cast_or_null
<TagDecl
>(DS
.getRepAsDecl())) {
14155 handleTagNumbering(Tag
, S
);
14156 if (FirstDeclaratorInGroup
&& !Tag
->hasNameForLinkage() &&
14157 getLangOpts().CPlusPlus
)
14158 Context
.addDeclaratorForUnnamedTagDecl(Tag
, FirstDeclaratorInGroup
);
14162 return BuildDeclaratorGroup(Decls
);
14165 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14166 /// group, performing any necessary semantic checking.
14167 Sema::DeclGroupPtrTy
14168 Sema::BuildDeclaratorGroup(MutableArrayRef
<Decl
*> Group
) {
14169 // C++14 [dcl.spec.auto]p7: (DR1347)
14170 // If the type that replaces the placeholder type is not the same in each
14171 // deduction, the program is ill-formed.
14172 if (Group
.size() > 1) {
14174 VarDecl
*DeducedDecl
= nullptr;
14175 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14176 VarDecl
*D
= dyn_cast
<VarDecl
>(Group
[i
]);
14177 if (!D
|| D
->isInvalidDecl())
14179 DeducedType
*DT
= D
->getType()->getContainedDeducedType();
14180 if (!DT
|| DT
->getDeducedType().isNull())
14182 if (Deduced
.isNull()) {
14183 Deduced
= DT
->getDeducedType();
14185 } else if (!Context
.hasSameType(DT
->getDeducedType(), Deduced
)) {
14186 auto *AT
= dyn_cast
<AutoType
>(DT
);
14187 auto Dia
= Diag(D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14188 diag::err_auto_different_deductions
)
14189 << (AT
? (unsigned)AT
->getKeyword() : 3) << Deduced
14190 << DeducedDecl
->getDeclName() << DT
->getDeducedType()
14191 << D
->getDeclName();
14192 if (DeducedDecl
->hasInit())
14193 Dia
<< DeducedDecl
->getInit()->getSourceRange();
14195 Dia
<< D
->getInit()->getSourceRange();
14196 D
->setInvalidDecl();
14202 ActOnDocumentableDecls(Group
);
14204 return DeclGroupPtrTy::make(
14205 DeclGroupRef::Create(Context
, Group
.data(), Group
.size()));
14208 void Sema::ActOnDocumentableDecl(Decl
*D
) {
14209 ActOnDocumentableDecls(D
);
14212 void Sema::ActOnDocumentableDecls(ArrayRef
<Decl
*> Group
) {
14213 // Don't parse the comment if Doxygen diagnostics are ignored.
14214 if (Group
.empty() || !Group
[0])
14217 if (Diags
.isIgnored(diag::warn_doc_param_not_found
,
14218 Group
[0]->getLocation()) &&
14219 Diags
.isIgnored(diag::warn_unknown_comment_command_name
,
14220 Group
[0]->getLocation()))
14223 if (Group
.size() >= 2) {
14224 // This is a decl group. Normally it will contain only declarations
14225 // produced from declarator list. But in case we have any definitions or
14226 // additional declaration references:
14227 // 'typedef struct S {} S;'
14228 // 'typedef struct S *S;'
14230 // FinalizeDeclaratorGroup adds these as separate declarations.
14231 Decl
*MaybeTagDecl
= Group
[0];
14232 if (MaybeTagDecl
&& isa
<TagDecl
>(MaybeTagDecl
)) {
14233 Group
= Group
.slice(1);
14237 // FIMXE: We assume every Decl in the group is in the same file.
14238 // This is false when preprocessor constructs the group from decls in
14239 // different files (e. g. macros or #include).
14240 Context
.attachCommentsToJustParsedDecls(Group
, &getPreprocessor());
14243 /// Common checks for a parameter-declaration that should apply to both function
14244 /// parameters and non-type template parameters.
14245 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope
*S
, Declarator
&D
) {
14246 // Check that there are no default arguments inside the type of this
14248 if (getLangOpts().CPlusPlus
)
14249 CheckExtraCXXDefaultArguments(D
);
14251 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14252 if (D
.getCXXScopeSpec().isSet()) {
14253 Diag(D
.getIdentifierLoc(), diag::err_qualified_param_declarator
)
14254 << D
.getCXXScopeSpec().getRange();
14257 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14258 // simple identifier except [...irrelevant cases...].
14259 switch (D
.getName().getKind()) {
14260 case UnqualifiedIdKind::IK_Identifier
:
14263 case UnqualifiedIdKind::IK_OperatorFunctionId
:
14264 case UnqualifiedIdKind::IK_ConversionFunctionId
:
14265 case UnqualifiedIdKind::IK_LiteralOperatorId
:
14266 case UnqualifiedIdKind::IK_ConstructorName
:
14267 case UnqualifiedIdKind::IK_DestructorName
:
14268 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
14269 case UnqualifiedIdKind::IK_DeductionGuideName
:
14270 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name
)
14271 << GetNameForDeclarator(D
).getName();
14274 case UnqualifiedIdKind::IK_TemplateId
:
14275 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
14276 // GetNameForDeclarator would not produce a useful name in this case.
14277 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name_template_id
);
14282 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14283 /// to introduce parameters into function prototype scope.
14284 Decl
*Sema::ActOnParamDeclarator(Scope
*S
, Declarator
&D
) {
14285 const DeclSpec
&DS
= D
.getDeclSpec();
14287 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14289 // C++03 [dcl.stc]p2 also permits 'auto'.
14290 StorageClass SC
= SC_None
;
14291 if (DS
.getStorageClassSpec() == DeclSpec::SCS_register
) {
14293 // In C++11, the 'register' storage class specifier is deprecated.
14294 // In C++17, it is not allowed, but we tolerate it as an extension.
14295 if (getLangOpts().CPlusPlus11
) {
14296 Diag(DS
.getStorageClassSpecLoc(),
14297 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
14298 : diag::warn_deprecated_register
)
14299 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
14301 } else if (getLangOpts().CPlusPlus
&&
14302 DS
.getStorageClassSpec() == DeclSpec::SCS_auto
) {
14304 } else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
) {
14305 Diag(DS
.getStorageClassSpecLoc(),
14306 diag::err_invalid_storage_class_in_func_decl
);
14307 D
.getMutableDeclSpec().ClearStorageClassSpecs();
14310 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
14311 Diag(DS
.getThreadStorageClassSpecLoc(), diag::err_invalid_thread
)
14312 << DeclSpec::getSpecifierName(TSCS
);
14313 if (DS
.isInlineSpecified())
14314 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
14315 << getLangOpts().CPlusPlus17
;
14316 if (DS
.hasConstexprSpecifier())
14317 Diag(DS
.getConstexprSpecLoc(), diag::err_invalid_constexpr
)
14318 << 0 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
14320 DiagnoseFunctionSpecifiers(DS
);
14322 CheckFunctionOrTemplateParamDeclarator(S
, D
);
14324 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
14325 QualType parmDeclType
= TInfo
->getType();
14327 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14328 IdentifierInfo
*II
= D
.getIdentifier();
14330 LookupResult
R(*this, II
, D
.getIdentifierLoc(), LookupOrdinaryName
,
14331 ForVisibleRedeclaration
);
14333 if (R
.isSingleResult()) {
14334 NamedDecl
*PrevDecl
= R
.getFoundDecl();
14335 if (PrevDecl
->isTemplateParameter()) {
14336 // Maybe we will complain about the shadowed template parameter.
14337 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
14338 // Just pretend that we didn't see the previous declaration.
14339 PrevDecl
= nullptr;
14340 } else if (S
->isDeclScope(PrevDecl
)) {
14341 Diag(D
.getIdentifierLoc(), diag::err_param_redefinition
) << II
;
14342 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
14344 // Recover by removing the name
14346 D
.SetIdentifier(nullptr, D
.getIdentifierLoc());
14347 D
.setInvalidType(true);
14352 // Temporarily put parameter variables in the translation unit, not
14353 // the enclosing context. This prevents them from accidentally
14354 // looking like class members in C++.
14356 CheckParameter(Context
.getTranslationUnitDecl(), D
.getBeginLoc(),
14357 D
.getIdentifierLoc(), II
, parmDeclType
, TInfo
, SC
);
14359 if (D
.isInvalidType())
14360 New
->setInvalidDecl();
14362 assert(S
->isFunctionPrototypeScope());
14363 assert(S
->getFunctionPrototypeDepth() >= 1);
14364 New
->setScopeInfo(S
->getFunctionPrototypeDepth() - 1,
14365 S
->getNextFunctionPrototypeIndex());
14367 // Add the parameter declaration into this scope.
14370 IdResolver
.AddDecl(New
);
14372 ProcessDeclAttributes(S
, New
, D
);
14374 if (D
.getDeclSpec().isModulePrivateSpecified())
14375 Diag(New
->getLocation(), diag::err_module_private_local
)
14376 << 1 << New
<< SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
14377 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
14379 if (New
->hasAttr
<BlocksAttr
>()) {
14380 Diag(New
->getLocation(), diag::err_block_on_nonlocal
);
14383 if (getLangOpts().OpenCL
)
14384 deduceOpenCLAddressSpace(New
);
14389 /// Synthesizes a variable for a parameter arising from a
14391 ParmVarDecl
*Sema::BuildParmVarDeclForTypedef(DeclContext
*DC
,
14392 SourceLocation Loc
,
14394 /* FIXME: setting StartLoc == Loc.
14395 Would it be worth to modify callers so as to provide proper source
14396 location for the unnamed parameters, embedding the parameter's type? */
14397 ParmVarDecl
*Param
= ParmVarDecl::Create(Context
, DC
, Loc
, Loc
, nullptr,
14398 T
, Context
.getTrivialTypeSourceInfo(T
, Loc
),
14400 Param
->setImplicit();
14404 void Sema::DiagnoseUnusedParameters(ArrayRef
<ParmVarDecl
*> Parameters
) {
14405 // Don't diagnose unused-parameter errors in template instantiations; we
14406 // will already have done so in the template itself.
14407 if (inTemplateInstantiation())
14410 for (const ParmVarDecl
*Parameter
: Parameters
) {
14411 if (!Parameter
->isReferenced() && Parameter
->getDeclName() &&
14412 !Parameter
->hasAttr
<UnusedAttr
>()) {
14413 Diag(Parameter
->getLocation(), diag::warn_unused_parameter
)
14414 << Parameter
->getDeclName();
14419 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14420 ArrayRef
<ParmVarDecl
*> Parameters
, QualType ReturnTy
, NamedDecl
*D
) {
14421 if (LangOpts
.NumLargeByValueCopy
== 0) // No check.
14424 // Warn if the return value is pass-by-value and larger than the specified
14426 if (!ReturnTy
->isDependentType() && ReturnTy
.isPODType(Context
)) {
14427 unsigned Size
= Context
.getTypeSizeInChars(ReturnTy
).getQuantity();
14428 if (Size
> LangOpts
.NumLargeByValueCopy
)
14429 Diag(D
->getLocation(), diag::warn_return_value_size
) << D
<< Size
;
14432 // Warn if any parameter is pass-by-value and larger than the specified
14434 for (const ParmVarDecl
*Parameter
: Parameters
) {
14435 QualType T
= Parameter
->getType();
14436 if (T
->isDependentType() || !T
.isPODType(Context
))
14438 unsigned Size
= Context
.getTypeSizeInChars(T
).getQuantity();
14439 if (Size
> LangOpts
.NumLargeByValueCopy
)
14440 Diag(Parameter
->getLocation(), diag::warn_parameter_size
)
14441 << Parameter
<< Size
;
14445 ParmVarDecl
*Sema::CheckParameter(DeclContext
*DC
, SourceLocation StartLoc
,
14446 SourceLocation NameLoc
, IdentifierInfo
*Name
,
14447 QualType T
, TypeSourceInfo
*TSInfo
,
14449 // In ARC, infer a lifetime qualifier for appropriate parameter types.
14450 if (getLangOpts().ObjCAutoRefCount
&&
14451 T
.getObjCLifetime() == Qualifiers::OCL_None
&&
14452 T
->isObjCLifetimeType()) {
14454 Qualifiers::ObjCLifetime lifetime
;
14456 // Special cases for arrays:
14457 // - if it's const, use __unsafe_unretained
14458 // - otherwise, it's an error
14459 if (T
->isArrayType()) {
14460 if (!T
.isConstQualified()) {
14461 if (DelayedDiagnostics
.shouldDelayDiagnostics())
14462 DelayedDiagnostics
.add(
14463 sema::DelayedDiagnostic::makeForbiddenType(
14464 NameLoc
, diag::err_arc_array_param_no_ownership
, T
, false));
14466 Diag(NameLoc
, diag::err_arc_array_param_no_ownership
)
14467 << TSInfo
->getTypeLoc().getSourceRange();
14469 lifetime
= Qualifiers::OCL_ExplicitNone
;
14471 lifetime
= T
->getObjCARCImplicitLifetime();
14473 T
= Context
.getLifetimeQualifiedType(T
, lifetime
);
14476 ParmVarDecl
*New
= ParmVarDecl::Create(Context
, DC
, StartLoc
, NameLoc
, Name
,
14477 Context
.getAdjustedParameterType(T
),
14478 TSInfo
, SC
, nullptr);
14480 // Make a note if we created a new pack in the scope of a lambda, so that
14481 // we know that references to that pack must also be expanded within the
14483 if (New
->isParameterPack())
14484 if (auto *LSI
= getEnclosingLambda())
14485 LSI
->LocalPacks
.push_back(New
);
14487 if (New
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14488 New
->getType().hasNonTrivialToPrimitiveCopyCUnion())
14489 checkNonTrivialCUnion(New
->getType(), New
->getLocation(),
14490 NTCUC_FunctionParam
, NTCUK_Destruct
|NTCUK_Copy
);
14492 // Parameters can not be abstract class types.
14493 // For record types, this is done by the AbstractClassUsageDiagnoser once
14494 // the class has been completely parsed.
14495 if (!CurContext
->isRecord() &&
14496 RequireNonAbstractType(NameLoc
, T
, diag::err_abstract_type_in_decl
,
14497 AbstractParamType
))
14498 New
->setInvalidDecl();
14500 // Parameter declarators cannot be interface types. All ObjC objects are
14501 // passed by reference.
14502 if (T
->isObjCObjectType()) {
14503 SourceLocation TypeEndLoc
=
14504 getLocForEndOfToken(TSInfo
->getTypeLoc().getEndLoc());
14506 diag::err_object_cannot_be_passed_returned_by_value
) << 1 << T
14507 << FixItHint::CreateInsertion(TypeEndLoc
, "*");
14508 T
= Context
.getObjCObjectPointerType(T
);
14512 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14513 // duration shall not be qualified by an address-space qualifier."
14514 // Since all parameters have automatic store duration, they can not have
14515 // an address space.
14516 if (T
.getAddressSpace() != LangAS::Default
&&
14517 // OpenCL allows function arguments declared to be an array of a type
14518 // to be qualified with an address space.
14519 !(getLangOpts().OpenCL
&&
14520 (T
->isArrayType() || T
.getAddressSpace() == LangAS::opencl_private
))) {
14521 Diag(NameLoc
, diag::err_arg_with_address_space
);
14522 New
->setInvalidDecl();
14525 // PPC MMA non-pointer types are not allowed as function argument types.
14526 if (Context
.getTargetInfo().getTriple().isPPC64() &&
14527 CheckPPCMMAType(New
->getOriginalType(), New
->getLocation())) {
14528 New
->setInvalidDecl();
14534 void Sema::ActOnFinishKNRParamDeclarations(Scope
*S
, Declarator
&D
,
14535 SourceLocation LocAfterDecls
) {
14536 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
14538 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14539 // in the declaration list shall have at least one declarator, those
14540 // declarators shall only declare identifiers from the identifier list, and
14541 // every identifier in the identifier list shall be declared.
14543 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14544 // identifiers it names shall be declared in the declaration list."
14546 // This is why we only diagnose in C99 and later. Note, the other conditions
14547 // listed are checked elsewhere.
14548 if (!FTI
.hasPrototype
) {
14549 for (int i
= FTI
.NumParams
; i
!= 0; /* decrement in loop */) {
14551 if (FTI
.Params
[i
].Param
== nullptr) {
14552 if (getLangOpts().C99
) {
14553 SmallString
<256> Code
;
14554 llvm::raw_svector_ostream(Code
)
14555 << " int " << FTI
.Params
[i
].Ident
->getName() << ";\n";
14556 Diag(FTI
.Params
[i
].IdentLoc
, diag::ext_param_not_declared
)
14557 << FTI
.Params
[i
].Ident
14558 << FixItHint::CreateInsertion(LocAfterDecls
, Code
);
14561 // Implicitly declare the argument as type 'int' for lack of a better
14563 AttributeFactory attrs
;
14564 DeclSpec
DS(attrs
);
14565 const char* PrevSpec
; // unused
14566 unsigned DiagID
; // unused
14567 DS
.SetTypeSpecType(DeclSpec::TST_int
, FTI
.Params
[i
].IdentLoc
, PrevSpec
,
14568 DiagID
, Context
.getPrintingPolicy());
14569 // Use the identifier location for the type source range.
14570 DS
.SetRangeStart(FTI
.Params
[i
].IdentLoc
);
14571 DS
.SetRangeEnd(FTI
.Params
[i
].IdentLoc
);
14572 Declarator
ParamD(DS
, ParsedAttributesView::none(),
14573 DeclaratorContext::KNRTypeList
);
14574 ParamD
.SetIdentifier(FTI
.Params
[i
].Ident
, FTI
.Params
[i
].IdentLoc
);
14575 FTI
.Params
[i
].Param
= ActOnParamDeclarator(S
, ParamD
);
14582 Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Declarator
&D
,
14583 MultiTemplateParamsArg TemplateParameterLists
,
14584 SkipBodyInfo
*SkipBody
, FnBodyKind BodyKind
) {
14585 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14586 assert(D
.isFunctionDeclarator() && "Not a function declarator!");
14587 Scope
*ParentScope
= FnBodyScope
->getParent();
14589 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14590 // we define a non-templated function definition, we will create a declaration
14591 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14592 // The base function declaration will have the equivalent of an `omp declare
14593 // variant` annotation which specifies the mangled definition as a
14594 // specialization function under the OpenMP context defined as part of the
14595 // `omp begin declare variant`.
14596 SmallVector
<FunctionDecl
*, 4> Bases
;
14597 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
14598 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14599 ParentScope
, D
, TemplateParameterLists
, Bases
);
14601 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
14602 Decl
*DP
= HandleDeclarator(ParentScope
, D
, TemplateParameterLists
);
14603 Decl
*Dcl
= ActOnStartOfFunctionDef(FnBodyScope
, DP
, SkipBody
, BodyKind
);
14605 if (!Bases
.empty())
14606 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
14611 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl
*D
) {
14612 Consumer
.HandleInlineFunctionDefinition(D
);
14616 ShouldWarnAboutMissingPrototype(const FunctionDecl
*FD
,
14617 const FunctionDecl
*&PossiblePrototype
) {
14618 // Don't warn about invalid declarations.
14619 if (FD
->isInvalidDecl())
14622 // Or declarations that aren't global.
14623 if (!FD
->isGlobal())
14626 // Don't warn about C++ member functions.
14627 if (isa
<CXXMethodDecl
>(FD
))
14630 // Don't warn about 'main'.
14631 if (isa
<TranslationUnitDecl
>(FD
->getDeclContext()->getRedeclContext()))
14632 if (IdentifierInfo
*II
= FD
->getIdentifier())
14633 if (II
->isStr("main") || II
->isStr("efi_main"))
14636 // Don't warn about inline functions.
14637 if (FD
->isInlined())
14640 // Don't warn about function templates.
14641 if (FD
->getDescribedFunctionTemplate())
14644 // Don't warn about function template specializations.
14645 if (FD
->isFunctionTemplateSpecialization())
14648 // Don't warn for OpenCL kernels.
14649 if (FD
->hasAttr
<OpenCLKernelAttr
>())
14652 // Don't warn on explicitly deleted functions.
14653 if (FD
->isDeleted())
14656 // Don't warn on implicitly local functions (such as having local-typed
14658 if (!FD
->isExternallyVisible())
14661 for (const FunctionDecl
*Prev
= FD
->getPreviousDecl();
14662 Prev
; Prev
= Prev
->getPreviousDecl()) {
14663 // Ignore any declarations that occur in function or method
14664 // scope, because they aren't visible from the header.
14665 if (Prev
->getLexicalDeclContext()->isFunctionOrMethod())
14668 PossiblePrototype
= Prev
;
14669 return Prev
->getType()->isFunctionNoProtoType();
14676 Sema::CheckForFunctionRedefinition(FunctionDecl
*FD
,
14677 const FunctionDecl
*EffectiveDefinition
,
14678 SkipBodyInfo
*SkipBody
) {
14679 const FunctionDecl
*Definition
= EffectiveDefinition
;
14681 !FD
->isDefined(Definition
, /*CheckForPendingFriendDefinition*/ true))
14684 if (Definition
->getFriendObjectKind() != Decl::FOK_None
) {
14685 if (FunctionDecl
*OrigDef
= Definition
->getInstantiatedFromMemberFunction()) {
14686 if (FunctionDecl
*OrigFD
= FD
->getInstantiatedFromMemberFunction()) {
14687 // A merged copy of the same function, instantiated as a member of
14688 // the same class, is OK.
14689 if (declaresSameEntity(OrigFD
, OrigDef
) &&
14690 declaresSameEntity(cast
<Decl
>(Definition
->getLexicalDeclContext()),
14691 cast
<Decl
>(FD
->getLexicalDeclContext())))
14697 if (canRedefineFunction(Definition
, getLangOpts()))
14700 // Don't emit an error when this is redefinition of a typo-corrected
14702 if (TypoCorrectedFunctionDefinitions
.count(Definition
))
14705 // If we don't have a visible definition of the function, and it's inline or
14706 // a template, skip the new definition.
14707 if (SkipBody
&& !hasVisibleDefinition(Definition
) &&
14708 (Definition
->getFormalLinkage() == InternalLinkage
||
14709 Definition
->isInlined() ||
14710 Definition
->getDescribedFunctionTemplate() ||
14711 Definition
->getNumTemplateParameterLists())) {
14712 SkipBody
->ShouldSkip
= true;
14713 SkipBody
->Previous
= const_cast<FunctionDecl
*>(Definition
);
14714 if (auto *TD
= Definition
->getDescribedFunctionTemplate())
14715 makeMergedDefinitionVisible(TD
);
14716 makeMergedDefinitionVisible(const_cast<FunctionDecl
*>(Definition
));
14720 if (getLangOpts().GNUMode
&& Definition
->isInlineSpecified() &&
14721 Definition
->getStorageClass() == SC_Extern
)
14722 Diag(FD
->getLocation(), diag::err_redefinition_extern_inline
)
14723 << FD
<< getLangOpts().CPlusPlus
;
14725 Diag(FD
->getLocation(), diag::err_redefinition
) << FD
;
14727 Diag(Definition
->getLocation(), diag::note_previous_definition
);
14728 FD
->setInvalidDecl();
14731 static void RebuildLambdaScopeInfo(CXXMethodDecl
*CallOperator
,
14733 CXXRecordDecl
*const LambdaClass
= CallOperator
->getParent();
14735 LambdaScopeInfo
*LSI
= S
.PushLambdaScope();
14736 LSI
->CallOperator
= CallOperator
;
14737 LSI
->Lambda
= LambdaClass
;
14738 LSI
->ReturnType
= CallOperator
->getReturnType();
14739 const LambdaCaptureDefault LCD
= LambdaClass
->getLambdaCaptureDefault();
14741 if (LCD
== LCD_None
)
14742 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_None
;
14743 else if (LCD
== LCD_ByCopy
)
14744 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByval
;
14745 else if (LCD
== LCD_ByRef
)
14746 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByref
;
14747 DeclarationNameInfo DNI
= CallOperator
->getNameInfo();
14749 LSI
->IntroducerRange
= DNI
.getCXXOperatorNameRange();
14750 LSI
->Mutable
= !CallOperator
->isConst();
14752 // Add the captures to the LSI so they can be noted as already
14753 // captured within tryCaptureVar.
14754 auto I
= LambdaClass
->field_begin();
14755 for (const auto &C
: LambdaClass
->captures()) {
14756 if (C
.capturesVariable()) {
14757 ValueDecl
*VD
= C
.getCapturedVar();
14758 if (VD
->isInitCapture())
14759 S
.CurrentInstantiationScope
->InstantiatedLocal(VD
, VD
);
14760 const bool ByRef
= C
.getCaptureKind() == LCK_ByRef
;
14761 LSI
->addCapture(VD
, /*IsBlock*/false, ByRef
,
14762 /*RefersToEnclosingVariableOrCapture*/true, C
.getLocation(),
14763 /*EllipsisLoc*/C
.isPackExpansion()
14764 ? C
.getEllipsisLoc() : SourceLocation(),
14765 I
->getType(), /*Invalid*/false);
14767 } else if (C
.capturesThis()) {
14768 LSI
->addThisCapture(/*Nested*/ false, C
.getLocation(), I
->getType(),
14769 C
.getCaptureKind() == LCK_StarThis
);
14771 LSI
->addVLATypeCapture(C
.getLocation(), I
->getCapturedVLAType(),
14778 Decl
*Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Decl
*D
,
14779 SkipBodyInfo
*SkipBody
,
14780 FnBodyKind BodyKind
) {
14782 // Parsing the function declaration failed in some way. Push on a fake scope
14783 // anyway so we can try to parse the function body.
14784 PushFunctionScope();
14785 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
14789 FunctionDecl
*FD
= nullptr;
14791 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
))
14792 FD
= FunTmpl
->getTemplatedDecl();
14794 FD
= cast
<FunctionDecl
>(D
);
14796 // Do not push if it is a lambda because one is already pushed when building
14797 // the lambda in ActOnStartOfLambdaDefinition().
14798 if (!isLambdaCallOperator(FD
))
14799 // [expr.const]/p14.1
14800 // An expression or conversion is in an immediate function context if it is
14801 // potentially evaluated and either: its innermost enclosing non-block scope
14802 // is a function parameter scope of an immediate function.
14803 PushExpressionEvaluationContext(
14804 FD
->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
14805 : ExprEvalContexts
.back().Context
);
14807 // Check for defining attributes before the check for redefinition.
14808 if (const auto *Attr
= FD
->getAttr
<AliasAttr
>()) {
14809 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 0;
14810 FD
->dropAttr
<AliasAttr
>();
14811 FD
->setInvalidDecl();
14813 if (const auto *Attr
= FD
->getAttr
<IFuncAttr
>()) {
14814 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 1;
14815 FD
->dropAttr
<IFuncAttr
>();
14816 FD
->setInvalidDecl();
14819 if (auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
14820 if (Ctor
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
14821 Ctor
->isDefaultConstructor() &&
14822 Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
14823 // If this is an MS ABI dllexport default constructor, instantiate any
14824 // default arguments.
14825 InstantiateDefaultCtorDefaultArgs(Ctor
);
14829 // See if this is a redefinition. If 'will have body' (or similar) is already
14830 // set, then these checks were already performed when it was set.
14831 if (!FD
->willHaveBody() && !FD
->isLateTemplateParsed() &&
14832 !FD
->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14833 CheckForFunctionRedefinition(FD
, nullptr, SkipBody
);
14835 // If we're skipping the body, we're done. Don't enter the scope.
14836 if (SkipBody
&& SkipBody
->ShouldSkip
)
14840 // Mark this function as "will have a body eventually". This lets users to
14841 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14843 FD
->setWillHaveBody();
14845 // If we are instantiating a generic lambda call operator, push
14846 // a LambdaScopeInfo onto the function stack. But use the information
14847 // that's already been calculated (ActOnLambdaExpr) to prime the current
14848 // LambdaScopeInfo.
14849 // When the template operator is being specialized, the LambdaScopeInfo,
14850 // has to be properly restored so that tryCaptureVariable doesn't try
14851 // and capture any new variables. In addition when calculating potential
14852 // captures during transformation of nested lambdas, it is necessary to
14853 // have the LSI properly restored.
14854 if (isGenericLambdaCallOperatorSpecialization(FD
)) {
14855 assert(inTemplateInstantiation() &&
14856 "There should be an active template instantiation on the stack "
14857 "when instantiating a generic lambda!");
14858 RebuildLambdaScopeInfo(cast
<CXXMethodDecl
>(D
), *this);
14860 // Enter a new function scope
14861 PushFunctionScope();
14864 // Builtin functions cannot be defined.
14865 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
14866 if (!Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
) &&
14867 !Context
.BuiltinInfo
.isPredefinedRuntimeFunction(BuiltinID
)) {
14868 Diag(FD
->getLocation(), diag::err_builtin_definition
) << FD
;
14869 FD
->setInvalidDecl();
14873 // The return type of a function definition must be complete (C99 6.9.1p3),
14874 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14875 QualType ResultType
= FD
->getReturnType();
14876 if (!ResultType
->isDependentType() && !ResultType
->isVoidType() &&
14877 !FD
->isInvalidDecl() && BodyKind
!= FnBodyKind::Delete
&&
14878 RequireCompleteType(FD
->getLocation(), ResultType
,
14879 diag::err_func_def_incomplete_result
))
14880 FD
->setInvalidDecl();
14883 PushDeclContext(FnBodyScope
, FD
);
14885 // Check the validity of our function parameters
14886 if (BodyKind
!= FnBodyKind::Delete
)
14887 CheckParmsForFunctionDef(FD
->parameters(),
14888 /*CheckParameterNames=*/true);
14890 // Add non-parameter declarations already in the function to the current
14893 for (Decl
*NPD
: FD
->decls()) {
14894 auto *NonParmDecl
= dyn_cast
<NamedDecl
>(NPD
);
14897 assert(!isa
<ParmVarDecl
>(NonParmDecl
) &&
14898 "parameters should not be in newly created FD yet");
14900 // If the decl has a name, make it accessible in the current scope.
14901 if (NonParmDecl
->getDeclName())
14902 PushOnScopeChains(NonParmDecl
, FnBodyScope
, /*AddToContext=*/false);
14904 // Similarly, dive into enums and fish their constants out, making them
14905 // accessible in this scope.
14906 if (auto *ED
= dyn_cast
<EnumDecl
>(NonParmDecl
)) {
14907 for (auto *EI
: ED
->enumerators())
14908 PushOnScopeChains(EI
, FnBodyScope
, /*AddToContext=*/false);
14913 // Introduce our parameters into the function scope
14914 for (auto *Param
: FD
->parameters()) {
14915 Param
->setOwningFunction(FD
);
14917 // If this has an identifier, add it to the scope stack.
14918 if (Param
->getIdentifier() && FnBodyScope
) {
14919 CheckShadow(FnBodyScope
, Param
);
14921 PushOnScopeChains(Param
, FnBodyScope
);
14925 // Ensure that the function's exception specification is instantiated.
14926 if (const FunctionProtoType
*FPT
= FD
->getType()->getAs
<FunctionProtoType
>())
14927 ResolveExceptionSpec(D
->getLocation(), FPT
);
14929 // dllimport cannot be applied to non-inline function definitions.
14930 if (FD
->hasAttr
<DLLImportAttr
>() && !FD
->isInlined() &&
14931 !FD
->isTemplateInstantiation()) {
14932 assert(!FD
->hasAttr
<DLLExportAttr
>());
14933 Diag(FD
->getLocation(), diag::err_attribute_dllimport_function_definition
);
14934 FD
->setInvalidDecl();
14937 // We want to attach documentation to original Decl (which might be
14938 // a function template).
14939 ActOnDocumentableDecl(D
);
14940 if (getCurLexicalContext()->isObjCContainer() &&
14941 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl
&&
14942 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation
)
14943 Diag(FD
->getLocation(), diag::warn_function_def_in_objc_container
);
14948 /// Given the set of return statements within a function body,
14949 /// compute the variables that are subject to the named return value
14952 /// Each of the variables that is subject to the named return value
14953 /// optimization will be marked as NRVO variables in the AST, and any
14954 /// return statement that has a marked NRVO variable as its NRVO candidate can
14955 /// use the named return value optimization.
14957 /// This function applies a very simplistic algorithm for NRVO: if every return
14958 /// statement in the scope of a variable has the same NRVO candidate, that
14959 /// candidate is an NRVO variable.
14960 void Sema::computeNRVO(Stmt
*Body
, FunctionScopeInfo
*Scope
) {
14961 ReturnStmt
**Returns
= Scope
->Returns
.data();
14963 for (unsigned I
= 0, E
= Scope
->Returns
.size(); I
!= E
; ++I
) {
14964 if (const VarDecl
*NRVOCandidate
= Returns
[I
]->getNRVOCandidate()) {
14965 if (!NRVOCandidate
->isNRVOVariable())
14966 Returns
[I
]->setNRVOCandidate(nullptr);
14971 bool Sema::canDelayFunctionBody(const Declarator
&D
) {
14972 // We can't delay parsing the body of a constexpr function template (yet).
14973 if (D
.getDeclSpec().hasConstexprSpecifier())
14976 // We can't delay parsing the body of a function template with a deduced
14977 // return type (yet).
14978 if (D
.getDeclSpec().hasAutoTypeSpec()) {
14979 // If the placeholder introduces a non-deduced trailing return type,
14980 // we can still delay parsing it.
14981 if (D
.getNumTypeObjects()) {
14982 const auto &Outer
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
14983 if (Outer
.Kind
== DeclaratorChunk::Function
&&
14984 Outer
.Fun
.hasTrailingReturnType()) {
14985 QualType Ty
= GetTypeFromParser(Outer
.Fun
.getTrailingReturnType());
14986 return Ty
.isNull() || !Ty
->isUndeducedType();
14995 bool Sema::canSkipFunctionBody(Decl
*D
) {
14996 // We cannot skip the body of a function (or function template) which is
14997 // constexpr, since we may need to evaluate its body in order to parse the
14998 // rest of the file.
14999 // We cannot skip the body of a function with an undeduced return type,
15000 // because any callers of that function need to know the type.
15001 if (const FunctionDecl
*FD
= D
->getAsFunction()) {
15002 if (FD
->isConstexpr())
15004 // We can't simply call Type::isUndeducedType here, because inside template
15005 // auto can be deduced to a dependent type, which is not considered
15007 if (FD
->getReturnType()->getContainedDeducedType())
15010 return Consumer
.shouldSkipFunctionBody(D
);
15013 Decl
*Sema::ActOnSkippedFunctionBody(Decl
*Decl
) {
15016 if (FunctionDecl
*FD
= Decl
->getAsFunction())
15017 FD
->setHasSkippedBody();
15018 else if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(Decl
))
15019 MD
->setHasSkippedBody();
15023 Decl
*Sema::ActOnFinishFunctionBody(Decl
*D
, Stmt
*BodyArg
) {
15024 return ActOnFinishFunctionBody(D
, BodyArg
, false);
15027 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15029 class ExitFunctionBodyRAII
{
15031 ExitFunctionBodyRAII(Sema
&S
, bool IsLambda
) : S(S
), IsLambda(IsLambda
) {}
15032 ~ExitFunctionBodyRAII() {
15034 S
.PopExpressionEvaluationContext();
15039 bool IsLambda
= false;
15042 static void diagnoseImplicitlyRetainedSelf(Sema
&S
) {
15043 llvm::DenseMap
<const BlockDecl
*, bool> EscapeInfo
;
15045 auto IsOrNestedInEscapingBlock
= [&](const BlockDecl
*BD
) {
15046 if (EscapeInfo
.count(BD
))
15047 return EscapeInfo
[BD
];
15050 const BlockDecl
*CurBD
= BD
;
15053 R
= !CurBD
->doesNotEscape();
15056 CurBD
= CurBD
->getParent()->getInnermostBlockDecl();
15059 return EscapeInfo
[BD
] = R
;
15062 // If the location where 'self' is implicitly retained is inside a escaping
15063 // block, emit a diagnostic.
15064 for (const std::pair
<SourceLocation
, const BlockDecl
*> &P
:
15065 S
.ImplicitlyRetainedSelfLocs
)
15066 if (IsOrNestedInEscapingBlock(P
.second
))
15067 S
.Diag(P
.first
, diag::warn_implicitly_retains_self
)
15068 << FixItHint::CreateInsertion(P
.first
, "self->");
15071 Decl
*Sema::ActOnFinishFunctionBody(Decl
*dcl
, Stmt
*Body
,
15072 bool IsInstantiation
) {
15073 FunctionScopeInfo
*FSI
= getCurFunction();
15074 FunctionDecl
*FD
= dcl
? dcl
->getAsFunction() : nullptr;
15076 if (FSI
->UsesFPIntrin
&& FD
&& !FD
->hasAttr
<StrictFPAttr
>())
15077 FD
->addAttr(StrictFPAttr::CreateImplicit(Context
));
15079 sema::AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
15080 sema::AnalysisBasedWarnings::Policy
*ActivePolicy
= nullptr;
15082 if (getLangOpts().Coroutines
&& FSI
->isCoroutine())
15083 CheckCompletedCoroutineBody(FD
, Body
);
15086 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15087 // one is already popped when finishing the lambda in BuildLambdaExpr().
15088 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15089 ExitFunctionBodyRAII
ExitRAII(*this, isLambdaCallOperator(FD
));
15093 FD
->setWillHaveBody(false);
15095 if (getLangOpts().CPlusPlus14
) {
15096 if (!FD
->isInvalidDecl() && Body
&& !FD
->isDependentContext() &&
15097 FD
->getReturnType()->isUndeducedType()) {
15098 // For a function with a deduced result type to return void,
15099 // the result type as written must be 'auto' or 'decltype(auto)',
15100 // possibly cv-qualified or constrained, but not ref-qualified.
15101 if (!FD
->getReturnType()->getAs
<AutoType
>()) {
15102 Diag(dcl
->getLocation(), diag::err_auto_fn_no_return_but_not_auto
)
15103 << FD
->getReturnType();
15104 FD
->setInvalidDecl();
15106 // Falling off the end of the function is the same as 'return;'.
15107 Expr
*Dummy
= nullptr;
15108 if (DeduceFunctionTypeFromReturnExpr(
15109 FD
, dcl
->getLocation(), Dummy
,
15110 FD
->getReturnType()->getAs
<AutoType
>()))
15111 FD
->setInvalidDecl();
15114 } else if (getLangOpts().CPlusPlus11
&& isLambdaCallOperator(FD
)) {
15115 // In C++11, we don't use 'auto' deduction rules for lambda call
15116 // operators because we don't support return type deduction.
15117 auto *LSI
= getCurLambda();
15118 if (LSI
->HasImplicitReturnType
) {
15119 deduceClosureReturnType(*LSI
);
15121 // C++11 [expr.prim.lambda]p4:
15122 // [...] if there are no return statements in the compound-statement
15123 // [the deduced type is] the type void
15125 LSI
->ReturnType
.isNull() ? Context
.VoidTy
: LSI
->ReturnType
;
15127 // Update the return type to the deduced type.
15128 const auto *Proto
= FD
->getType()->castAs
<FunctionProtoType
>();
15129 FD
->setType(Context
.getFunctionType(RetType
, Proto
->getParamTypes(),
15130 Proto
->getExtProtoInfo()));
15134 // If the function implicitly returns zero (like 'main') or is naked,
15135 // don't complain about missing return statements.
15136 if (FD
->hasImplicitReturnZero() || FD
->hasAttr
<NakedAttr
>())
15137 WP
.disableCheckFallThrough();
15139 // MSVC permits the use of pure specifier (=0) on function definition,
15140 // defined at class scope, warn about this non-standard construct.
15141 if (getLangOpts().MicrosoftExt
&& FD
->isPure() && !FD
->isOutOfLine())
15142 Diag(FD
->getLocation(), diag::ext_pure_function_definition
);
15144 if (!FD
->isInvalidDecl()) {
15145 // Don't diagnose unused parameters of defaulted, deleted or naked
15147 if (!FD
->isDeleted() && !FD
->isDefaulted() && !FD
->hasSkippedBody() &&
15148 !FD
->hasAttr
<NakedAttr
>())
15149 DiagnoseUnusedParameters(FD
->parameters());
15150 DiagnoseSizeOfParametersAndReturnValue(FD
->parameters(),
15151 FD
->getReturnType(), FD
);
15153 // If this is a structor, we need a vtable.
15154 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(FD
))
15155 MarkVTableUsed(FD
->getLocation(), Constructor
->getParent());
15156 else if (CXXDestructorDecl
*Destructor
=
15157 dyn_cast
<CXXDestructorDecl
>(FD
))
15158 MarkVTableUsed(FD
->getLocation(), Destructor
->getParent());
15160 // Try to apply the named return value optimization. We have to check
15161 // if we can do this here because lambdas keep return statements around
15162 // to deduce an implicit return type.
15163 if (FD
->getReturnType()->isRecordType() &&
15164 (!getLangOpts().CPlusPlus
|| !FD
->isDependentContext()))
15165 computeNRVO(Body
, FSI
);
15168 // GNU warning -Wmissing-prototypes:
15169 // Warn if a global function is defined without a previous
15170 // prototype declaration. This warning is issued even if the
15171 // definition itself provides a prototype. The aim is to detect
15172 // global functions that fail to be declared in header files.
15173 const FunctionDecl
*PossiblePrototype
= nullptr;
15174 if (ShouldWarnAboutMissingPrototype(FD
, PossiblePrototype
)) {
15175 Diag(FD
->getLocation(), diag::warn_missing_prototype
) << FD
;
15177 if (PossiblePrototype
) {
15178 // We found a declaration that is not a prototype,
15179 // but that could be a zero-parameter prototype
15180 if (TypeSourceInfo
*TI
= PossiblePrototype
->getTypeSourceInfo()) {
15181 TypeLoc TL
= TI
->getTypeLoc();
15182 if (FunctionNoProtoTypeLoc FTL
= TL
.getAs
<FunctionNoProtoTypeLoc
>())
15183 Diag(PossiblePrototype
->getLocation(),
15184 diag::note_declaration_not_a_prototype
)
15185 << (FD
->getNumParams() != 0)
15186 << (FD
->getNumParams() == 0 ? FixItHint::CreateInsertion(
15187 FTL
.getRParenLoc(), "void")
15191 // Returns true if the token beginning at this Loc is `const`.
15192 auto isLocAtConst
= [&](SourceLocation Loc
, const SourceManager
&SM
,
15193 const LangOptions
&LangOpts
) {
15194 std::pair
<FileID
, unsigned> LocInfo
= SM
.getDecomposedLoc(Loc
);
15195 if (LocInfo
.first
.isInvalid())
15198 bool Invalid
= false;
15199 StringRef Buffer
= SM
.getBufferData(LocInfo
.first
, &Invalid
);
15203 if (LocInfo
.second
> Buffer
.size())
15206 const char *LexStart
= Buffer
.data() + LocInfo
.second
;
15207 StringRef
StartTok(LexStart
, Buffer
.size() - LocInfo
.second
);
15209 return StartTok
.consume_front("const") &&
15210 (StartTok
.empty() || isWhitespace(StartTok
[0]) ||
15211 StartTok
.startswith("/*") || StartTok
.startswith("//"));
15214 auto findBeginLoc
= [&]() {
15215 // If the return type has `const` qualifier, we want to insert
15216 // `static` before `const` (and not before the typename).
15217 if ((FD
->getReturnType()->isAnyPointerType() &&
15218 FD
->getReturnType()->getPointeeType().isConstQualified()) ||
15219 FD
->getReturnType().isConstQualified()) {
15220 // But only do this if we can determine where the `const` is.
15222 if (isLocAtConst(FD
->getBeginLoc(), getSourceManager(),
15225 return FD
->getBeginLoc();
15227 return FD
->getTypeSpecStartLoc();
15229 Diag(FD
->getTypeSpecStartLoc(),
15230 diag::note_static_for_internal_linkage
)
15231 << /* function */ 1
15232 << (FD
->getStorageClass() == SC_None
15233 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15238 // If the function being defined does not have a prototype, then we may
15239 // need to diagnose it as changing behavior in C2x because we now know
15240 // whether the function accepts arguments or not. This only handles the
15241 // case where the definition has no prototype but does have parameters
15242 // and either there is no previous potential prototype, or the previous
15243 // potential prototype also has no actual prototype. This handles cases
15245 // void f(); void f(a) int a; {}
15246 // void g(a) int a; {}
15247 // See MergeFunctionDecl() for other cases of the behavior change
15248 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15249 // type without a prototype.
15250 if (!FD
->hasWrittenPrototype() && FD
->getNumParams() != 0 &&
15251 (!PossiblePrototype
|| (!PossiblePrototype
->hasWrittenPrototype() &&
15252 !PossiblePrototype
->isImplicit()))) {
15253 // The function definition has parameters, so this will change behavior
15254 // in C2x. If there is a possible prototype, it comes before the
15255 // function definition.
15256 // FIXME: The declaration may have already been diagnosed as being
15257 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15258 // there's no way to test for the "changes behavior" condition in
15259 // SemaType.cpp when forming the declaration's function type. So, we do
15260 // this awkward dance instead.
15262 // If we have a possible prototype and it declares a function with a
15263 // prototype, we don't want to diagnose it; if we have a possible
15264 // prototype and it has no prototype, it may have already been
15265 // diagnosed in SemaType.cpp as deprecated depending on whether
15266 // -Wstrict-prototypes is enabled. If we already warned about it being
15267 // deprecated, add a note that it also changes behavior. If we didn't
15268 // warn about it being deprecated (because the diagnostic is not
15269 // enabled), warn now that it is deprecated and changes behavior.
15271 // This K&R C function definition definitely changes behavior in C2x,
15273 Diag(FD
->getLocation(), diag::warn_non_prototype_changes_behavior
)
15274 << /*definition*/ 1 << /* not supported in C2x */ 0;
15276 // If we have a possible prototype for the function which is a user-
15277 // visible declaration, we already tested that it has no prototype.
15278 // This will change behavior in C2x. This gets a warning rather than a
15279 // note because it's the same behavior-changing problem as with the
15281 if (PossiblePrototype
)
15282 Diag(PossiblePrototype
->getLocation(),
15283 diag::warn_non_prototype_changes_behavior
)
15284 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15285 << /*definition*/ 1;
15288 // Warn on CPUDispatch with an actual body.
15289 if (FD
->isMultiVersion() && FD
->hasAttr
<CPUDispatchAttr
>() && Body
)
15290 if (const auto *CmpndBody
= dyn_cast
<CompoundStmt
>(Body
))
15291 if (!CmpndBody
->body_empty())
15292 Diag(CmpndBody
->body_front()->getBeginLoc(),
15293 diag::warn_dispatch_body_ignored
);
15295 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
15296 const CXXMethodDecl
*KeyFunction
;
15297 if (MD
->isOutOfLine() && (MD
= MD
->getCanonicalDecl()) &&
15299 (KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent())) &&
15300 MD
== KeyFunction
->getCanonicalDecl()) {
15301 // Update the key-function state if necessary for this ABI.
15302 if (FD
->isInlined() &&
15303 !Context
.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15304 Context
.setNonKeyFunction(MD
);
15306 // If the newly-chosen key function is already defined, then we
15307 // need to mark the vtable as used retroactively.
15308 KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent());
15309 const FunctionDecl
*Definition
;
15310 if (KeyFunction
&& KeyFunction
->isDefined(Definition
))
15311 MarkVTableUsed(Definition
->getLocation(), MD
->getParent(), true);
15313 // We just defined they key function; mark the vtable as used.
15314 MarkVTableUsed(FD
->getLocation(), MD
->getParent(), true);
15320 (FD
== getCurFunctionDecl() || getCurLambda()->CallOperator
== FD
) &&
15321 "Function parsing confused");
15322 } else if (ObjCMethodDecl
*MD
= dyn_cast_or_null
<ObjCMethodDecl
>(dcl
)) {
15323 assert(MD
== getCurMethodDecl() && "Method parsing confused");
15325 if (!MD
->isInvalidDecl()) {
15326 DiagnoseSizeOfParametersAndReturnValue(MD
->parameters(),
15327 MD
->getReturnType(), MD
);
15330 computeNRVO(Body
, FSI
);
15332 if (FSI
->ObjCShouldCallSuper
) {
15333 Diag(MD
->getEndLoc(), diag::warn_objc_missing_super_call
)
15334 << MD
->getSelector().getAsString();
15335 FSI
->ObjCShouldCallSuper
= false;
15337 if (FSI
->ObjCWarnForNoDesignatedInitChain
) {
15338 const ObjCMethodDecl
*InitMethod
= nullptr;
15339 bool isDesignated
=
15340 MD
->isDesignatedInitializerForTheInterface(&InitMethod
);
15341 assert(isDesignated
&& InitMethod
);
15342 (void)isDesignated
;
15344 auto superIsNSObject
= [&](const ObjCMethodDecl
*MD
) {
15345 auto IFace
= MD
->getClassInterface();
15348 auto SuperD
= IFace
->getSuperClass();
15351 return SuperD
->getIdentifier() ==
15352 NSAPIObj
->getNSClassId(NSAPI::ClassId_NSObject
);
15354 // Don't issue this warning for unavailable inits or direct subclasses
15356 if (!MD
->isUnavailable() && !superIsNSObject(MD
)) {
15357 Diag(MD
->getLocation(),
15358 diag::warn_objc_designated_init_missing_super_call
);
15359 Diag(InitMethod
->getLocation(),
15360 diag::note_objc_designated_init_marked_here
);
15362 FSI
->ObjCWarnForNoDesignatedInitChain
= false;
15364 if (FSI
->ObjCWarnForNoInitDelegation
) {
15365 // Don't issue this warning for unavaialable inits.
15366 if (!MD
->isUnavailable())
15367 Diag(MD
->getLocation(),
15368 diag::warn_objc_secondary_init_missing_init_call
);
15369 FSI
->ObjCWarnForNoInitDelegation
= false;
15372 diagnoseImplicitlyRetainedSelf(*this);
15374 // Parsing the function declaration failed in some way. Pop the fake scope
15376 PopFunctionScopeInfo(ActivePolicy
, dcl
);
15380 if (Body
&& FSI
->HasPotentialAvailabilityViolations
)
15381 DiagnoseUnguardedAvailabilityViolations(dcl
);
15383 assert(!FSI
->ObjCShouldCallSuper
&&
15384 "This should only be set for ObjC methods, which should have been "
15385 "handled in the block above.");
15387 // Verify and clean out per-function state.
15388 if (Body
&& (!FD
|| !FD
->isDefaulted())) {
15389 // C++ constructors that have function-try-blocks can't have return
15390 // statements in the handlers of that block. (C++ [except.handle]p14)
15392 if (FD
&& isa
<CXXConstructorDecl
>(FD
) && isa
<CXXTryStmt
>(Body
))
15393 DiagnoseReturnInConstructorExceptionHandler(cast
<CXXTryStmt
>(Body
));
15395 // Verify that gotos and switch cases don't jump into scopes illegally.
15396 if (FSI
->NeedsScopeChecking() && !PP
.isCodeCompletionEnabled())
15397 DiagnoseInvalidJumps(Body
);
15399 if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(dcl
)) {
15400 if (!Destructor
->getParent()->isDependentType())
15401 CheckDestructor(Destructor
);
15403 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
15404 Destructor
->getParent());
15407 // If any errors have occurred, clear out any temporaries that may have
15408 // been leftover. This ensures that these temporaries won't be picked up
15409 // for deletion in some later function.
15410 if (hasUncompilableErrorOccurred() ||
15411 getDiagnostics().getSuppressAllDiagnostics()) {
15412 DiscardCleanupsInEvaluationContext();
15414 if (!hasUncompilableErrorOccurred() && !isa
<FunctionTemplateDecl
>(dcl
)) {
15415 // Since the body is valid, issue any analysis-based warnings that are
15417 ActivePolicy
= &WP
;
15420 if (!IsInstantiation
&& FD
&& FD
->isConstexpr() && !FD
->isInvalidDecl() &&
15421 !CheckConstexprFunctionDefinition(FD
, CheckConstexprKind::Diagnose
))
15422 FD
->setInvalidDecl();
15424 if (FD
&& FD
->hasAttr
<NakedAttr
>()) {
15425 for (const Stmt
*S
: Body
->children()) {
15426 // Allow local register variables without initializer as they don't
15427 // require prologue.
15428 bool RegisterVariables
= false;
15429 if (auto *DS
= dyn_cast
<DeclStmt
>(S
)) {
15430 for (const auto *Decl
: DS
->decls()) {
15431 if (const auto *Var
= dyn_cast
<VarDecl
>(Decl
)) {
15432 RegisterVariables
=
15433 Var
->hasAttr
<AsmLabelAttr
>() && !Var
->hasInit();
15434 if (!RegisterVariables
)
15439 if (RegisterVariables
)
15441 if (!isa
<AsmStmt
>(S
) && !isa
<NullStmt
>(S
)) {
15442 Diag(S
->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function
);
15443 Diag(FD
->getAttr
<NakedAttr
>()->getLocation(), diag::note_attribute
);
15444 FD
->setInvalidDecl();
15450 assert(ExprCleanupObjects
.size() ==
15451 ExprEvalContexts
.back().NumCleanupObjects
&&
15452 "Leftover temporaries in function");
15453 assert(!Cleanup
.exprNeedsCleanups() &&
15454 "Unaccounted cleanups in function");
15455 assert(MaybeODRUseExprs
.empty() &&
15456 "Leftover expressions for odr-use checking");
15458 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15459 // the declaration context below. Otherwise, we're unable to transform
15460 // 'this' expressions when transforming immediate context functions.
15462 if (!IsInstantiation
)
15465 PopFunctionScopeInfo(ActivePolicy
, dcl
);
15466 // If any errors have occurred, clear out any temporaries that may have
15467 // been leftover. This ensures that these temporaries won't be picked up for
15468 // deletion in some later function.
15469 if (hasUncompilableErrorOccurred()) {
15470 DiscardCleanupsInEvaluationContext();
15473 if (FD
&& ((LangOpts
.OpenMP
&& (LangOpts
.OpenMPIsDevice
||
15474 !LangOpts
.OMPTargetTriples
.empty())) ||
15475 LangOpts
.CUDA
|| LangOpts
.SYCLIsDevice
)) {
15476 auto ES
= getEmissionStatus(FD
);
15477 if (ES
== Sema::FunctionEmissionStatus::Emitted
||
15478 ES
== Sema::FunctionEmissionStatus::Unknown
)
15479 DeclsToCheckForDeferredDiags
.insert(FD
);
15482 if (FD
&& !FD
->isDeleted())
15483 checkTypeSupport(FD
->getType(), FD
->getLocation(), FD
);
15488 /// When we finish delayed parsing of an attribute, we must attach it to the
15490 void Sema::ActOnFinishDelayedAttribute(Scope
*S
, Decl
*D
,
15491 ParsedAttributes
&Attrs
) {
15492 // Always attach attributes to the underlying decl.
15493 if (TemplateDecl
*TD
= dyn_cast
<TemplateDecl
>(D
))
15494 D
= TD
->getTemplatedDecl();
15495 ProcessDeclAttributeList(S
, D
, Attrs
);
15497 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(D
))
15498 if (Method
->isStatic())
15499 checkThisInStaticMemberFunctionAttributes(Method
);
15502 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15503 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15504 NamedDecl
*Sema::ImplicitlyDefineFunction(SourceLocation Loc
,
15505 IdentifierInfo
&II
, Scope
*S
) {
15506 // It is not valid to implicitly define a function in C2x.
15507 assert(LangOpts
.implicitFunctionsAllowed() &&
15508 "Implicit function declarations aren't allowed in this language mode");
15510 // Find the scope in which the identifier is injected and the corresponding
15512 // FIXME: C89 does not say what happens if there is no enclosing block scope.
15513 // In that case, we inject the declaration into the translation unit scope
15515 Scope
*BlockScope
= S
;
15516 while (!BlockScope
->isCompoundStmtScope() && BlockScope
->getParent())
15517 BlockScope
= BlockScope
->getParent();
15519 Scope
*ContextScope
= BlockScope
;
15520 while (!ContextScope
->getEntity())
15521 ContextScope
= ContextScope
->getParent();
15522 ContextRAII
SavedContext(*this, ContextScope
->getEntity());
15524 // Before we produce a declaration for an implicitly defined
15525 // function, see whether there was a locally-scoped declaration of
15526 // this name as a function or variable. If so, use that
15527 // (non-visible) declaration, and complain about it.
15528 NamedDecl
*ExternCPrev
= findLocallyScopedExternCDecl(&II
);
15530 // We still need to inject the function into the enclosing block scope so
15531 // that later (non-call) uses can see it.
15532 PushOnScopeChains(ExternCPrev
, BlockScope
, /*AddToContext*/false);
15534 // C89 footnote 38:
15535 // If in fact it is not defined as having type "function returning int",
15536 // the behavior is undefined.
15537 if (!isa
<FunctionDecl
>(ExternCPrev
) ||
15538 !Context
.typesAreCompatible(
15539 cast
<FunctionDecl
>(ExternCPrev
)->getType(),
15540 Context
.getFunctionNoProtoType(Context
.IntTy
))) {
15541 Diag(Loc
, diag::ext_use_out_of_scope_declaration
)
15542 << ExternCPrev
<< !getLangOpts().C99
;
15543 Diag(ExternCPrev
->getLocation(), diag::note_previous_declaration
);
15544 return ExternCPrev
;
15548 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15550 if (II
.getName().startswith("__builtin_"))
15551 diag_id
= diag::warn_builtin_unknown
;
15552 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15553 else if (getLangOpts().C99
)
15554 diag_id
= diag::ext_implicit_function_decl_c99
;
15556 diag_id
= diag::warn_implicit_function_decl
;
15558 TypoCorrection Corrected
;
15559 // Because typo correction is expensive, only do it if the implicit
15560 // function declaration is going to be treated as an error.
15562 // Perform the correction before issuing the main diagnostic, as some
15563 // consumers use typo-correction callbacks to enhance the main diagnostic.
15564 if (S
&& !ExternCPrev
&&
15565 (Diags
.getDiagnosticLevel(diag_id
, Loc
) >= DiagnosticsEngine::Error
)) {
15566 DeclFilterCCC
<FunctionDecl
> CCC
{};
15567 Corrected
= CorrectTypo(DeclarationNameInfo(&II
, Loc
), LookupOrdinaryName
,
15568 S
, nullptr, CCC
, CTK_NonError
);
15571 Diag(Loc
, diag_id
) << &II
;
15573 // If the correction is going to suggest an implicitly defined function,
15574 // skip the correction as not being a particularly good idea.
15575 bool Diagnose
= true;
15576 if (const auto *D
= Corrected
.getCorrectionDecl())
15577 Diagnose
= !D
->isImplicit();
15579 diagnoseTypo(Corrected
, PDiag(diag::note_function_suggestion
),
15580 /*ErrorRecovery*/ false);
15583 // If we found a prior declaration of this function, don't bother building
15584 // another one. We've already pushed that one into scope, so there's nothing
15587 return ExternCPrev
;
15589 // Set a Declarator for the implicit definition: int foo();
15591 AttributeFactory attrFactory
;
15592 DeclSpec
DS(attrFactory
);
15594 bool Error
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, Dummy
, DiagID
,
15595 Context
.getPrintingPolicy());
15596 (void)Error
; // Silence warning.
15597 assert(!Error
&& "Error setting up implicit decl!");
15598 SourceLocation NoLoc
;
15599 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::Block
);
15600 D
.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15601 /*IsAmbiguous=*/false,
15602 /*LParenLoc=*/NoLoc
,
15603 /*Params=*/nullptr,
15605 /*EllipsisLoc=*/NoLoc
,
15606 /*RParenLoc=*/NoLoc
,
15607 /*RefQualifierIsLvalueRef=*/true,
15608 /*RefQualifierLoc=*/NoLoc
,
15609 /*MutableLoc=*/NoLoc
, EST_None
,
15610 /*ESpecRange=*/SourceRange(),
15611 /*Exceptions=*/nullptr,
15612 /*ExceptionRanges=*/nullptr,
15613 /*NumExceptions=*/0,
15614 /*NoexceptExpr=*/nullptr,
15615 /*ExceptionSpecTokens=*/nullptr,
15616 /*DeclsInPrototype=*/None
, Loc
,
15618 std::move(DS
.getAttributes()), SourceLocation());
15619 D
.SetIdentifier(&II
, Loc
);
15621 // Insert this function into the enclosing block scope.
15622 FunctionDecl
*FD
= cast
<FunctionDecl
>(ActOnDeclarator(BlockScope
, D
));
15625 AddKnownFunctionAttributes(FD
);
15630 /// If this function is a C++ replaceable global allocation function
15631 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15632 /// adds any function attributes that we know a priori based on the standard.
15634 /// We need to check for duplicate attributes both here and where user-written
15635 /// attributes are applied to declarations.
15636 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15637 FunctionDecl
*FD
) {
15638 if (FD
->isInvalidDecl())
15641 if (FD
->getDeclName().getCXXOverloadedOperator() != OO_New
&&
15642 FD
->getDeclName().getCXXOverloadedOperator() != OO_Array_New
)
15645 Optional
<unsigned> AlignmentParam
;
15646 bool IsNothrow
= false;
15647 if (!FD
->isReplaceableGlobalAllocationFunction(&AlignmentParam
, &IsNothrow
))
15650 // C++2a [basic.stc.dynamic.allocation]p4:
15651 // An allocation function that has a non-throwing exception specification
15652 // indicates failure by returning a null pointer value. Any other allocation
15653 // function never returns a null pointer value and indicates failure only by
15654 // throwing an exception [...]
15655 if (!IsNothrow
&& !FD
->hasAttr
<ReturnsNonNullAttr
>())
15656 FD
->addAttr(ReturnsNonNullAttr::CreateImplicit(Context
, FD
->getLocation()));
15658 // C++2a [basic.stc.dynamic.allocation]p2:
15659 // An allocation function attempts to allocate the requested amount of
15660 // storage. [...] If the request succeeds, the value returned by a
15661 // replaceable allocation function is a [...] pointer value p0 different
15662 // from any previously returned value p1 [...]
15664 // However, this particular information is being added in codegen,
15665 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15667 // C++2a [basic.stc.dynamic.allocation]p2:
15668 // An allocation function attempts to allocate the requested amount of
15669 // storage. If it is successful, it returns the address of the start of a
15670 // block of storage whose length in bytes is at least as large as the
15672 if (!FD
->hasAttr
<AllocSizeAttr
>()) {
15673 FD
->addAttr(AllocSizeAttr::CreateImplicit(
15674 Context
, /*ElemSizeParam=*/ParamIdx(1, FD
),
15675 /*NumElemsParam=*/ParamIdx(), FD
->getLocation()));
15678 // C++2a [basic.stc.dynamic.allocation]p3:
15679 // For an allocation function [...], the pointer returned on a successful
15680 // call shall represent the address of storage that is aligned as follows:
15681 // (3.1) If the allocation function takes an argument of type
15682 // std​::​align_Âval_Ât, the storage will have the alignment
15683 // specified by the value of this argument.
15684 if (AlignmentParam
&& !FD
->hasAttr
<AllocAlignAttr
>()) {
15685 FD
->addAttr(AllocAlignAttr::CreateImplicit(
15686 Context
, ParamIdx(AlignmentParam
.value(), FD
), FD
->getLocation()));
15690 // C++2a [basic.stc.dynamic.allocation]p3:
15691 // For an allocation function [...], the pointer returned on a successful
15692 // call shall represent the address of storage that is aligned as follows:
15693 // (3.2) Otherwise, if the allocation function is named operator new[],
15694 // the storage is aligned for any object that does not have
15695 // new-extended alignment ([basic.align]) and is no larger than the
15697 // (3.3) Otherwise, the storage is aligned for any object that does not
15698 // have new-extended alignment and is of the requested size.
15701 /// Adds any function attributes that we know a priori based on
15702 /// the declaration of this function.
15704 /// These attributes can apply both to implicitly-declared builtins
15705 /// (like __builtin___printf_chk) or to library-declared functions
15706 /// like NSLog or printf.
15708 /// We need to check for duplicate attributes both here and where user-written
15709 /// attributes are applied to declarations.
15710 void Sema::AddKnownFunctionAttributes(FunctionDecl
*FD
) {
15711 if (FD
->isInvalidDecl())
15714 // If this is a built-in function, map its builtin attributes to
15715 // actual attributes.
15716 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
15717 // Handle printf-formatting attributes.
15718 unsigned FormatIdx
;
15720 if (Context
.BuiltinInfo
.isPrintfLike(BuiltinID
, FormatIdx
, HasVAListArg
)) {
15721 if (!FD
->hasAttr
<FormatAttr
>()) {
15722 const char *fmt
= "printf";
15723 unsigned int NumParams
= FD
->getNumParams();
15724 if (FormatIdx
< NumParams
&& // NumParams may be 0 (e.g. vfprintf)
15725 FD
->getParamDecl(FormatIdx
)->getType()->isObjCObjectPointerType())
15727 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
15728 &Context
.Idents
.get(fmt
),
15730 HasVAListArg
? 0 : FormatIdx
+2,
15731 FD
->getLocation()));
15734 if (Context
.BuiltinInfo
.isScanfLike(BuiltinID
, FormatIdx
,
15736 if (!FD
->hasAttr
<FormatAttr
>())
15737 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
15738 &Context
.Idents
.get("scanf"),
15740 HasVAListArg
? 0 : FormatIdx
+2,
15741 FD
->getLocation()));
15744 // Handle automatically recognized callbacks.
15745 SmallVector
<int, 4> Encoding
;
15746 if (!FD
->hasAttr
<CallbackAttr
>() &&
15747 Context
.BuiltinInfo
.performsCallback(BuiltinID
, Encoding
))
15748 FD
->addAttr(CallbackAttr::CreateImplicit(
15749 Context
, Encoding
.data(), Encoding
.size(), FD
->getLocation()));
15751 // Mark const if we don't care about errno and/or floating point exceptions
15752 // that are the only thing preventing the function from being const. This
15753 // allows IRgen to use LLVM intrinsics for such functions.
15754 bool NoExceptions
=
15755 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore
;
15756 bool ConstWithoutErrnoAndExceptions
=
15757 Context
.BuiltinInfo
.isConstWithoutErrnoAndExceptions(BuiltinID
);
15758 bool ConstWithoutExceptions
=
15759 Context
.BuiltinInfo
.isConstWithoutExceptions(BuiltinID
);
15760 if (!FD
->hasAttr
<ConstAttr
>() &&
15761 (ConstWithoutErrnoAndExceptions
|| ConstWithoutExceptions
) &&
15762 (!ConstWithoutErrnoAndExceptions
||
15763 (!getLangOpts().MathErrno
&& NoExceptions
)) &&
15764 (!ConstWithoutExceptions
|| NoExceptions
))
15765 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
15767 // We make "fma" on GNU or Windows const because we know it does not set
15768 // errno in those environments even though it could set errno based on the
15770 const llvm::Triple
&Trip
= Context
.getTargetInfo().getTriple();
15771 if ((Trip
.isGNUEnvironment() || Trip
.isOSMSVCRT()) &&
15772 !FD
->hasAttr
<ConstAttr
>()) {
15773 switch (BuiltinID
) {
15774 case Builtin::BI__builtin_fma
:
15775 case Builtin::BI__builtin_fmaf
:
15776 case Builtin::BI__builtin_fmal
:
15777 case Builtin::BIfma
:
15778 case Builtin::BIfmaf
:
15779 case Builtin::BIfmal
:
15780 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
15787 if (Context
.BuiltinInfo
.isReturnsTwice(BuiltinID
) &&
15788 !FD
->hasAttr
<ReturnsTwiceAttr
>())
15789 FD
->addAttr(ReturnsTwiceAttr::CreateImplicit(Context
,
15790 FD
->getLocation()));
15791 if (Context
.BuiltinInfo
.isNoThrow(BuiltinID
) && !FD
->hasAttr
<NoThrowAttr
>())
15792 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
15793 if (Context
.BuiltinInfo
.isPure(BuiltinID
) && !FD
->hasAttr
<PureAttr
>())
15794 FD
->addAttr(PureAttr::CreateImplicit(Context
, FD
->getLocation()));
15795 if (Context
.BuiltinInfo
.isConst(BuiltinID
) && !FD
->hasAttr
<ConstAttr
>())
15796 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
15797 if (getLangOpts().CUDA
&& Context
.BuiltinInfo
.isTSBuiltin(BuiltinID
) &&
15798 !FD
->hasAttr
<CUDADeviceAttr
>() && !FD
->hasAttr
<CUDAHostAttr
>()) {
15799 // Add the appropriate attribute, depending on the CUDA compilation mode
15800 // and which target the builtin belongs to. For example, during host
15801 // compilation, aux builtins are __device__, while the rest are __host__.
15802 if (getLangOpts().CUDAIsDevice
!=
15803 Context
.BuiltinInfo
.isAuxBuiltinID(BuiltinID
))
15804 FD
->addAttr(CUDADeviceAttr::CreateImplicit(Context
, FD
->getLocation()));
15806 FD
->addAttr(CUDAHostAttr::CreateImplicit(Context
, FD
->getLocation()));
15809 // Add known guaranteed alignment for allocation functions.
15810 switch (BuiltinID
) {
15811 case Builtin::BImemalign
:
15812 case Builtin::BIaligned_alloc
:
15813 if (!FD
->hasAttr
<AllocAlignAttr
>())
15814 FD
->addAttr(AllocAlignAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
15815 FD
->getLocation()));
15821 // Add allocsize attribute for allocation functions.
15822 switch (BuiltinID
) {
15823 case Builtin::BIcalloc
:
15824 FD
->addAttr(AllocSizeAttr::CreateImplicit(
15825 Context
, ParamIdx(1, FD
), ParamIdx(2, FD
), FD
->getLocation()));
15827 case Builtin::BImemalign
:
15828 case Builtin::BIaligned_alloc
:
15829 case Builtin::BIrealloc
:
15830 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(2, FD
),
15831 ParamIdx(), FD
->getLocation()));
15833 case Builtin::BImalloc
:
15834 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
15835 ParamIdx(), FD
->getLocation()));
15842 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD
);
15844 // If C++ exceptions are enabled but we are told extern "C" functions cannot
15845 // throw, add an implicit nothrow attribute to any extern "C" function we come
15847 if (getLangOpts().CXXExceptions
&& getLangOpts().ExternCNoUnwind
&&
15848 FD
->isExternC() && !FD
->hasAttr
<NoThrowAttr
>()) {
15849 const auto *FPT
= FD
->getType()->getAs
<FunctionProtoType
>();
15850 if (!FPT
|| FPT
->getExceptionSpecType() == EST_None
)
15851 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
15854 IdentifierInfo
*Name
= FD
->getIdentifier();
15857 if ((!getLangOpts().CPlusPlus
&&
15858 FD
->getDeclContext()->isTranslationUnit()) ||
15859 (isa
<LinkageSpecDecl
>(FD
->getDeclContext()) &&
15860 cast
<LinkageSpecDecl
>(FD
->getDeclContext())->getLanguage() ==
15861 LinkageSpecDecl::lang_c
)) {
15862 // Okay: this could be a libc/libm/Objective-C function we know
15867 if (Name
->isStr("asprintf") || Name
->isStr("vasprintf")) {
15868 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15869 // target-specific builtins, perhaps?
15870 if (!FD
->hasAttr
<FormatAttr
>())
15871 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
15872 &Context
.Idents
.get("printf"), 2,
15873 Name
->isStr("vasprintf") ? 0 : 3,
15874 FD
->getLocation()));
15877 if (Name
->isStr("__CFStringMakeConstantString")) {
15878 // We already have a __builtin___CFStringMakeConstantString,
15879 // but builds that use -fno-constant-cfstrings don't go through that.
15880 if (!FD
->hasAttr
<FormatArgAttr
>())
15881 FD
->addAttr(FormatArgAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
15882 FD
->getLocation()));
15886 TypedefDecl
*Sema::ParseTypedefDecl(Scope
*S
, Declarator
&D
, QualType T
,
15887 TypeSourceInfo
*TInfo
) {
15888 assert(D
.getIdentifier() && "Wrong callback for declspec without declarator");
15889 assert(!T
.isNull() && "GetTypeForDeclarator() returned null type");
15892 assert(D
.isInvalidType() && "no declarator info for valid type");
15893 TInfo
= Context
.getTrivialTypeSourceInfo(T
);
15896 // Scope manipulation handled by caller.
15897 TypedefDecl
*NewTD
=
15898 TypedefDecl::Create(Context
, CurContext
, D
.getBeginLoc(),
15899 D
.getIdentifierLoc(), D
.getIdentifier(), TInfo
);
15901 // Bail out immediately if we have an invalid declaration.
15902 if (D
.isInvalidType()) {
15903 NewTD
->setInvalidDecl();
15907 if (D
.getDeclSpec().isModulePrivateSpecified()) {
15908 if (CurContext
->isFunctionOrMethod())
15909 Diag(NewTD
->getLocation(), diag::err_module_private_local
)
15911 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
15912 << FixItHint::CreateRemoval(
15913 D
.getDeclSpec().getModulePrivateSpecLoc());
15915 NewTD
->setModulePrivate();
15918 // C++ [dcl.typedef]p8:
15919 // If the typedef declaration defines an unnamed class (or
15920 // enum), the first typedef-name declared by the declaration
15921 // to be that class type (or enum type) is used to denote the
15922 // class type (or enum type) for linkage purposes only.
15923 // We need to check whether the type was declared in the declaration.
15924 switch (D
.getDeclSpec().getTypeSpecType()) {
15927 case TST_interface
:
15930 TagDecl
*tagFromDeclSpec
= cast
<TagDecl
>(D
.getDeclSpec().getRepAsDecl());
15931 setTagNameForLinkagePurposes(tagFromDeclSpec
, NewTD
);
15942 /// Check that this is a valid underlying type for an enum declaration.
15943 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo
*TI
) {
15944 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
15945 QualType T
= TI
->getType();
15947 if (T
->isDependentType())
15950 // This doesn't use 'isIntegralType' despite the error message mentioning
15951 // integral type because isIntegralType would also allow enum types in C.
15952 if (const BuiltinType
*BT
= T
->getAs
<BuiltinType
>())
15953 if (BT
->isInteger())
15956 if (T
->isBitIntType())
15959 return Diag(UnderlyingLoc
, diag::err_enum_invalid_underlying
) << T
;
15962 /// Check whether this is a valid redeclaration of a previous enumeration.
15963 /// \return true if the redeclaration was invalid.
15964 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc
, bool IsScoped
,
15965 QualType EnumUnderlyingTy
, bool IsFixed
,
15966 const EnumDecl
*Prev
) {
15967 if (IsScoped
!= Prev
->isScoped()) {
15968 Diag(EnumLoc
, diag::err_enum_redeclare_scoped_mismatch
)
15969 << Prev
->isScoped();
15970 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
15974 if (IsFixed
&& Prev
->isFixed()) {
15975 if (!EnumUnderlyingTy
->isDependentType() &&
15976 !Prev
->getIntegerType()->isDependentType() &&
15977 !Context
.hasSameUnqualifiedType(EnumUnderlyingTy
,
15978 Prev
->getIntegerType())) {
15979 // TODO: Highlight the underlying type of the redeclaration.
15980 Diag(EnumLoc
, diag::err_enum_redeclare_type_mismatch
)
15981 << EnumUnderlyingTy
<< Prev
->getIntegerType();
15982 Diag(Prev
->getLocation(), diag::note_previous_declaration
)
15983 << Prev
->getIntegerTypeRange();
15986 } else if (IsFixed
!= Prev
->isFixed()) {
15987 Diag(EnumLoc
, diag::err_enum_redeclare_fixed_mismatch
)
15988 << Prev
->isFixed();
15989 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
15996 /// Get diagnostic %select index for tag kind for
15997 /// redeclaration diagnostic message.
15998 /// WARNING: Indexes apply to particular diagnostics only!
16000 /// \returns diagnostic %select index.
16001 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag
) {
16003 case TTK_Struct
: return 0;
16004 case TTK_Interface
: return 1;
16005 case TTK_Class
: return 2;
16006 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16010 /// Determine if tag kind is a class-key compatible with
16011 /// class for redeclaration (class, struct, or __interface).
16013 /// \returns true iff the tag kind is compatible.
16014 static bool isClassCompatTagKind(TagTypeKind Tag
)
16016 return Tag
== TTK_Struct
|| Tag
== TTK_Class
|| Tag
== TTK_Interface
;
16019 Sema::NonTagKind
Sema::getNonTagTypeDeclKind(const Decl
*PrevDecl
,
16021 if (isa
<TypedefDecl
>(PrevDecl
))
16022 return NTK_Typedef
;
16023 else if (isa
<TypeAliasDecl
>(PrevDecl
))
16024 return NTK_TypeAlias
;
16025 else if (isa
<ClassTemplateDecl
>(PrevDecl
))
16026 return NTK_Template
;
16027 else if (isa
<TypeAliasTemplateDecl
>(PrevDecl
))
16028 return NTK_TypeAliasTemplate
;
16029 else if (isa
<TemplateTemplateParmDecl
>(PrevDecl
))
16030 return NTK_TemplateTemplateArgument
;
16033 case TTK_Interface
:
16035 return getLangOpts().CPlusPlus
? NTK_NonClass
: NTK_NonStruct
;
16037 return NTK_NonUnion
;
16039 return NTK_NonEnum
;
16041 llvm_unreachable("invalid TTK");
16044 /// Determine whether a tag with a given kind is acceptable
16045 /// as a redeclaration of the given tag declaration.
16047 /// \returns true if the new tag kind is acceptable, false otherwise.
16048 bool Sema::isAcceptableTagRedeclaration(const TagDecl
*Previous
,
16049 TagTypeKind NewTag
, bool isDefinition
,
16050 SourceLocation NewTagLoc
,
16051 const IdentifierInfo
*Name
) {
16052 // C++ [dcl.type.elab]p3:
16053 // The class-key or enum keyword present in the
16054 // elaborated-type-specifier shall agree in kind with the
16055 // declaration to which the name in the elaborated-type-specifier
16056 // refers. This rule also applies to the form of
16057 // elaborated-type-specifier that declares a class-name or
16058 // friend class since it can be construed as referring to the
16059 // definition of the class. Thus, in any
16060 // elaborated-type-specifier, the enum keyword shall be used to
16061 // refer to an enumeration (7.2), the union class-key shall be
16062 // used to refer to a union (clause 9), and either the class or
16063 // struct class-key shall be used to refer to a class (clause 9)
16064 // declared using the class or struct class-key.
16065 TagTypeKind OldTag
= Previous
->getTagKind();
16066 if (OldTag
!= NewTag
&&
16067 !(isClassCompatTagKind(OldTag
) && isClassCompatTagKind(NewTag
)))
16070 // Tags are compatible, but we might still want to warn on mismatched tags.
16071 // Non-class tags can't be mismatched at this point.
16072 if (!isClassCompatTagKind(NewTag
))
16075 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16076 // by our warning analysis. We don't want to warn about mismatches with (eg)
16077 // declarations in system headers that are designed to be specialized, but if
16078 // a user asks us to warn, we should warn if their code contains mismatched
16080 auto IsIgnoredLoc
= [&](SourceLocation Loc
) {
16081 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch
,
16084 if (IsIgnoredLoc(NewTagLoc
))
16087 auto IsIgnored
= [&](const TagDecl
*Tag
) {
16088 return IsIgnoredLoc(Tag
->getLocation());
16090 while (IsIgnored(Previous
)) {
16091 Previous
= Previous
->getPreviousDecl();
16094 OldTag
= Previous
->getTagKind();
16097 bool isTemplate
= false;
16098 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Previous
))
16099 isTemplate
= Record
->getDescribedClassTemplate();
16101 if (inTemplateInstantiation()) {
16102 if (OldTag
!= NewTag
) {
16103 // In a template instantiation, do not offer fix-its for tag mismatches
16104 // since they usually mess up the template instead of fixing the problem.
16105 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16106 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16107 << getRedeclDiagFromTagKind(OldTag
);
16108 // FIXME: Note previous location?
16113 if (isDefinition
) {
16114 // On definitions, check all previous tags and issue a fix-it for each
16115 // one that doesn't match the current tag.
16116 if (Previous
->getDefinition()) {
16117 // Don't suggest fix-its for redefinitions.
16121 bool previousMismatch
= false;
16122 for (const TagDecl
*I
: Previous
->redecls()) {
16123 if (I
->getTagKind() != NewTag
) {
16124 // Ignore previous declarations for which the warning was disabled.
16128 if (!previousMismatch
) {
16129 previousMismatch
= true;
16130 Diag(NewTagLoc
, diag::warn_struct_class_previous_tag_mismatch
)
16131 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16132 << getRedeclDiagFromTagKind(I
->getTagKind());
16134 Diag(I
->getInnerLocStart(), diag::note_struct_class_suggestion
)
16135 << getRedeclDiagFromTagKind(NewTag
)
16136 << FixItHint::CreateReplacement(I
->getInnerLocStart(),
16137 TypeWithKeyword::getTagTypeKindName(NewTag
));
16143 // Identify the prevailing tag kind: this is the kind of the definition (if
16144 // there is a non-ignored definition), or otherwise the kind of the prior
16145 // (non-ignored) declaration.
16146 const TagDecl
*PrevDef
= Previous
->getDefinition();
16147 if (PrevDef
&& IsIgnored(PrevDef
))
16149 const TagDecl
*Redecl
= PrevDef
? PrevDef
: Previous
;
16150 if (Redecl
->getTagKind() != NewTag
) {
16151 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16152 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16153 << getRedeclDiagFromTagKind(OldTag
);
16154 Diag(Redecl
->getLocation(), diag::note_previous_use
);
16156 // If there is a previous definition, suggest a fix-it.
16158 Diag(NewTagLoc
, diag::note_struct_class_suggestion
)
16159 << getRedeclDiagFromTagKind(Redecl
->getTagKind())
16160 << FixItHint::CreateReplacement(SourceRange(NewTagLoc
),
16161 TypeWithKeyword::getTagTypeKindName(Redecl
->getTagKind()));
16168 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16169 /// from an outer enclosing namespace or file scope inside a friend declaration.
16170 /// This should provide the commented out code in the following snippet:
16174 /// struct Y { friend struct /*N::*/ X; };
16177 static FixItHint
createFriendTagNNSFixIt(Sema
&SemaRef
, NamedDecl
*ND
, Scope
*S
,
16178 SourceLocation NameLoc
) {
16179 // While the decl is in a namespace, do repeated lookup of that name and see
16180 // if we get the same namespace back. If we do not, continue until
16181 // translation unit scope, at which point we have a fully qualified NNS.
16182 SmallVector
<IdentifierInfo
*, 4> Namespaces
;
16183 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
16184 for (; !DC
->isTranslationUnit(); DC
= DC
->getParent()) {
16185 // This tag should be declared in a namespace, which can only be enclosed by
16186 // other namespaces. Bail if there's an anonymous namespace in the chain.
16187 NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(DC
);
16188 if (!Namespace
|| Namespace
->isAnonymousNamespace())
16189 return FixItHint();
16190 IdentifierInfo
*II
= Namespace
->getIdentifier();
16191 Namespaces
.push_back(II
);
16192 NamedDecl
*Lookup
= SemaRef
.LookupSingleName(
16193 S
, II
, NameLoc
, Sema::LookupNestedNameSpecifierName
);
16194 if (Lookup
== Namespace
)
16198 // Once we have all the namespaces, reverse them to go outermost first, and
16200 SmallString
<64> Insertion
;
16201 llvm::raw_svector_ostream
OS(Insertion
);
16202 if (DC
->isTranslationUnit())
16204 std::reverse(Namespaces
.begin(), Namespaces
.end());
16205 for (auto *II
: Namespaces
)
16206 OS
<< II
->getName() << "::";
16207 return FixItHint::CreateInsertion(NameLoc
, Insertion
);
16210 /// Determine whether a tag originally declared in context \p OldDC can
16211 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16212 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16213 /// using-declaration).
16214 static bool isAcceptableTagRedeclContext(Sema
&S
, DeclContext
*OldDC
,
16215 DeclContext
*NewDC
) {
16216 OldDC
= OldDC
->getRedeclContext();
16217 NewDC
= NewDC
->getRedeclContext();
16219 if (OldDC
->Equals(NewDC
))
16222 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16223 // encloses the other).
16224 if (S
.getLangOpts().MSVCCompat
&&
16225 (OldDC
->Encloses(NewDC
) || NewDC
->Encloses(OldDC
)))
16231 /// This is invoked when we see 'struct foo' or 'struct {'. In the
16232 /// former case, Name will be non-null. In the later case, Name will be null.
16233 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16234 /// reference/declaration/definition of a tag.
16236 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16237 /// trailing-type-specifier) other than one in an alias-declaration.
16239 /// \param SkipBody If non-null, will be set to indicate if the caller should
16240 /// skip the definition of this tag and treat it as if it were a declaration.
16241 Decl
*Sema::ActOnTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
,
16242 SourceLocation KWLoc
, CXXScopeSpec
&SS
,
16243 IdentifierInfo
*Name
, SourceLocation NameLoc
,
16244 const ParsedAttributesView
&Attrs
, AccessSpecifier AS
,
16245 SourceLocation ModulePrivateLoc
,
16246 MultiTemplateParamsArg TemplateParameterLists
,
16247 bool &OwnedDecl
, bool &IsDependent
,
16248 SourceLocation ScopedEnumKWLoc
,
16249 bool ScopedEnumUsesClassTag
, TypeResult UnderlyingType
,
16250 bool IsTypeSpecifier
, bool IsTemplateParamOrArg
,
16251 SkipBodyInfo
*SkipBody
) {
16252 // If this is not a definition, it must have a name.
16253 IdentifierInfo
*OrigName
= Name
;
16254 assert((Name
!= nullptr || TUK
== TUK_Definition
) &&
16255 "Nameless record must be a definition!");
16256 assert(TemplateParameterLists
.size() == 0 || TUK
!= TUK_Reference
);
16259 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
16260 bool ScopedEnum
= ScopedEnumKWLoc
.isValid();
16262 // FIXME: Check member specializations more carefully.
16263 bool isMemberSpecialization
= false;
16264 bool Invalid
= false;
16266 // We only need to do this matching if we have template parameters
16267 // or a scope specifier, which also conveniently avoids this work
16268 // for non-C++ cases.
16269 if (TemplateParameterLists
.size() > 0 ||
16270 (SS
.isNotEmpty() && TUK
!= TUK_Reference
)) {
16271 if (TemplateParameterList
*TemplateParams
=
16272 MatchTemplateParametersToScopeSpecifier(
16273 KWLoc
, NameLoc
, SS
, nullptr, TemplateParameterLists
,
16274 TUK
== TUK_Friend
, isMemberSpecialization
, Invalid
)) {
16275 if (Kind
== TTK_Enum
) {
16276 Diag(KWLoc
, diag::err_enum_template
);
16280 if (TemplateParams
->size() > 0) {
16281 // This is a declaration or definition of a class template (which may
16282 // be a member of another template).
16288 DeclResult Result
= CheckClassTemplate(
16289 S
, TagSpec
, TUK
, KWLoc
, SS
, Name
, NameLoc
, Attrs
, TemplateParams
,
16290 AS
, ModulePrivateLoc
,
16291 /*FriendLoc*/ SourceLocation(), TemplateParameterLists
.size() - 1,
16292 TemplateParameterLists
.data(), SkipBody
);
16293 return Result
.get();
16295 // The "template<>" header is extraneous.
16296 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
16297 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
16298 isMemberSpecialization
= true;
16302 if (!TemplateParameterLists
.empty() && isMemberSpecialization
&&
16303 CheckTemplateDeclScope(S
, TemplateParameterLists
.back()))
16307 // Figure out the underlying type if this a enum declaration. We need to do
16308 // this early, because it's needed to detect if this is an incompatible
16310 llvm::PointerUnion
<const Type
*, TypeSourceInfo
*> EnumUnderlying
;
16311 bool IsFixed
= !UnderlyingType
.isUnset() || ScopedEnum
;
16313 if (Kind
== TTK_Enum
) {
16314 if (UnderlyingType
.isInvalid() || (!UnderlyingType
.get() && ScopedEnum
)) {
16315 // No underlying type explicitly specified, or we failed to parse the
16316 // type, default to int.
16317 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16318 } else if (UnderlyingType
.get()) {
16319 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16320 // integral type; any cv-qualification is ignored.
16321 TypeSourceInfo
*TI
= nullptr;
16322 GetTypeFromParser(UnderlyingType
.get(), &TI
);
16323 EnumUnderlying
= TI
;
16325 if (CheckEnumUnderlyingType(TI
))
16326 // Recover by falling back to int.
16327 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16329 if (DiagnoseUnexpandedParameterPack(TI
->getTypeLoc().getBeginLoc(), TI
,
16330 UPPC_FixedUnderlyingType
))
16331 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16333 } else if (Context
.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16334 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16335 // of 'int'. However, if this is an unfixed forward declaration, don't set
16336 // the underlying type unless the user enables -fms-compatibility. This
16337 // makes unfixed forward declared enums incomplete and is more conforming.
16338 if (TUK
== TUK_Definition
|| getLangOpts().MSVCCompat
)
16339 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16343 DeclContext
*SearchDC
= CurContext
;
16344 DeclContext
*DC
= CurContext
;
16345 bool isStdBadAlloc
= false;
16346 bool isStdAlignValT
= false;
16348 RedeclarationKind Redecl
= forRedeclarationInCurContext();
16349 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
)
16350 Redecl
= NotForRedeclaration
;
16352 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16353 /// implemented asks for structural equivalence checking, the returned decl
16354 /// here is passed back to the parser, allowing the tag body to be parsed.
16355 auto createTagFromNewDecl
= [&]() -> TagDecl
* {
16356 assert(!getLangOpts().CPlusPlus
&& "not meant for C++ usage");
16357 // If there is an identifier, use the location of the identifier as the
16358 // location of the decl, otherwise use the location of the struct/union
16360 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
16361 TagDecl
*New
= nullptr;
16363 if (Kind
== TTK_Enum
) {
16364 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
, nullptr,
16365 ScopedEnum
, ScopedEnumUsesClassTag
, IsFixed
);
16366 // If this is an undefined enum, bail.
16367 if (TUK
!= TUK_Definition
&& !Invalid
)
16369 if (EnumUnderlying
) {
16370 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
16371 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
16372 ED
->setIntegerTypeSourceInfo(TI
);
16374 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
16375 QualType EnumTy
= ED
->getIntegerType();
16376 ED
->setPromotionType(EnumTy
->isPromotableIntegerType()
16377 ? Context
.getPromotedIntegerType(EnumTy
)
16380 } else { // struct/union
16381 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
16385 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
16386 // Add alignment attributes if necessary; these attributes are checked
16387 // when the ASTContext lays out the structure.
16389 // It is important for implementing the correct semantics that this
16390 // happen here (in ActOnTag). The #pragma pack stack is
16391 // maintained as a result of parser callbacks which can occur at
16392 // many points during the parsing of a struct declaration (because
16393 // the #pragma tokens are effectively skipped over during the
16394 // parsing of the struct).
16395 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
16396 AddAlignmentAttributesForRecord(RD
);
16397 AddMsStructLayoutForRecord(RD
);
16400 New
->setLexicalDeclContext(CurContext
);
16404 LookupResult
Previous(*this, Name
, NameLoc
, LookupTagName
, Redecl
);
16405 if (Name
&& SS
.isNotEmpty()) {
16406 // We have a nested-name tag ('struct foo::bar').
16408 // Check for invalid 'foo::'.
16409 if (SS
.isInvalid()) {
16411 goto CreateNewDecl
;
16414 // If this is a friend or a reference to a class in a dependent
16415 // context, don't try to make a decl for it.
16416 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
16417 DC
= computeDeclContext(SS
, false);
16419 IsDependent
= true;
16423 DC
= computeDeclContext(SS
, true);
16425 Diag(SS
.getRange().getBegin(), diag::err_dependent_nested_name_spec
)
16431 if (RequireCompleteDeclContext(SS
, DC
))
16435 // Look-up name inside 'foo::'.
16436 LookupQualifiedName(Previous
, DC
);
16438 if (Previous
.isAmbiguous())
16441 if (Previous
.empty()) {
16442 // Name lookup did not find anything. However, if the
16443 // nested-name-specifier refers to the current instantiation,
16444 // and that current instantiation has any dependent base
16445 // classes, we might find something at instantiation time: treat
16446 // this as a dependent elaborated-type-specifier.
16447 // But this only makes any sense for reference-like lookups.
16448 if (Previous
.wasNotFoundInCurrentInstantiation() &&
16449 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)) {
16450 IsDependent
= true;
16454 // A tag 'foo::bar' must already exist.
16455 Diag(NameLoc
, diag::err_not_tag_in_scope
)
16456 << Kind
<< Name
<< DC
<< SS
.getRange();
16459 goto CreateNewDecl
;
16462 // C++14 [class.mem]p14:
16463 // If T is the name of a class, then each of the following shall have a
16464 // name different from T:
16465 // -- every member of class T that is itself a type
16466 if (TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
16467 DiagnoseClassNameShadow(SearchDC
, DeclarationNameInfo(Name
, NameLoc
)))
16470 // If this is a named struct, check to see if there was a previous forward
16471 // declaration or definition.
16472 // FIXME: We're looking into outer scopes here, even when we
16473 // shouldn't be. Doing so can result in ambiguities that we
16474 // shouldn't be diagnosing.
16475 LookupName(Previous
, S
);
16477 // When declaring or defining a tag, ignore ambiguities introduced
16478 // by types using'ed into this scope.
16479 if (Previous
.isAmbiguous() &&
16480 (TUK
== TUK_Definition
|| TUK
== TUK_Declaration
)) {
16481 LookupResult::Filter F
= Previous
.makeFilter();
16482 while (F
.hasNext()) {
16483 NamedDecl
*ND
= F
.next();
16484 if (!ND
->getDeclContext()->getRedeclContext()->Equals(
16485 SearchDC
->getRedeclContext()))
16491 // C++11 [namespace.memdef]p3:
16492 // If the name in a friend declaration is neither qualified nor
16493 // a template-id and the declaration is a function or an
16494 // elaborated-type-specifier, the lookup to determine whether
16495 // the entity has been previously declared shall not consider
16496 // any scopes outside the innermost enclosing namespace.
16498 // MSVC doesn't implement the above rule for types, so a friend tag
16499 // declaration may be a redeclaration of a type declared in an enclosing
16500 // scope. They do implement this rule for friend functions.
16502 // Does it matter that this should be by scope instead of by
16503 // semantic context?
16504 if (!Previous
.empty() && TUK
== TUK_Friend
) {
16505 DeclContext
*EnclosingNS
= SearchDC
->getEnclosingNamespaceContext();
16506 LookupResult::Filter F
= Previous
.makeFilter();
16507 bool FriendSawTagOutsideEnclosingNamespace
= false;
16508 while (F
.hasNext()) {
16509 NamedDecl
*ND
= F
.next();
16510 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
16511 if (DC
->isFileContext() &&
16512 !EnclosingNS
->Encloses(ND
->getDeclContext())) {
16513 if (getLangOpts().MSVCCompat
)
16514 FriendSawTagOutsideEnclosingNamespace
= true;
16521 // Diagnose this MSVC extension in the easy case where lookup would have
16522 // unambiguously found something outside the enclosing namespace.
16523 if (Previous
.isSingleResult() && FriendSawTagOutsideEnclosingNamespace
) {
16524 NamedDecl
*ND
= Previous
.getFoundDecl();
16525 Diag(NameLoc
, diag::ext_friend_tag_redecl_outside_namespace
)
16526 << createFriendTagNNSFixIt(*this, ND
, S
, NameLoc
);
16530 // Note: there used to be some attempt at recovery here.
16531 if (Previous
.isAmbiguous())
16534 if (!getLangOpts().CPlusPlus
&& TUK
!= TUK_Reference
) {
16535 // FIXME: This makes sure that we ignore the contexts associated
16536 // with C structs, unions, and enums when looking for a matching
16537 // tag declaration or definition. See the similar lookup tweak
16538 // in Sema::LookupName; is there a better way to deal with this?
16539 while (isa
<RecordDecl
, EnumDecl
, ObjCContainerDecl
>(SearchDC
))
16540 SearchDC
= SearchDC
->getParent();
16541 } else if (getLangOpts().CPlusPlus
) {
16542 // Inside ObjCContainer want to keep it as a lexical decl context but go
16543 // past it (most often to TranslationUnit) to find the semantic decl
16545 while (isa
<ObjCContainerDecl
>(SearchDC
))
16546 SearchDC
= SearchDC
->getParent();
16548 } else if (getLangOpts().CPlusPlus
) {
16549 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16550 // TagDecl the same way as we skip it for named TagDecl.
16551 while (isa
<ObjCContainerDecl
>(SearchDC
))
16552 SearchDC
= SearchDC
->getParent();
16555 if (Previous
.isSingleResult() &&
16556 Previous
.getFoundDecl()->isTemplateParameter()) {
16557 // Maybe we will complain about the shadowed template parameter.
16558 DiagnoseTemplateParameterShadow(NameLoc
, Previous
.getFoundDecl());
16559 // Just pretend that we didn't see the previous declaration.
16563 if (getLangOpts().CPlusPlus
&& Name
&& DC
&& StdNamespace
&&
16564 DC
->Equals(getStdNamespace())) {
16565 if (Name
->isStr("bad_alloc")) {
16566 // This is a declaration of or a reference to "std::bad_alloc".
16567 isStdBadAlloc
= true;
16569 // If std::bad_alloc has been implicitly declared (but made invisible to
16570 // name lookup), fill in this implicit declaration as the previous
16571 // declaration, so that the declarations get chained appropriately.
16572 if (Previous
.empty() && StdBadAlloc
)
16573 Previous
.addDecl(getStdBadAlloc());
16574 } else if (Name
->isStr("align_val_t")) {
16575 isStdAlignValT
= true;
16576 if (Previous
.empty() && StdAlignValT
)
16577 Previous
.addDecl(getStdAlignValT());
16581 // If we didn't find a previous declaration, and this is a reference
16582 // (or friend reference), move to the correct scope. In C++, we
16583 // also need to do a redeclaration lookup there, just in case
16584 // there's a shadow friend decl.
16585 if (Name
&& Previous
.empty() &&
16586 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
|| IsTemplateParamOrArg
)) {
16587 if (Invalid
) goto CreateNewDecl
;
16588 assert(SS
.isEmpty());
16590 if (TUK
== TUK_Reference
|| IsTemplateParamOrArg
) {
16591 // C++ [basic.scope.pdecl]p5:
16592 // -- for an elaborated-type-specifier of the form
16594 // class-key identifier
16596 // if the elaborated-type-specifier is used in the
16597 // decl-specifier-seq or parameter-declaration-clause of a
16598 // function defined in namespace scope, the identifier is
16599 // declared as a class-name in the namespace that contains
16600 // the declaration; otherwise, except as a friend
16601 // declaration, the identifier is declared in the smallest
16602 // non-class, non-function-prototype scope that contains the
16605 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16606 // C structs and unions.
16608 // It is an error in C++ to declare (rather than define) an enum
16609 // type, including via an elaborated type specifier. We'll
16610 // diagnose that later; for now, declare the enum in the same
16611 // scope as we would have picked for any other tag type.
16613 // GNU C also supports this behavior as part of its incomplete
16614 // enum types extension, while GNU C++ does not.
16616 // Find the context where we'll be declaring the tag.
16617 // FIXME: We would like to maintain the current DeclContext as the
16618 // lexical context,
16619 SearchDC
= getTagInjectionContext(SearchDC
);
16621 // Find the scope where we'll be declaring the tag.
16622 S
= getTagInjectionScope(S
, getLangOpts());
16624 assert(TUK
== TUK_Friend
);
16625 // C++ [namespace.memdef]p3:
16626 // If a friend declaration in a non-local class first declares a
16627 // class or function, the friend class or function is a member of
16628 // the innermost enclosing namespace.
16629 SearchDC
= SearchDC
->getEnclosingNamespaceContext();
16632 // In C++, we need to do a redeclaration lookup to properly
16633 // diagnose some problems.
16634 // FIXME: redeclaration lookup is also used (with and without C++) to find a
16635 // hidden declaration so that we don't get ambiguity errors when using a
16636 // type declared by an elaborated-type-specifier. In C that is not correct
16637 // and we should instead merge compatible types found by lookup.
16638 if (getLangOpts().CPlusPlus
) {
16639 // FIXME: This can perform qualified lookups into function contexts,
16640 // which are meaningless.
16641 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
16642 LookupQualifiedName(Previous
, SearchDC
);
16644 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
16645 LookupName(Previous
, S
);
16649 // If we have a known previous declaration to use, then use it.
16650 if (Previous
.empty() && SkipBody
&& SkipBody
->Previous
)
16651 Previous
.addDecl(SkipBody
->Previous
);
16653 if (!Previous
.empty()) {
16654 NamedDecl
*PrevDecl
= Previous
.getFoundDecl();
16655 NamedDecl
*DirectPrevDecl
= Previous
.getRepresentativeDecl();
16657 // It's okay to have a tag decl in the same scope as a typedef
16658 // which hides a tag decl in the same scope. Finding this
16659 // with a redeclaration lookup can only actually happen in C++.
16661 // This is also okay for elaborated-type-specifiers, which is
16662 // technically forbidden by the current standard but which is
16663 // okay according to the likely resolution of an open issue;
16664 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16665 if (getLangOpts().CPlusPlus
) {
16666 if (TypedefNameDecl
*TD
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
16667 if (const TagType
*TT
= TD
->getUnderlyingType()->getAs
<TagType
>()) {
16668 TagDecl
*Tag
= TT
->getDecl();
16669 if (Tag
->getDeclName() == Name
&&
16670 Tag
->getDeclContext()->getRedeclContext()
16671 ->Equals(TD
->getDeclContext()->getRedeclContext())) {
16674 Previous
.addDecl(Tag
);
16675 Previous
.resolveKind();
16681 // If this is a redeclaration of a using shadow declaration, it must
16682 // declare a tag in the same context. In MSVC mode, we allow a
16683 // redefinition if either context is within the other.
16684 if (auto *Shadow
= dyn_cast
<UsingShadowDecl
>(DirectPrevDecl
)) {
16685 auto *OldTag
= dyn_cast
<TagDecl
>(PrevDecl
);
16686 if (SS
.isEmpty() && TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
16687 isDeclInScope(Shadow
, SearchDC
, S
, isMemberSpecialization
) &&
16688 !(OldTag
&& isAcceptableTagRedeclContext(
16689 *this, OldTag
->getDeclContext(), SearchDC
))) {
16690 Diag(KWLoc
, diag::err_using_decl_conflict_reverse
);
16691 Diag(Shadow
->getTargetDecl()->getLocation(),
16692 diag::note_using_decl_target
);
16693 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
16695 // Recover by ignoring the old declaration.
16697 goto CreateNewDecl
;
16701 if (TagDecl
*PrevTagDecl
= dyn_cast
<TagDecl
>(PrevDecl
)) {
16702 // If this is a use of a previous tag, or if the tag is already declared
16703 // in the same scope (so that the definition/declaration completes or
16704 // rementions the tag), reuse the decl.
16705 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
||
16706 isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
16707 SS
.isNotEmpty() || isMemberSpecialization
)) {
16708 // Make sure that this wasn't declared as an enum and now used as a
16709 // struct or something similar.
16710 if (!isAcceptableTagRedeclaration(PrevTagDecl
, Kind
,
16711 TUK
== TUK_Definition
, KWLoc
,
16713 bool SafeToContinue
16714 = (PrevTagDecl
->getTagKind() != TTK_Enum
&&
16716 if (SafeToContinue
)
16717 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
16719 << FixItHint::CreateReplacement(SourceRange(KWLoc
),
16720 PrevTagDecl
->getKindName());
16722 Diag(KWLoc
, diag::err_use_with_wrong_tag
) << Name
;
16723 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
16725 if (SafeToContinue
)
16726 Kind
= PrevTagDecl
->getTagKind();
16728 // Recover by making this an anonymous redefinition.
16735 if (Kind
== TTK_Enum
&& PrevTagDecl
->getTagKind() == TTK_Enum
) {
16736 const EnumDecl
*PrevEnum
= cast
<EnumDecl
>(PrevTagDecl
);
16737 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)
16738 return PrevTagDecl
;
16740 QualType EnumUnderlyingTy
;
16741 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
16742 EnumUnderlyingTy
= TI
->getType().getUnqualifiedType();
16743 else if (const Type
*T
= EnumUnderlying
.dyn_cast
<const Type
*>())
16744 EnumUnderlyingTy
= QualType(T
, 0);
16746 // All conflicts with previous declarations are recovered by
16747 // returning the previous declaration, unless this is a definition,
16748 // in which case we want the caller to bail out.
16749 if (CheckEnumRedeclaration(NameLoc
.isValid() ? NameLoc
: KWLoc
,
16750 ScopedEnum
, EnumUnderlyingTy
,
16751 IsFixed
, PrevEnum
))
16752 return TUK
== TUK_Declaration
? PrevTagDecl
: nullptr;
16755 // C++11 [class.mem]p1:
16756 // A member shall not be declared twice in the member-specification,
16757 // except that a nested class or member class template can be declared
16758 // and then later defined.
16759 if (TUK
== TUK_Declaration
&& PrevDecl
->isCXXClassMember() &&
16760 S
->isDeclScope(PrevDecl
)) {
16761 Diag(NameLoc
, diag::ext_member_redeclared
);
16762 Diag(PrevTagDecl
->getLocation(), diag::note_previous_declaration
);
16766 // If this is a use, just return the declaration we found, unless
16767 // we have attributes.
16768 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
16769 if (!Attrs
.empty()) {
16770 // FIXME: Diagnose these attributes. For now, we create a new
16771 // declaration to hold them.
16772 } else if (TUK
== TUK_Reference
&&
16773 (PrevTagDecl
->getFriendObjectKind() ==
16774 Decl::FOK_Undeclared
||
16775 PrevDecl
->getOwningModule() != getCurrentModule()) &&
16777 // This declaration is a reference to an existing entity, but
16778 // has different visibility from that entity: it either makes
16779 // a friend visible or it makes a type visible in a new module.
16780 // In either case, create a new declaration. We only do this if
16781 // the declaration would have meant the same thing if no prior
16782 // declaration were found, that is, if it was found in the same
16783 // scope where we would have injected a declaration.
16784 if (!getTagInjectionContext(CurContext
)->getRedeclContext()
16785 ->Equals(PrevDecl
->getDeclContext()->getRedeclContext()))
16786 return PrevTagDecl
;
16787 // This is in the injected scope, create a new declaration in
16789 S
= getTagInjectionScope(S
, getLangOpts());
16791 return PrevTagDecl
;
16795 // Diagnose attempts to redefine a tag.
16796 if (TUK
== TUK_Definition
) {
16797 if (NamedDecl
*Def
= PrevTagDecl
->getDefinition()) {
16798 // If we're defining a specialization and the previous definition
16799 // is from an implicit instantiation, don't emit an error
16800 // here; we'll catch this in the general case below.
16801 bool IsExplicitSpecializationAfterInstantiation
= false;
16802 if (isMemberSpecialization
) {
16803 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Def
))
16804 IsExplicitSpecializationAfterInstantiation
=
16805 RD
->getTemplateSpecializationKind() !=
16806 TSK_ExplicitSpecialization
;
16807 else if (EnumDecl
*ED
= dyn_cast
<EnumDecl
>(Def
))
16808 IsExplicitSpecializationAfterInstantiation
=
16809 ED
->getTemplateSpecializationKind() !=
16810 TSK_ExplicitSpecialization
;
16813 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16814 // not keep more that one definition around (merge them). However,
16815 // ensure the decl passes the structural compatibility check in
16816 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16817 NamedDecl
*Hidden
= nullptr;
16818 if (SkipBody
&& !hasVisibleDefinition(Def
, &Hidden
)) {
16819 // There is a definition of this tag, but it is not visible. We
16820 // explicitly make use of C++'s one definition rule here, and
16821 // assume that this definition is identical to the hidden one
16822 // we already have. Make the existing definition visible and
16823 // use it in place of this one.
16824 if (!getLangOpts().CPlusPlus
) {
16825 // Postpone making the old definition visible until after we
16826 // complete parsing the new one and do the structural
16828 SkipBody
->CheckSameAsPrevious
= true;
16829 SkipBody
->New
= createTagFromNewDecl();
16830 SkipBody
->Previous
= Def
;
16833 SkipBody
->ShouldSkip
= true;
16834 SkipBody
->Previous
= Def
;
16835 makeMergedDefinitionVisible(Hidden
);
16836 // Carry on and handle it like a normal definition. We'll
16837 // skip starting the definitiion later.
16839 } else if (!IsExplicitSpecializationAfterInstantiation
) {
16840 // A redeclaration in function prototype scope in C isn't
16841 // visible elsewhere, so merely issue a warning.
16842 if (!getLangOpts().CPlusPlus
&& S
->containedInPrototypeScope())
16843 Diag(NameLoc
, diag::warn_redefinition_in_param_list
) << Name
;
16845 Diag(NameLoc
, diag::err_redefinition
) << Name
;
16846 notePreviousDefinition(Def
,
16847 NameLoc
.isValid() ? NameLoc
: KWLoc
);
16848 // If this is a redefinition, recover by making this
16849 // struct be anonymous, which will make any later
16850 // references get the previous definition.
16856 // If the type is currently being defined, complain
16857 // about a nested redefinition.
16858 auto *TD
= Context
.getTagDeclType(PrevTagDecl
)->getAsTagDecl();
16859 if (TD
->isBeingDefined()) {
16860 Diag(NameLoc
, diag::err_nested_redefinition
) << Name
;
16861 Diag(PrevTagDecl
->getLocation(),
16862 diag::note_previous_definition
);
16869 // Okay, this is definition of a previously declared or referenced
16870 // tag. We're going to create a new Decl for it.
16873 // Okay, we're going to make a redeclaration. If this is some kind
16874 // of reference, make sure we build the redeclaration in the same DC
16875 // as the original, and ignore the current access specifier.
16876 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
16877 SearchDC
= PrevTagDecl
->getDeclContext();
16881 // If we get here we have (another) forward declaration or we
16882 // have a definition. Just create a new decl.
16885 // If we get here, this is a definition of a new tag type in a nested
16886 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16887 // new decl/type. We set PrevDecl to NULL so that the entities
16888 // have distinct types.
16891 // If we get here, we're going to create a new Decl. If PrevDecl
16892 // is non-NULL, it's a definition of the tag declared by
16893 // PrevDecl. If it's NULL, we have a new definition.
16895 // Otherwise, PrevDecl is not a tag, but was found with tag
16896 // lookup. This is only actually possible in C++, where a few
16897 // things like templates still live in the tag namespace.
16899 // Use a better diagnostic if an elaborated-type-specifier
16900 // found the wrong kind of type on the first
16901 // (non-redeclaration) lookup.
16902 if ((TUK
== TUK_Reference
|| TUK
== TUK_Friend
) &&
16903 !Previous
.isForRedeclaration()) {
16904 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
16905 Diag(NameLoc
, diag::err_tag_reference_non_tag
) << PrevDecl
<< NTK
16907 Diag(PrevDecl
->getLocation(), diag::note_declared_at
);
16910 // Otherwise, only diagnose if the declaration is in scope.
16911 } else if (!isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
16912 SS
.isNotEmpty() || isMemberSpecialization
)) {
16915 // Diagnose implicit declarations introduced by elaborated types.
16916 } else if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
16917 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
16918 Diag(NameLoc
, diag::err_tag_reference_conflict
) << NTK
;
16919 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
16922 // Otherwise it's a declaration. Call out a particularly common
16924 } else if (TypedefNameDecl
*TND
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
16926 if (isa
<TypeAliasDecl
>(PrevDecl
)) Kind
= 1;
16927 Diag(NameLoc
, diag::err_tag_definition_of_typedef
)
16928 << Name
<< Kind
<< TND
->getUnderlyingType();
16929 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
16932 // Otherwise, diagnose.
16934 // The tag name clashes with something else in the target scope,
16935 // issue an error and recover by making this tag be anonymous.
16936 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
16937 notePreviousDefinition(PrevDecl
, NameLoc
);
16942 // The existing declaration isn't relevant to us; we're in a
16943 // new scope, so clear out the previous declaration.
16950 TagDecl
*PrevDecl
= nullptr;
16951 if (Previous
.isSingleResult())
16952 PrevDecl
= cast
<TagDecl
>(Previous
.getFoundDecl());
16954 // If there is an identifier, use the location of the identifier as the
16955 // location of the decl, otherwise use the location of the struct/union
16957 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
16959 // Otherwise, create a new declaration. If there is a previous
16960 // declaration of the same entity, the two will be linked via
16964 if (Kind
== TTK_Enum
) {
16965 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16966 // enum X { A, B, C } D; D should chain to X.
16967 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
,
16968 cast_or_null
<EnumDecl
>(PrevDecl
), ScopedEnum
,
16969 ScopedEnumUsesClassTag
, IsFixed
);
16971 if (isStdAlignValT
&& (!StdAlignValT
|| getStdAlignValT()->isImplicit()))
16972 StdAlignValT
= cast
<EnumDecl
>(New
);
16974 // If this is an undefined enum, warn.
16975 if (TUK
!= TUK_Definition
&& !Invalid
) {
16977 if (IsFixed
&& cast
<EnumDecl
>(New
)->isFixed()) {
16978 // C++0x: 7.2p2: opaque-enum-declaration.
16979 // Conflicts are diagnosed above. Do nothing.
16981 else if (PrevDecl
&& (Def
= cast
<EnumDecl
>(PrevDecl
)->getDefinition())) {
16982 Diag(Loc
, diag::ext_forward_ref_enum_def
)
16984 Diag(Def
->getLocation(), diag::note_previous_definition
);
16986 unsigned DiagID
= diag::ext_forward_ref_enum
;
16987 if (getLangOpts().MSVCCompat
)
16988 DiagID
= diag::ext_ms_forward_ref_enum
;
16989 else if (getLangOpts().CPlusPlus
)
16990 DiagID
= diag::err_forward_ref_enum
;
16995 if (EnumUnderlying
) {
16996 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
16997 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
16998 ED
->setIntegerTypeSourceInfo(TI
);
17000 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
17001 QualType EnumTy
= ED
->getIntegerType();
17002 ED
->setPromotionType(EnumTy
->isPromotableIntegerType()
17003 ? Context
.getPromotedIntegerType(EnumTy
)
17005 assert(ED
->isComplete() && "enum with type should be complete");
17008 // struct/union/class
17010 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17011 // struct X { int A; } D; D should chain to X.
17012 if (getLangOpts().CPlusPlus
) {
17013 // FIXME: Look for a way to use RecordDecl for simple structs.
17014 New
= CXXRecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17015 cast_or_null
<CXXRecordDecl
>(PrevDecl
));
17017 if (isStdBadAlloc
&& (!StdBadAlloc
|| getStdBadAlloc()->isImplicit()))
17018 StdBadAlloc
= cast
<CXXRecordDecl
>(New
);
17020 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17021 cast_or_null
<RecordDecl
>(PrevDecl
));
17024 // C++11 [dcl.type]p3:
17025 // A type-specifier-seq shall not define a class or enumeration [...].
17026 if (getLangOpts().CPlusPlus
&& (IsTypeSpecifier
|| IsTemplateParamOrArg
) &&
17027 TUK
== TUK_Definition
) {
17028 Diag(New
->getLocation(), diag::err_type_defined_in_type_specifier
)
17029 << Context
.getTagDeclType(New
);
17033 if (!Invalid
&& getLangOpts().CPlusPlus
&& TUK
== TUK_Definition
&&
17034 DC
->getDeclKind() == Decl::Enum
) {
17035 Diag(New
->getLocation(), diag::err_type_defined_in_enum
)
17036 << Context
.getTagDeclType(New
);
17040 // Maybe add qualifier info.
17041 if (SS
.isNotEmpty()) {
17043 // If this is either a declaration or a definition, check the
17044 // nested-name-specifier against the current context.
17045 if ((TUK
== TUK_Definition
|| TUK
== TUK_Declaration
) &&
17046 diagnoseQualifiedDeclaration(SS
, DC
, OrigName
, Loc
,
17047 isMemberSpecialization
))
17050 New
->setQualifierInfo(SS
.getWithLocInContext(Context
));
17051 if (TemplateParameterLists
.size() > 0) {
17052 New
->setTemplateParameterListsInfo(Context
, TemplateParameterLists
);
17059 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
17060 // Add alignment attributes if necessary; these attributes are checked when
17061 // the ASTContext lays out the structure.
17063 // It is important for implementing the correct semantics that this
17064 // happen here (in ActOnTag). The #pragma pack stack is
17065 // maintained as a result of parser callbacks which can occur at
17066 // many points during the parsing of a struct declaration (because
17067 // the #pragma tokens are effectively skipped over during the
17068 // parsing of the struct).
17069 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
17070 AddAlignmentAttributesForRecord(RD
);
17071 AddMsStructLayoutForRecord(RD
);
17075 if (ModulePrivateLoc
.isValid()) {
17076 if (isMemberSpecialization
)
17077 Diag(New
->getLocation(), diag::err_module_private_specialization
)
17079 << FixItHint::CreateRemoval(ModulePrivateLoc
);
17080 // __module_private__ does not apply to local classes. However, we only
17081 // diagnose this as an error when the declaration specifiers are
17082 // freestanding. Here, we just ignore the __module_private__.
17083 else if (!SearchDC
->isFunctionOrMethod())
17084 New
->setModulePrivate();
17087 // If this is a specialization of a member class (of a class template),
17088 // check the specialization.
17089 if (isMemberSpecialization
&& CheckMemberSpecialization(New
, Previous
))
17092 // If we're declaring or defining a tag in function prototype scope in C,
17093 // note that this type can only be used within the function and add it to
17094 // the list of decls to inject into the function definition scope.
17095 if ((Name
|| Kind
== TTK_Enum
) &&
17096 getNonFieldDeclScope(S
)->isFunctionPrototypeScope()) {
17097 if (getLangOpts().CPlusPlus
) {
17098 // C++ [dcl.fct]p6:
17099 // Types shall not be defined in return or parameter types.
17100 if (TUK
== TUK_Definition
&& !IsTypeSpecifier
) {
17101 Diag(Loc
, diag::err_type_defined_in_param_type
)
17105 } else if (!PrevDecl
) {
17106 Diag(Loc
, diag::warn_decl_in_param_list
) << Context
.getTagDeclType(New
);
17111 New
->setInvalidDecl();
17113 // Set the lexical context. If the tag has a C++ scope specifier, the
17114 // lexical context will be different from the semantic context.
17115 New
->setLexicalDeclContext(CurContext
);
17117 // Mark this as a friend decl if applicable.
17118 // In Microsoft mode, a friend declaration also acts as a forward
17119 // declaration so we always pass true to setObjectOfFriendDecl to make
17120 // the tag name visible.
17121 if (TUK
== TUK_Friend
)
17122 New
->setObjectOfFriendDecl(getLangOpts().MSVCCompat
);
17124 // Set the access specifier.
17125 if (!Invalid
&& SearchDC
->isRecord())
17126 SetMemberAccessSpecifier(New
, PrevDecl
, AS
);
17129 CheckRedeclarationInModule(New
, PrevDecl
);
17131 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
))
17132 New
->startDefinition();
17134 ProcessDeclAttributeList(S
, New
, Attrs
);
17135 AddPragmaAttributes(S
, New
);
17137 // If this has an identifier, add it to the scope stack.
17138 if (TUK
== TUK_Friend
) {
17139 // We might be replacing an existing declaration in the lookup tables;
17140 // if so, borrow its access specifier.
17142 New
->setAccess(PrevDecl
->getAccess());
17144 DeclContext
*DC
= New
->getDeclContext()->getRedeclContext();
17145 DC
->makeDeclVisibleInContext(New
);
17146 if (Name
) // can be null along some error paths
17147 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
17148 PushOnScopeChains(New
, EnclosingScope
, /* AddToContext = */ false);
17150 S
= getNonFieldDeclScope(S
);
17151 PushOnScopeChains(New
, S
, true);
17153 CurContext
->addDecl(New
);
17156 // If this is the C FILE type, notify the AST context.
17157 if (IdentifierInfo
*II
= New
->getIdentifier())
17158 if (!New
->isInvalidDecl() &&
17159 New
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17161 Context
.setFILEDecl(New
);
17164 mergeDeclAttributes(New
, PrevDecl
);
17166 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(New
))
17167 inferGslOwnerPointerAttribute(CXXRD
);
17169 // If there's a #pragma GCC visibility in scope, set the visibility of this
17171 AddPushedVisibilityAttribute(New
);
17173 if (isMemberSpecialization
&& !New
->isInvalidDecl())
17174 CompleteMemberSpecialization(New
, Previous
);
17177 // In C++, don't return an invalid declaration. We can't recover well from
17178 // the cases where we make the type anonymous.
17179 if (Invalid
&& getLangOpts().CPlusPlus
) {
17180 if (New
->isBeingDefined())
17181 if (auto RD
= dyn_cast
<RecordDecl
>(New
))
17182 RD
->completeDefinition();
17184 } else if (SkipBody
&& SkipBody
->ShouldSkip
) {
17185 return SkipBody
->Previous
;
17191 void Sema::ActOnTagStartDefinition(Scope
*S
, Decl
*TagD
) {
17192 AdjustDeclIfTemplate(TagD
);
17193 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17195 // Enter the tag context.
17196 PushDeclContext(S
, Tag
);
17198 ActOnDocumentableDecl(TagD
);
17200 // If there's a #pragma GCC visibility in scope, set the visibility of this
17202 AddPushedVisibilityAttribute(Tag
);
17205 bool Sema::ActOnDuplicateDefinition(Decl
*Prev
, SkipBodyInfo
&SkipBody
) {
17206 if (!hasStructuralCompatLayout(Prev
, SkipBody
.New
))
17209 // Make the previous decl visible.
17210 makeMergedDefinitionVisible(SkipBody
.Previous
);
17214 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl
*IDecl
) {
17215 assert(IDecl
->getLexicalParent() == CurContext
&&
17216 "The next DeclContext should be lexically contained in the current one.");
17217 CurContext
= IDecl
;
17220 void Sema::ActOnStartCXXMemberDeclarations(Scope
*S
, Decl
*TagD
,
17221 SourceLocation FinalLoc
,
17222 bool IsFinalSpelledSealed
,
17224 SourceLocation LBraceLoc
) {
17225 AdjustDeclIfTemplate(TagD
);
17226 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(TagD
);
17228 FieldCollector
->StartClass();
17230 if (!Record
->getIdentifier())
17234 Record
->markAbstract();
17236 if (FinalLoc
.isValid()) {
17237 Record
->addAttr(FinalAttr::Create(
17238 Context
, FinalLoc
, AttributeCommonInfo::AS_Keyword
,
17239 static_cast<FinalAttr::Spelling
>(IsFinalSpelledSealed
)));
17242 // [...] The class-name is also inserted into the scope of the
17243 // class itself; this is known as the injected-class-name. For
17244 // purposes of access checking, the injected-class-name is treated
17245 // as if it were a public member name.
17246 CXXRecordDecl
*InjectedClassName
= CXXRecordDecl::Create(
17247 Context
, Record
->getTagKind(), CurContext
, Record
->getBeginLoc(),
17248 Record
->getLocation(), Record
->getIdentifier(),
17249 /*PrevDecl=*/nullptr,
17250 /*DelayTypeCreation=*/true);
17251 Context
.getTypeDeclType(InjectedClassName
, Record
);
17252 InjectedClassName
->setImplicit();
17253 InjectedClassName
->setAccess(AS_public
);
17254 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate())
17255 InjectedClassName
->setDescribedClassTemplate(Template
);
17256 PushOnScopeChains(InjectedClassName
, S
);
17257 assert(InjectedClassName
->isInjectedClassName() &&
17258 "Broken injected-class-name");
17261 void Sema::ActOnTagFinishDefinition(Scope
*S
, Decl
*TagD
,
17262 SourceRange BraceRange
) {
17263 AdjustDeclIfTemplate(TagD
);
17264 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17265 Tag
->setBraceRange(BraceRange
);
17267 // Make sure we "complete" the definition even it is invalid.
17268 if (Tag
->isBeingDefined()) {
17269 assert(Tag
->isInvalidDecl() && "We should already have completed it");
17270 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
17271 RD
->completeDefinition();
17274 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
17275 FieldCollector
->FinishClass();
17276 if (RD
->hasAttr
<SYCLSpecialClassAttr
>()) {
17277 auto *Def
= RD
->getDefinition();
17278 assert(Def
&& "The record is expected to have a completed definition");
17279 unsigned NumInitMethods
= 0;
17280 for (auto *Method
: Def
->methods()) {
17281 if (!Method
->getIdentifier())
17283 if (Method
->getName() == "__init")
17286 if (NumInitMethods
> 1 || !Def
->hasInitMethod())
17287 Diag(RD
->getLocation(), diag::err_sycl_special_type_num_init_method
);
17291 // Exit this scope of this tag's definition.
17294 if (getCurLexicalContext()->isObjCContainer() &&
17295 Tag
->getDeclContext()->isFileContext())
17296 Tag
->setTopLevelDeclInObjCContainer();
17298 // Notify the consumer that we've defined a tag.
17299 if (!Tag
->isInvalidDecl())
17300 Consumer
.HandleTagDeclDefinition(Tag
);
17302 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17303 // from XLs and instead matches the XL #pragma pack(1) behavior.
17304 if (Context
.getTargetInfo().getTriple().isOSAIX() &&
17305 AlignPackStack
.hasValue()) {
17306 AlignPackInfo APInfo
= AlignPackStack
.CurrentValue
;
17307 // Only diagnose #pragma align(packed).
17308 if (!APInfo
.IsAlignAttr() || APInfo
.getAlignMode() != AlignPackInfo::Packed
)
17310 const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
);
17313 // Only warn if there is at least 1 bitfield member.
17314 if (llvm::any_of(RD
->fields(),
17315 [](const FieldDecl
*FD
) { return FD
->isBitField(); }))
17316 Diag(BraceRange
.getBegin(), diag::warn_pragma_align_not_xl_compatible
);
17320 void Sema::ActOnObjCContainerFinishDefinition() {
17321 // Exit this scope of this interface definition.
17325 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl
*ObjCCtx
) {
17326 assert(ObjCCtx
== CurContext
&& "Mismatch of container contexts");
17327 OriginalLexicalContext
= ObjCCtx
;
17328 ActOnObjCContainerFinishDefinition();
17331 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl
*ObjCCtx
) {
17332 ActOnObjCContainerStartDefinition(ObjCCtx
);
17333 OriginalLexicalContext
= nullptr;
17336 void Sema::ActOnTagDefinitionError(Scope
*S
, Decl
*TagD
) {
17337 AdjustDeclIfTemplate(TagD
);
17338 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17339 Tag
->setInvalidDecl();
17341 // Make sure we "complete" the definition even it is invalid.
17342 if (Tag
->isBeingDefined()) {
17343 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
17344 RD
->completeDefinition();
17347 // We're undoing ActOnTagStartDefinition here, not
17348 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17349 // the FieldCollector.
17354 // Note that FieldName may be null for anonymous bitfields.
17355 ExprResult
Sema::VerifyBitField(SourceLocation FieldLoc
,
17356 IdentifierInfo
*FieldName
, QualType FieldTy
,
17357 bool IsMsStruct
, Expr
*BitWidth
) {
17359 if (BitWidth
->containsErrors())
17360 return ExprError();
17362 // C99 6.7.2.1p4 - verify the field type.
17363 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17364 if (!FieldTy
->isDependentType() && !FieldTy
->isIntegralOrEnumerationType()) {
17365 // Handle incomplete and sizeless types with a specific error.
17366 if (RequireCompleteSizedType(FieldLoc
, FieldTy
,
17367 diag::err_field_incomplete_or_sizeless
))
17368 return ExprError();
17370 return Diag(FieldLoc
, diag::err_not_integral_type_bitfield
)
17371 << FieldName
<< FieldTy
<< BitWidth
->getSourceRange();
17372 return Diag(FieldLoc
, diag::err_not_integral_type_anon_bitfield
)
17373 << FieldTy
<< BitWidth
->getSourceRange();
17374 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr
*>(BitWidth
),
17375 UPPC_BitFieldWidth
))
17376 return ExprError();
17378 // If the bit-width is type- or value-dependent, don't try to check
17380 if (BitWidth
->isValueDependent() || BitWidth
->isTypeDependent())
17383 llvm::APSInt Value
;
17384 ExprResult ICE
= VerifyIntegerConstantExpression(BitWidth
, &Value
, AllowFold
);
17385 if (ICE
.isInvalid())
17387 BitWidth
= ICE
.get();
17389 // Zero-width bitfield is ok for anonymous field.
17390 if (Value
== 0 && FieldName
)
17391 return Diag(FieldLoc
, diag::err_bitfield_has_zero_width
) << FieldName
;
17393 if (Value
.isSigned() && Value
.isNegative()) {
17395 return Diag(FieldLoc
, diag::err_bitfield_has_negative_width
)
17396 << FieldName
<< toString(Value
, 10);
17397 return Diag(FieldLoc
, diag::err_anon_bitfield_has_negative_width
)
17398 << toString(Value
, 10);
17401 // The size of the bit-field must not exceed our maximum permitted object
17403 if (Value
.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context
)) {
17404 return Diag(FieldLoc
, diag::err_bitfield_too_wide
)
17405 << !FieldName
<< FieldName
<< toString(Value
, 10);
17408 if (!FieldTy
->isDependentType()) {
17409 uint64_t TypeStorageSize
= Context
.getTypeSize(FieldTy
);
17410 uint64_t TypeWidth
= Context
.getIntWidth(FieldTy
);
17411 bool BitfieldIsOverwide
= Value
.ugt(TypeWidth
);
17413 // Over-wide bitfields are an error in C or when using the MSVC bitfield
17415 bool CStdConstraintViolation
=
17416 BitfieldIsOverwide
&& !getLangOpts().CPlusPlus
;
17417 bool MSBitfieldViolation
=
17418 Value
.ugt(TypeStorageSize
) &&
17419 (IsMsStruct
|| Context
.getTargetInfo().getCXXABI().isMicrosoft());
17420 if (CStdConstraintViolation
|| MSBitfieldViolation
) {
17421 unsigned DiagWidth
=
17422 CStdConstraintViolation
? TypeWidth
: TypeStorageSize
;
17423 return Diag(FieldLoc
, diag::err_bitfield_width_exceeds_type_width
)
17424 << (bool)FieldName
<< FieldName
<< toString(Value
, 10)
17425 << !CStdConstraintViolation
<< DiagWidth
;
17428 // Warn on types where the user might conceivably expect to get all
17429 // specified bits as value bits: that's all integral types other than
17431 if (BitfieldIsOverwide
&& !FieldTy
->isBooleanType() && FieldName
) {
17432 Diag(FieldLoc
, diag::warn_bitfield_width_exceeds_type_width
)
17433 << FieldName
<< toString(Value
, 10)
17434 << (unsigned)TypeWidth
;
17441 /// ActOnField - Each field of a C struct/union is passed into this in order
17442 /// to create a FieldDecl object for it.
17443 Decl
*Sema::ActOnField(Scope
*S
, Decl
*TagD
, SourceLocation DeclStart
,
17444 Declarator
&D
, Expr
*BitfieldWidth
) {
17445 FieldDecl
*Res
= HandleField(S
, cast_or_null
<RecordDecl
>(TagD
),
17446 DeclStart
, D
, static_cast<Expr
*>(BitfieldWidth
),
17447 /*InitStyle=*/ICIS_NoInit
, AS_public
);
17451 /// HandleField - Analyze a field of a C struct or a C++ data member.
17453 FieldDecl
*Sema::HandleField(Scope
*S
, RecordDecl
*Record
,
17454 SourceLocation DeclStart
,
17455 Declarator
&D
, Expr
*BitWidth
,
17456 InClassInitStyle InitStyle
,
17457 AccessSpecifier AS
) {
17458 if (D
.isDecompositionDeclarator()) {
17459 const DecompositionDeclarator
&Decomp
= D
.getDecompositionDeclarator();
17460 Diag(Decomp
.getLSquareLoc(), diag::err_decomp_decl_context
)
17461 << Decomp
.getSourceRange();
17465 IdentifierInfo
*II
= D
.getIdentifier();
17466 SourceLocation Loc
= DeclStart
;
17467 if (II
) Loc
= D
.getIdentifierLoc();
17469 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17470 QualType T
= TInfo
->getType();
17471 if (getLangOpts().CPlusPlus
) {
17472 CheckExtraCXXDefaultArguments(D
);
17474 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
17475 UPPC_DataMemberType
)) {
17476 D
.setInvalidType();
17478 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
17482 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
17484 if (D
.getDeclSpec().isInlineSpecified())
17485 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
17486 << getLangOpts().CPlusPlus17
;
17487 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
17488 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
17489 diag::err_invalid_thread
)
17490 << DeclSpec::getSpecifierName(TSCS
);
17492 // Check to see if this name was declared as a member previously
17493 NamedDecl
*PrevDecl
= nullptr;
17494 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
,
17495 ForVisibleRedeclaration
);
17496 LookupName(Previous
, S
);
17497 switch (Previous
.getResultKind()) {
17498 case LookupResult::Found
:
17499 case LookupResult::FoundUnresolvedValue
:
17500 PrevDecl
= Previous
.getAsSingle
<NamedDecl
>();
17503 case LookupResult::FoundOverloaded
:
17504 PrevDecl
= Previous
.getRepresentativeDecl();
17507 case LookupResult::NotFound
:
17508 case LookupResult::NotFoundInCurrentInstantiation
:
17509 case LookupResult::Ambiguous
:
17512 Previous
.suppressDiagnostics();
17514 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
17515 // Maybe we will complain about the shadowed template parameter.
17516 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
17517 // Just pretend that we didn't see the previous declaration.
17518 PrevDecl
= nullptr;
17521 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
17522 PrevDecl
= nullptr;
17525 = (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable
);
17526 SourceLocation TSSL
= D
.getBeginLoc();
17528 = CheckFieldDecl(II
, T
, TInfo
, Record
, Loc
, Mutable
, BitWidth
, InitStyle
,
17529 TSSL
, AS
, PrevDecl
, &D
);
17531 if (NewFD
->isInvalidDecl())
17532 Record
->setInvalidDecl();
17534 if (D
.getDeclSpec().isModulePrivateSpecified())
17535 NewFD
->setModulePrivate();
17537 if (NewFD
->isInvalidDecl() && PrevDecl
) {
17538 // Don't introduce NewFD into scope; there's already something
17539 // with the same name in the same scope.
17541 PushOnScopeChains(NewFD
, S
);
17543 Record
->addDecl(NewFD
);
17548 /// Build a new FieldDecl and check its well-formedness.
17550 /// This routine builds a new FieldDecl given the fields name, type,
17551 /// record, etc. \p PrevDecl should refer to any previous declaration
17552 /// with the same name and in the same scope as the field to be
17555 /// \returns a new FieldDecl.
17557 /// \todo The Declarator argument is a hack. It will be removed once
17558 FieldDecl
*Sema::CheckFieldDecl(DeclarationName Name
, QualType T
,
17559 TypeSourceInfo
*TInfo
,
17560 RecordDecl
*Record
, SourceLocation Loc
,
17561 bool Mutable
, Expr
*BitWidth
,
17562 InClassInitStyle InitStyle
,
17563 SourceLocation TSSL
,
17564 AccessSpecifier AS
, NamedDecl
*PrevDecl
,
17566 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
17567 bool InvalidDecl
= false;
17568 if (D
) InvalidDecl
= D
->isInvalidType();
17570 // If we receive a broken type, recover by assuming 'int' and
17571 // marking this declaration as invalid.
17572 if (T
.isNull() || T
->containsErrors()) {
17573 InvalidDecl
= true;
17577 QualType EltTy
= Context
.getBaseElementType(T
);
17578 if (!EltTy
->isDependentType() && !EltTy
->containsErrors()) {
17579 if (RequireCompleteSizedType(Loc
, EltTy
,
17580 diag::err_field_incomplete_or_sizeless
)) {
17581 // Fields of incomplete type force their record to be invalid.
17582 Record
->setInvalidDecl();
17583 InvalidDecl
= true;
17586 EltTy
->isIncompleteType(&Def
);
17587 if (Def
&& Def
->isInvalidDecl()) {
17588 Record
->setInvalidDecl();
17589 InvalidDecl
= true;
17594 // TR 18037 does not allow fields to be declared with address space
17595 if (T
.hasAddressSpace() || T
->isDependentAddressSpaceType() ||
17596 T
->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17597 Diag(Loc
, diag::err_field_with_address_space
);
17598 Record
->setInvalidDecl();
17599 InvalidDecl
= true;
17602 if (LangOpts
.OpenCL
) {
17603 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17604 // used as structure or union field: image, sampler, event or block types.
17605 if (T
->isEventT() || T
->isImageType() || T
->isSamplerT() ||
17606 T
->isBlockPointerType()) {
17607 Diag(Loc
, diag::err_opencl_type_struct_or_union_field
) << T
;
17608 Record
->setInvalidDecl();
17609 InvalidDecl
= true;
17611 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17613 if (BitWidth
&& !getOpenCLOptions().isAvailableOption(
17614 "__cl_clang_bitfields", LangOpts
)) {
17615 Diag(Loc
, diag::err_opencl_bitfields
);
17616 InvalidDecl
= true;
17620 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17621 if (!InvalidDecl
&& getLangOpts().CPlusPlus
&& !II
&& BitWidth
&&
17622 T
.hasQualifiers()) {
17623 InvalidDecl
= true;
17624 Diag(Loc
, diag::err_anon_bitfield_qualifiers
);
17627 // C99 6.7.2.1p8: A member of a structure or union may have any type other
17628 // than a variably modified type.
17629 if (!InvalidDecl
&& T
->isVariablyModifiedType()) {
17630 if (!tryToFixVariablyModifiedVarType(
17631 TInfo
, T
, Loc
, diag::err_typecheck_field_variable_size
))
17632 InvalidDecl
= true;
17635 // Fields can not have abstract class types
17636 if (!InvalidDecl
&& RequireNonAbstractType(Loc
, T
,
17637 diag::err_abstract_type_in_decl
,
17638 AbstractFieldType
))
17639 InvalidDecl
= true;
17642 BitWidth
= nullptr;
17643 // If this is declared as a bit-field, check the bit-field.
17646 VerifyBitField(Loc
, II
, T
, Record
->isMsStruct(Context
), BitWidth
).get();
17648 InvalidDecl
= true;
17649 BitWidth
= nullptr;
17653 // Check that 'mutable' is consistent with the type of the declaration.
17654 if (!InvalidDecl
&& Mutable
) {
17655 unsigned DiagID
= 0;
17656 if (T
->isReferenceType())
17657 DiagID
= getLangOpts().MSVCCompat
? diag::ext_mutable_reference
17658 : diag::err_mutable_reference
;
17659 else if (T
.isConstQualified())
17660 DiagID
= diag::err_mutable_const
;
17663 SourceLocation ErrLoc
= Loc
;
17664 if (D
&& D
->getDeclSpec().getStorageClassSpecLoc().isValid())
17665 ErrLoc
= D
->getDeclSpec().getStorageClassSpecLoc();
17666 Diag(ErrLoc
, DiagID
);
17667 if (DiagID
!= diag::ext_mutable_reference
) {
17669 InvalidDecl
= true;
17674 // C++11 [class.union]p8 (DR1460):
17675 // At most one variant member of a union may have a
17676 // brace-or-equal-initializer.
17677 if (InitStyle
!= ICIS_NoInit
)
17678 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Record
), Loc
);
17680 FieldDecl
*NewFD
= FieldDecl::Create(Context
, Record
, TSSL
, Loc
, II
, T
, TInfo
,
17681 BitWidth
, Mutable
, InitStyle
);
17683 NewFD
->setInvalidDecl();
17685 if (PrevDecl
&& !isa
<TagDecl
>(PrevDecl
)) {
17686 Diag(Loc
, diag::err_duplicate_member
) << II
;
17687 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
17688 NewFD
->setInvalidDecl();
17691 if (!InvalidDecl
&& getLangOpts().CPlusPlus
) {
17692 if (Record
->isUnion()) {
17693 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
17694 CXXRecordDecl
* RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
17695 if (RDecl
->getDefinition()) {
17696 // C++ [class.union]p1: An object of a class with a non-trivial
17697 // constructor, a non-trivial copy constructor, a non-trivial
17698 // destructor, or a non-trivial copy assignment operator
17699 // cannot be a member of a union, nor can an array of such
17701 if (CheckNontrivialField(NewFD
))
17702 NewFD
->setInvalidDecl();
17706 // C++ [class.union]p1: If a union contains a member of reference type,
17707 // the program is ill-formed, except when compiling with MSVC extensions
17709 if (EltTy
->isReferenceType()) {
17710 Diag(NewFD
->getLocation(), getLangOpts().MicrosoftExt
?
17711 diag::ext_union_member_of_reference_type
:
17712 diag::err_union_member_of_reference_type
)
17713 << NewFD
->getDeclName() << EltTy
;
17714 if (!getLangOpts().MicrosoftExt
)
17715 NewFD
->setInvalidDecl();
17720 // FIXME: We need to pass in the attributes given an AST
17721 // representation, not a parser representation.
17723 // FIXME: The current scope is almost... but not entirely... correct here.
17724 ProcessDeclAttributes(getCurScope(), NewFD
, *D
);
17726 if (NewFD
->hasAttrs())
17727 CheckAlignasUnderalignment(NewFD
);
17730 // In auto-retain/release, infer strong retension for fields of
17731 // retainable type.
17732 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewFD
))
17733 NewFD
->setInvalidDecl();
17735 if (T
.isObjCGCWeak())
17736 Diag(Loc
, diag::warn_attribute_weak_on_field
);
17738 // PPC MMA non-pointer types are not allowed as field types.
17739 if (Context
.getTargetInfo().getTriple().isPPC64() &&
17740 CheckPPCMMAType(T
, NewFD
->getLocation()))
17741 NewFD
->setInvalidDecl();
17743 NewFD
->setAccess(AS
);
17747 bool Sema::CheckNontrivialField(FieldDecl
*FD
) {
17749 assert(getLangOpts().CPlusPlus
&& "valid check only for C++");
17751 if (FD
->isInvalidDecl() || FD
->getType()->isDependentType())
17754 QualType EltTy
= Context
.getBaseElementType(FD
->getType());
17755 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
17756 CXXRecordDecl
*RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
17757 if (RDecl
->getDefinition()) {
17758 // We check for copy constructors before constructors
17759 // because otherwise we'll never get complaints about
17760 // copy constructors.
17762 CXXSpecialMember member
= CXXInvalid
;
17763 // We're required to check for any non-trivial constructors. Since the
17764 // implicit default constructor is suppressed if there are any
17765 // user-declared constructors, we just need to check that there is a
17766 // trivial default constructor and a trivial copy constructor. (We don't
17767 // worry about move constructors here, since this is a C++98 check.)
17768 if (RDecl
->hasNonTrivialCopyConstructor())
17769 member
= CXXCopyConstructor
;
17770 else if (!RDecl
->hasTrivialDefaultConstructor())
17771 member
= CXXDefaultConstructor
;
17772 else if (RDecl
->hasNonTrivialCopyAssignment())
17773 member
= CXXCopyAssignment
;
17774 else if (RDecl
->hasNonTrivialDestructor())
17775 member
= CXXDestructor
;
17777 if (member
!= CXXInvalid
) {
17778 if (!getLangOpts().CPlusPlus11
&&
17779 getLangOpts().ObjCAutoRefCount
&& RDecl
->hasObjectMember()) {
17780 // Objective-C++ ARC: it is an error to have a non-trivial field of
17781 // a union. However, system headers in Objective-C programs
17782 // occasionally have Objective-C lifetime objects within unions,
17783 // and rather than cause the program to fail, we make those
17784 // members unavailable.
17785 SourceLocation Loc
= FD
->getLocation();
17786 if (getSourceManager().isInSystemHeader(Loc
)) {
17787 if (!FD
->hasAttr
<UnavailableAttr
>())
17788 FD
->addAttr(UnavailableAttr::CreateImplicit(Context
, "",
17789 UnavailableAttr::IR_ARCFieldWithOwnership
, Loc
));
17794 Diag(FD
->getLocation(), getLangOpts().CPlusPlus11
?
17795 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
:
17796 diag::err_illegal_union_or_anon_struct_member
)
17797 << FD
->getParent()->isUnion() << FD
->getDeclName() << member
;
17798 DiagnoseNontrivial(RDecl
, member
);
17799 return !getLangOpts().CPlusPlus11
;
17807 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17808 /// AST enum value.
17809 static ObjCIvarDecl::AccessControl
17810 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility
) {
17811 switch (ivarVisibility
) {
17812 default: llvm_unreachable("Unknown visitibility kind");
17813 case tok::objc_private
: return ObjCIvarDecl::Private
;
17814 case tok::objc_public
: return ObjCIvarDecl::Public
;
17815 case tok::objc_protected
: return ObjCIvarDecl::Protected
;
17816 case tok::objc_package
: return ObjCIvarDecl::Package
;
17820 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17821 /// in order to create an IvarDecl object for it.
17822 Decl
*Sema::ActOnIvar(Scope
*S
,
17823 SourceLocation DeclStart
,
17824 Declarator
&D
, Expr
*BitfieldWidth
,
17825 tok::ObjCKeywordKind Visibility
) {
17827 IdentifierInfo
*II
= D
.getIdentifier();
17828 Expr
*BitWidth
= (Expr
*)BitfieldWidth
;
17829 SourceLocation Loc
= DeclStart
;
17830 if (II
) Loc
= D
.getIdentifierLoc();
17832 // FIXME: Unnamed fields can be handled in various different ways, for
17833 // example, unnamed unions inject all members into the struct namespace!
17835 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17836 QualType T
= TInfo
->getType();
17839 // 6.7.2.1p3, 6.7.2.1p4
17840 BitWidth
= VerifyBitField(Loc
, II
, T
, /*IsMsStruct*/false, BitWidth
).get();
17842 D
.setInvalidType();
17849 if (T
->isReferenceType()) {
17850 Diag(Loc
, diag::err_ivar_reference_type
);
17851 D
.setInvalidType();
17853 // C99 6.7.2.1p8: A member of a structure or union may have any type other
17854 // than a variably modified type.
17855 else if (T
->isVariablyModifiedType()) {
17856 if (!tryToFixVariablyModifiedVarType(
17857 TInfo
, T
, Loc
, diag::err_typecheck_ivar_variable_size
))
17858 D
.setInvalidType();
17861 // Get the visibility (access control) for this ivar.
17862 ObjCIvarDecl::AccessControl ac
=
17863 Visibility
!= tok::objc_not_keyword
? TranslateIvarVisibility(Visibility
)
17864 : ObjCIvarDecl::None
;
17865 // Must set ivar's DeclContext to its enclosing interface.
17866 ObjCContainerDecl
*EnclosingDecl
= cast
<ObjCContainerDecl
>(CurContext
);
17867 if (!EnclosingDecl
|| EnclosingDecl
->isInvalidDecl())
17869 ObjCContainerDecl
*EnclosingContext
;
17870 if (ObjCImplementationDecl
*IMPDecl
=
17871 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
17872 if (LangOpts
.ObjCRuntime
.isFragile()) {
17873 // Case of ivar declared in an implementation. Context is that of its class.
17874 EnclosingContext
= IMPDecl
->getClassInterface();
17875 assert(EnclosingContext
&& "Implementation has no class interface!");
17878 EnclosingContext
= EnclosingDecl
;
17880 if (ObjCCategoryDecl
*CDecl
=
17881 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
17882 if (LangOpts
.ObjCRuntime
.isFragile() || !CDecl
->IsClassExtension()) {
17883 Diag(Loc
, diag::err_misplaced_ivar
) << CDecl
->IsClassExtension();
17887 EnclosingContext
= EnclosingDecl
;
17890 // Construct the decl.
17891 ObjCIvarDecl
*NewID
= ObjCIvarDecl::Create(Context
, EnclosingContext
,
17892 DeclStart
, Loc
, II
, T
,
17893 TInfo
, ac
, (Expr
*)BitfieldWidth
);
17896 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, Loc
, LookupMemberName
,
17897 ForVisibleRedeclaration
);
17898 if (PrevDecl
&& isDeclInScope(PrevDecl
, EnclosingContext
, S
)
17899 && !isa
<TagDecl
>(PrevDecl
)) {
17900 Diag(Loc
, diag::err_duplicate_member
) << II
;
17901 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
17902 NewID
->setInvalidDecl();
17906 // Process attributes attached to the ivar.
17907 ProcessDeclAttributes(S
, NewID
, D
);
17909 if (D
.isInvalidType())
17910 NewID
->setInvalidDecl();
17912 // In ARC, infer 'retaining' for ivars of retainable type.
17913 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewID
))
17914 NewID
->setInvalidDecl();
17916 if (D
.getDeclSpec().isModulePrivateSpecified())
17917 NewID
->setModulePrivate();
17920 // FIXME: When interfaces are DeclContexts, we'll need to add
17921 // these to the interface.
17923 IdResolver
.AddDecl(NewID
);
17926 if (LangOpts
.ObjCRuntime
.isNonFragile() &&
17927 !NewID
->isInvalidDecl() && isa
<ObjCInterfaceDecl
>(EnclosingDecl
))
17928 Diag(Loc
, diag::warn_ivars_in_interface
);
17933 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17934 /// class and class extensions. For every class \@interface and class
17935 /// extension \@interface, if the last ivar is a bitfield of any type,
17936 /// then add an implicit `char :0` ivar to the end of that interface.
17937 void Sema::ActOnLastBitfield(SourceLocation DeclLoc
,
17938 SmallVectorImpl
<Decl
*> &AllIvarDecls
) {
17939 if (LangOpts
.ObjCRuntime
.isFragile() || AllIvarDecls
.empty())
17942 Decl
*ivarDecl
= AllIvarDecls
[AllIvarDecls
.size()-1];
17943 ObjCIvarDecl
*Ivar
= cast
<ObjCIvarDecl
>(ivarDecl
);
17945 if (!Ivar
->isBitField() || Ivar
->isZeroLengthBitField(Context
))
17947 ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(CurContext
);
17949 if (ObjCCategoryDecl
*CD
= dyn_cast
<ObjCCategoryDecl
>(CurContext
)) {
17950 if (!CD
->IsClassExtension())
17953 // No need to add this to end of @implementation.
17957 // All conditions are met. Add a new bitfield to the tail end of ivars.
17958 llvm::APInt
Zero(Context
.getTypeSize(Context
.IntTy
), 0);
17959 Expr
* BW
= IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
, DeclLoc
);
17961 Ivar
= ObjCIvarDecl::Create(Context
, cast
<ObjCContainerDecl
>(CurContext
),
17962 DeclLoc
, DeclLoc
, nullptr,
17964 Context
.getTrivialTypeSourceInfo(Context
.CharTy
,
17966 ObjCIvarDecl::Private
, BW
,
17968 AllIvarDecls
.push_back(Ivar
);
17971 /// [class.dtor]p4:
17972 /// At the end of the definition of a class, overload resolution is
17973 /// performed among the prospective destructors declared in that class with
17974 /// an empty argument list to select the destructor for the class, also
17975 /// known as the selected destructor.
17977 /// We do the overload resolution here, then mark the selected constructor in the AST.
17978 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17979 static void ComputeSelectedDestructor(Sema
&S
, CXXRecordDecl
*Record
) {
17980 if (!Record
->hasUserDeclaredDestructor()) {
17984 SourceLocation Loc
= Record
->getLocation();
17985 OverloadCandidateSet
OCS(Loc
, OverloadCandidateSet::CSK_Normal
);
17987 for (auto *Decl
: Record
->decls()) {
17988 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(Decl
)) {
17989 if (DD
->isInvalidDecl())
17991 S
.AddOverloadCandidate(DD
, DeclAccessPair::make(DD
, DD
->getAccess()), {},
17993 assert(DD
->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18000 OverloadCandidateSet::iterator Best
;
18002 OverloadCandidateDisplayKind DisplayKind
;
18004 switch (OCS
.BestViableFunction(S
, Loc
, Best
)) {
18007 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(Best
->Function
));
18011 Msg
= diag::err_ambiguous_destructor
;
18012 DisplayKind
= OCD_AmbiguousCandidates
;
18015 case OR_No_Viable_Function
:
18016 Msg
= diag::err_no_viable_destructor
;
18017 DisplayKind
= OCD_AllCandidates
;
18022 // OpenCL have got their own thing going with destructors. It's slightly broken,
18023 // but we allow it.
18024 if (!S
.LangOpts
.OpenCL
) {
18025 PartialDiagnostic Diag
= S
.PDiag(Msg
) << Record
;
18026 OCS
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
, DisplayKind
, {});
18027 Record
->setInvalidDecl();
18029 // It's a bit hacky: At this point we've raised an error but we want the
18030 // rest of the compiler to continue somehow working. However almost
18031 // everything we'll try to do with the class will depend on there being a
18032 // destructor. So let's pretend the first one is selected and hope for the
18034 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(OCS
.begin()->Function
));
18038 /// [class.mem.special]p5
18039 /// Two special member functions are of the same kind if:
18040 /// - they are both default constructors,
18041 /// - they are both copy or move constructors with the same first parameter
18043 /// - they are both copy or move assignment operators with the same first
18044 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18045 static bool AreSpecialMemberFunctionsSameKind(ASTContext
&Context
,
18048 Sema::CXXSpecialMember CSM
) {
18049 if (CSM
== Sema::CXXDefaultConstructor
)
18051 if (!Context
.hasSameType(M1
->getParamDecl(0)->getType(),
18052 M2
->getParamDecl(0)->getType()))
18054 if (!Context
.hasSameType(M1
->getThisType(), M2
->getThisType()))
18060 /// [class.mem.special]p6:
18061 /// An eligible special member function is a special member function for which:
18062 /// - the function is not deleted,
18063 /// - the associated constraints, if any, are satisfied, and
18064 /// - no special member function of the same kind whose associated constraints
18065 /// [CWG2595], if any, are satisfied is more constrained.
18066 static void SetEligibleMethods(Sema
&S
, CXXRecordDecl
*Record
,
18067 ArrayRef
<CXXMethodDecl
*> Methods
,
18068 Sema::CXXSpecialMember CSM
) {
18069 SmallVector
<bool, 4> SatisfactionStatus
;
18071 for (CXXMethodDecl
*Method
: Methods
) {
18072 const Expr
*Constraints
= Method
->getTrailingRequiresClause();
18074 SatisfactionStatus
.push_back(true);
18076 ConstraintSatisfaction Satisfaction
;
18077 if (S
.CheckFunctionConstraints(Method
, Satisfaction
))
18078 SatisfactionStatus
.push_back(false);
18080 SatisfactionStatus
.push_back(Satisfaction
.IsSatisfied
);
18084 for (size_t i
= 0; i
< Methods
.size(); i
++) {
18085 if (!SatisfactionStatus
[i
])
18087 CXXMethodDecl
*Method
= Methods
[i
];
18088 const Expr
*Constraints
= Method
->getTrailingRequiresClause();
18089 bool AnotherMethodIsMoreConstrained
= false;
18090 for (size_t j
= 0; j
< Methods
.size(); j
++) {
18091 if (i
== j
|| !SatisfactionStatus
[j
])
18093 CXXMethodDecl
*OtherMethod
= Methods
[j
];
18094 if (!AreSpecialMemberFunctionsSameKind(S
.Context
, Method
, OtherMethod
,
18098 const Expr
*OtherConstraints
= OtherMethod
->getTrailingRequiresClause();
18099 if (!OtherConstraints
)
18101 if (!Constraints
) {
18102 AnotherMethodIsMoreConstrained
= true;
18105 if (S
.IsAtLeastAsConstrained(OtherMethod
, {OtherConstraints
}, Method
,
18107 AnotherMethodIsMoreConstrained
)) {
18108 // There was an error with the constraints comparison. Exit the loop
18109 // and don't consider this function eligible.
18110 AnotherMethodIsMoreConstrained
= true;
18112 if (AnotherMethodIsMoreConstrained
)
18115 // FIXME: Do not consider deleted methods as eligible after implementing
18116 // DR1734 and DR1496.
18117 if (!AnotherMethodIsMoreConstrained
) {
18118 Method
->setIneligibleOrNotSelected(false);
18119 Record
->addedEligibleSpecialMemberFunction(Method
, 1 << CSM
);
18124 static void ComputeSpecialMemberFunctionsEligiblity(Sema
&S
,
18125 CXXRecordDecl
*Record
) {
18126 SmallVector
<CXXMethodDecl
*, 4> DefaultConstructors
;
18127 SmallVector
<CXXMethodDecl
*, 4> CopyConstructors
;
18128 SmallVector
<CXXMethodDecl
*, 4> MoveConstructors
;
18129 SmallVector
<CXXMethodDecl
*, 4> CopyAssignmentOperators
;
18130 SmallVector
<CXXMethodDecl
*, 4> MoveAssignmentOperators
;
18132 for (auto *Decl
: Record
->decls()) {
18133 auto *MD
= dyn_cast
<CXXMethodDecl
>(Decl
);
18135 auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(Decl
);
18137 MD
= dyn_cast
<CXXMethodDecl
>(FTD
->getTemplatedDecl());
18141 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
18142 if (CD
->isInvalidDecl())
18144 if (CD
->isDefaultConstructor())
18145 DefaultConstructors
.push_back(MD
);
18146 else if (CD
->isCopyConstructor())
18147 CopyConstructors
.push_back(MD
);
18148 else if (CD
->isMoveConstructor())
18149 MoveConstructors
.push_back(MD
);
18150 } else if (MD
->isCopyAssignmentOperator()) {
18151 CopyAssignmentOperators
.push_back(MD
);
18152 } else if (MD
->isMoveAssignmentOperator()) {
18153 MoveAssignmentOperators
.push_back(MD
);
18157 SetEligibleMethods(S
, Record
, DefaultConstructors
,
18158 Sema::CXXDefaultConstructor
);
18159 SetEligibleMethods(S
, Record
, CopyConstructors
, Sema::CXXCopyConstructor
);
18160 SetEligibleMethods(S
, Record
, MoveConstructors
, Sema::CXXMoveConstructor
);
18161 SetEligibleMethods(S
, Record
, CopyAssignmentOperators
,
18162 Sema::CXXCopyAssignment
);
18163 SetEligibleMethods(S
, Record
, MoveAssignmentOperators
,
18164 Sema::CXXMoveAssignment
);
18167 void Sema::ActOnFields(Scope
*S
, SourceLocation RecLoc
, Decl
*EnclosingDecl
,
18168 ArrayRef
<Decl
*> Fields
, SourceLocation LBrac
,
18169 SourceLocation RBrac
,
18170 const ParsedAttributesView
&Attrs
) {
18171 assert(EnclosingDecl
&& "missing record or interface decl");
18173 // If this is an Objective-C @implementation or category and we have
18174 // new fields here we should reset the layout of the interface since
18175 // it will now change.
18176 if (!Fields
.empty() && isa
<ObjCContainerDecl
>(EnclosingDecl
)) {
18177 ObjCContainerDecl
*DC
= cast
<ObjCContainerDecl
>(EnclosingDecl
);
18178 switch (DC
->getKind()) {
18180 case Decl::ObjCCategory
:
18181 Context
.ResetObjCLayout(cast
<ObjCCategoryDecl
>(DC
)->getClassInterface());
18183 case Decl::ObjCImplementation
:
18185 ResetObjCLayout(cast
<ObjCImplementationDecl
>(DC
)->getClassInterface());
18190 RecordDecl
*Record
= dyn_cast
<RecordDecl
>(EnclosingDecl
);
18191 CXXRecordDecl
*CXXRecord
= dyn_cast
<CXXRecordDecl
>(EnclosingDecl
);
18193 // Start counting up the number of named members; make sure to include
18194 // members of anonymous structs and unions in the total.
18195 unsigned NumNamedMembers
= 0;
18197 for (const auto *I
: Record
->decls()) {
18198 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
18199 if (IFD
->getDeclName())
18204 // Verify that all the fields are okay.
18205 SmallVector
<FieldDecl
*, 32> RecFields
;
18207 for (ArrayRef
<Decl
*>::iterator i
= Fields
.begin(), end
= Fields
.end();
18209 FieldDecl
*FD
= cast
<FieldDecl
>(*i
);
18211 // Get the type for the field.
18212 const Type
*FDTy
= FD
->getType().getTypePtr();
18214 if (!FD
->isAnonymousStructOrUnion()) {
18215 // Remember all fields written by the user.
18216 RecFields
.push_back(FD
);
18219 // If the field is already invalid for some reason, don't emit more
18220 // diagnostics about it.
18221 if (FD
->isInvalidDecl()) {
18222 EnclosingDecl
->setInvalidDecl();
18227 // A structure or union shall not contain a member with
18228 // incomplete or function type (hence, a structure shall not
18229 // contain an instance of itself, but may contain a pointer to
18230 // an instance of itself), except that the last member of a
18231 // structure with more than one named member may have incomplete
18232 // array type; such a structure (and any union containing,
18233 // possibly recursively, a member that is such a structure)
18234 // shall not be a member of a structure or an element of an
18236 bool IsLastField
= (i
+ 1 == Fields
.end());
18237 if (FDTy
->isFunctionType()) {
18238 // Field declared as a function.
18239 Diag(FD
->getLocation(), diag::err_field_declared_as_function
)
18240 << FD
->getDeclName();
18241 FD
->setInvalidDecl();
18242 EnclosingDecl
->setInvalidDecl();
18244 } else if (FDTy
->isIncompleteArrayType() &&
18245 (Record
|| isa
<ObjCContainerDecl
>(EnclosingDecl
))) {
18247 // Flexible array member.
18248 // Microsoft and g++ is more permissive regarding flexible array.
18249 // It will accept flexible array in union and also
18250 // as the sole element of a struct/class.
18251 unsigned DiagID
= 0;
18252 if (!Record
->isUnion() && !IsLastField
) {
18253 Diag(FD
->getLocation(), diag::err_flexible_array_not_at_end
)
18254 << FD
->getDeclName() << FD
->getType() << Record
->getTagKind();
18255 Diag((*(i
+ 1))->getLocation(), diag::note_next_field_declaration
);
18256 FD
->setInvalidDecl();
18257 EnclosingDecl
->setInvalidDecl();
18259 } else if (Record
->isUnion())
18260 DiagID
= getLangOpts().MicrosoftExt
18261 ? diag::ext_flexible_array_union_ms
18262 : getLangOpts().CPlusPlus
18263 ? diag::ext_flexible_array_union_gnu
18264 : diag::err_flexible_array_union
;
18265 else if (NumNamedMembers
< 1)
18266 DiagID
= getLangOpts().MicrosoftExt
18267 ? diag::ext_flexible_array_empty_aggregate_ms
18268 : getLangOpts().CPlusPlus
18269 ? diag::ext_flexible_array_empty_aggregate_gnu
18270 : diag::err_flexible_array_empty_aggregate
;
18273 Diag(FD
->getLocation(), DiagID
) << FD
->getDeclName()
18274 << Record
->getTagKind();
18275 // While the layout of types that contain virtual bases is not specified
18276 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18277 // virtual bases after the derived members. This would make a flexible
18278 // array member declared at the end of an object not adjacent to the end
18280 if (CXXRecord
&& CXXRecord
->getNumVBases() != 0)
18281 Diag(FD
->getLocation(), diag::err_flexible_array_virtual_base
)
18282 << FD
->getDeclName() << Record
->getTagKind();
18283 if (!getLangOpts().C99
)
18284 Diag(FD
->getLocation(), diag::ext_c99_flexible_array_member
)
18285 << FD
->getDeclName() << Record
->getTagKind();
18287 // If the element type has a non-trivial destructor, we would not
18288 // implicitly destroy the elements, so disallow it for now.
18290 // FIXME: GCC allows this. We should probably either implicitly delete
18291 // the destructor of the containing class, or just allow this.
18292 QualType BaseElem
= Context
.getBaseElementType(FD
->getType());
18293 if (!BaseElem
->isDependentType() && BaseElem
.isDestructedType()) {
18294 Diag(FD
->getLocation(), diag::err_flexible_array_has_nontrivial_dtor
)
18295 << FD
->getDeclName() << FD
->getType();
18296 FD
->setInvalidDecl();
18297 EnclosingDecl
->setInvalidDecl();
18300 // Okay, we have a legal flexible array member at the end of the struct.
18301 Record
->setHasFlexibleArrayMember(true);
18303 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18304 // unless they are followed by another ivar. That check is done
18305 // elsewhere, after synthesized ivars are known.
18307 } else if (!FDTy
->isDependentType() &&
18308 RequireCompleteSizedType(
18309 FD
->getLocation(), FD
->getType(),
18310 diag::err_field_incomplete_or_sizeless
)) {
18312 FD
->setInvalidDecl();
18313 EnclosingDecl
->setInvalidDecl();
18315 } else if (const RecordType
*FDTTy
= FDTy
->getAs
<RecordType
>()) {
18316 if (Record
&& FDTTy
->getDecl()->hasFlexibleArrayMember()) {
18317 // A type which contains a flexible array member is considered to be a
18318 // flexible array member.
18319 Record
->setHasFlexibleArrayMember(true);
18320 if (!Record
->isUnion()) {
18321 // If this is a struct/class and this is not the last element, reject
18322 // it. Note that GCC supports variable sized arrays in the middle of
18325 Diag(FD
->getLocation(), diag::ext_variable_sized_type_in_struct
)
18326 << FD
->getDeclName() << FD
->getType();
18328 // We support flexible arrays at the end of structs in
18329 // other structs as an extension.
18330 Diag(FD
->getLocation(), diag::ext_flexible_array_in_struct
)
18331 << FD
->getDeclName();
18335 if (isa
<ObjCContainerDecl
>(EnclosingDecl
) &&
18336 RequireNonAbstractType(FD
->getLocation(), FD
->getType(),
18337 diag::err_abstract_type_in_decl
,
18338 AbstractIvarType
)) {
18339 // Ivars can not have abstract class types
18340 FD
->setInvalidDecl();
18342 if (Record
&& FDTTy
->getDecl()->hasObjectMember())
18343 Record
->setHasObjectMember(true);
18344 if (Record
&& FDTTy
->getDecl()->hasVolatileMember())
18345 Record
->setHasVolatileMember(true);
18346 } else if (FDTy
->isObjCObjectType()) {
18347 /// A field cannot be an Objective-c object
18348 Diag(FD
->getLocation(), diag::err_statically_allocated_object
)
18349 << FixItHint::CreateInsertion(FD
->getLocation(), "*");
18350 QualType T
= Context
.getObjCObjectPointerType(FD
->getType());
18352 } else if (Record
&& Record
->isUnion() &&
18353 FD
->getType().hasNonTrivialObjCLifetime() &&
18354 getSourceManager().isInSystemHeader(FD
->getLocation()) &&
18355 !getLangOpts().CPlusPlus
&& !FD
->hasAttr
<UnavailableAttr
>() &&
18356 (FD
->getType().getObjCLifetime() != Qualifiers::OCL_Strong
||
18357 !Context
.hasDirectOwnershipQualifier(FD
->getType()))) {
18358 // For backward compatibility, fields of C unions declared in system
18359 // headers that have non-trivial ObjC ownership qualifications are marked
18360 // as unavailable unless the qualifier is explicit and __strong. This can
18361 // break ABI compatibility between programs compiled with ARC and MRR, but
18362 // is a better option than rejecting programs using those unions under
18364 FD
->addAttr(UnavailableAttr::CreateImplicit(
18365 Context
, "", UnavailableAttr::IR_ARCFieldWithOwnership
,
18366 FD
->getLocation()));
18367 } else if (getLangOpts().ObjC
&&
18368 getLangOpts().getGC() != LangOptions::NonGC
&& Record
&&
18369 !Record
->hasObjectMember()) {
18370 if (FD
->getType()->isObjCObjectPointerType() ||
18371 FD
->getType().isObjCGCStrong())
18372 Record
->setHasObjectMember(true);
18373 else if (Context
.getAsArrayType(FD
->getType())) {
18374 QualType BaseType
= Context
.getBaseElementType(FD
->getType());
18375 if (BaseType
->isRecordType() &&
18376 BaseType
->castAs
<RecordType
>()->getDecl()->hasObjectMember())
18377 Record
->setHasObjectMember(true);
18378 else if (BaseType
->isObjCObjectPointerType() ||
18379 BaseType
.isObjCGCStrong())
18380 Record
->setHasObjectMember(true);
18384 if (Record
&& !getLangOpts().CPlusPlus
&&
18385 !shouldIgnoreForRecordTriviality(FD
)) {
18386 QualType FT
= FD
->getType();
18387 if (FT
.isNonTrivialToPrimitiveDefaultInitialize()) {
18388 Record
->setNonTrivialToPrimitiveDefaultInitialize(true);
18389 if (FT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18391 Record
->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18393 QualType::PrimitiveCopyKind PCK
= FT
.isNonTrivialToPrimitiveCopy();
18394 if (PCK
!= QualType::PCK_Trivial
&& PCK
!= QualType::PCK_VolatileTrivial
) {
18395 Record
->setNonTrivialToPrimitiveCopy(true);
18396 if (FT
.hasNonTrivialToPrimitiveCopyCUnion() || Record
->isUnion())
18397 Record
->setHasNonTrivialToPrimitiveCopyCUnion(true);
18399 if (FT
.isDestructedType()) {
18400 Record
->setNonTrivialToPrimitiveDestroy(true);
18401 Record
->setParamDestroyedInCallee(true);
18402 if (FT
.hasNonTrivialToPrimitiveDestructCUnion() || Record
->isUnion())
18403 Record
->setHasNonTrivialToPrimitiveDestructCUnion(true);
18406 if (const auto *RT
= FT
->getAs
<RecordType
>()) {
18407 if (RT
->getDecl()->getArgPassingRestrictions() ==
18408 RecordDecl::APK_CanNeverPassInRegs
)
18409 Record
->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs
);
18410 } else if (FT
.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak
)
18411 Record
->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs
);
18414 if (Record
&& FD
->getType().isVolatileQualified())
18415 Record
->setHasVolatileMember(true);
18416 // Keep track of the number of named members.
18417 if (FD
->getIdentifier())
18421 // Okay, we successfully defined 'Record'.
18423 bool Completed
= false;
18425 if (!CXXRecord
->isInvalidDecl()) {
18426 // Set access bits correctly on the directly-declared conversions.
18427 for (CXXRecordDecl::conversion_iterator
18428 I
= CXXRecord
->conversion_begin(),
18429 E
= CXXRecord
->conversion_end(); I
!= E
; ++I
)
18430 I
.setAccess((*I
)->getAccess());
18433 // Add any implicitly-declared members to this class.
18434 AddImplicitlyDeclaredMembersToClass(CXXRecord
);
18436 if (!CXXRecord
->isDependentType()) {
18437 if (!CXXRecord
->isInvalidDecl()) {
18438 // If we have virtual base classes, we may end up finding multiple
18439 // final overriders for a given virtual function. Check for this
18441 if (CXXRecord
->getNumVBases()) {
18442 CXXFinalOverriderMap FinalOverriders
;
18443 CXXRecord
->getFinalOverriders(FinalOverriders
);
18445 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
18446 MEnd
= FinalOverriders
.end();
18448 for (OverridingMethods::iterator SO
= M
->second
.begin(),
18449 SOEnd
= M
->second
.end();
18450 SO
!= SOEnd
; ++SO
) {
18451 assert(SO
->second
.size() > 0 &&
18452 "Virtual function without overriding functions?");
18453 if (SO
->second
.size() == 1)
18456 // C++ [class.virtual]p2:
18457 // In a derived class, if a virtual member function of a base
18458 // class subobject has more than one final overrider the
18459 // program is ill-formed.
18460 Diag(Record
->getLocation(), diag::err_multiple_final_overriders
)
18461 << (const NamedDecl
*)M
->first
<< Record
;
18462 Diag(M
->first
->getLocation(),
18463 diag::note_overridden_virtual_function
);
18464 for (OverridingMethods::overriding_iterator
18465 OM
= SO
->second
.begin(),
18466 OMEnd
= SO
->second
.end();
18468 Diag(OM
->Method
->getLocation(), diag::note_final_overrider
)
18469 << (const NamedDecl
*)M
->first
<< OM
->Method
->getParent();
18471 Record
->setInvalidDecl();
18474 CXXRecord
->completeDefinition(&FinalOverriders
);
18478 ComputeSelectedDestructor(*this, CXXRecord
);
18479 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord
);
18484 Record
->completeDefinition();
18486 // Handle attributes before checking the layout.
18487 ProcessDeclAttributeList(S
, Record
, Attrs
);
18489 // Check to see if a FieldDecl is a pointer to a function.
18490 auto IsFunctionPointer
= [&](const Decl
*D
) {
18491 const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
18494 QualType FieldType
= FD
->getType().getDesugaredType(Context
);
18495 if (isa
<PointerType
>(FieldType
)) {
18496 QualType PointeeType
= cast
<PointerType
>(FieldType
)->getPointeeType();
18497 return PointeeType
.getDesugaredType(Context
)->isFunctionType();
18502 // Maybe randomize the record's decls. We automatically randomize a record
18503 // of function pointers, unless it has the "no_randomize_layout" attribute.
18504 if (!getLangOpts().CPlusPlus
&&
18505 (Record
->hasAttr
<RandomizeLayoutAttr
>() ||
18506 (!Record
->hasAttr
<NoRandomizeLayoutAttr
>() &&
18507 llvm::all_of(Record
->decls(), IsFunctionPointer
))) &&
18508 !Record
->isUnion() && !getLangOpts().RandstructSeed
.empty() &&
18509 !Record
->isRandomized()) {
18510 SmallVector
<Decl
*, 32> NewDeclOrdering
;
18511 if (randstruct::randomizeStructureLayout(Context
, Record
,
18513 Record
->reorderDecls(NewDeclOrdering
);
18516 // We may have deferred checking for a deleted destructor. Check now.
18518 auto *Dtor
= CXXRecord
->getDestructor();
18519 if (Dtor
&& Dtor
->isImplicit() &&
18520 ShouldDeleteSpecialMember(Dtor
, CXXDestructor
)) {
18521 CXXRecord
->setImplicitDestructorIsDeleted();
18522 SetDeclDeleted(Dtor
, CXXRecord
->getLocation());
18526 if (Record
->hasAttrs()) {
18527 CheckAlignasUnderalignment(Record
);
18529 if (const MSInheritanceAttr
*IA
= Record
->getAttr
<MSInheritanceAttr
>())
18530 checkMSInheritanceAttrOnDefinition(cast
<CXXRecordDecl
>(Record
),
18531 IA
->getRange(), IA
->getBestCase(),
18532 IA
->getInheritanceModel());
18535 // Check if the structure/union declaration is a type that can have zero
18536 // size in C. For C this is a language extension, for C++ it may cause
18537 // compatibility problems.
18538 bool CheckForZeroSize
;
18539 if (!getLangOpts().CPlusPlus
) {
18540 CheckForZeroSize
= true;
18542 // For C++ filter out types that cannot be referenced in C code.
18543 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
);
18545 CXXRecord
->getLexicalDeclContext()->isExternCContext() &&
18546 !CXXRecord
->isDependentType() && !inTemplateInstantiation() &&
18547 CXXRecord
->isCLike();
18549 if (CheckForZeroSize
) {
18550 bool ZeroSize
= true;
18551 bool IsEmpty
= true;
18552 unsigned NonBitFields
= 0;
18553 for (RecordDecl::field_iterator I
= Record
->field_begin(),
18554 E
= Record
->field_end();
18555 (NonBitFields
== 0 || ZeroSize
) && I
!= E
; ++I
) {
18557 if (I
->isUnnamedBitfield()) {
18558 if (!I
->isZeroLengthBitField(Context
))
18562 QualType FieldType
= I
->getType();
18563 if (FieldType
->isIncompleteType() ||
18564 !Context
.getTypeSizeInChars(FieldType
).isZero())
18569 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18570 // allowed in C++, but warn if its declaration is inside
18571 // extern "C" block.
18573 Diag(RecLoc
, getLangOpts().CPlusPlus
?
18574 diag::warn_zero_size_struct_union_in_extern_c
:
18575 diag::warn_zero_size_struct_union_compat
)
18576 << IsEmpty
<< Record
->isUnion() << (NonBitFields
> 1);
18579 // Structs without named members are extension in C (C99 6.7.2.1p7),
18580 // but are accepted by GCC.
18581 if (NonBitFields
== 0 && !getLangOpts().CPlusPlus
) {
18582 Diag(RecLoc
, IsEmpty
? diag::ext_empty_struct_union
:
18583 diag::ext_no_named_members_in_struct_union
)
18584 << Record
->isUnion();
18588 ObjCIvarDecl
**ClsFields
=
18589 reinterpret_cast<ObjCIvarDecl
**>(RecFields
.data());
18590 if (ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(EnclosingDecl
)) {
18591 ID
->setEndOfDefinitionLoc(RBrac
);
18592 // Add ivar's to class's DeclContext.
18593 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
18594 ClsFields
[i
]->setLexicalDeclContext(ID
);
18595 ID
->addDecl(ClsFields
[i
]);
18597 // Must enforce the rule that ivars in the base classes may not be
18599 if (ID
->getSuperClass())
18600 DiagnoseDuplicateIvars(ID
, ID
->getSuperClass());
18601 } else if (ObjCImplementationDecl
*IMPDecl
=
18602 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
18603 assert(IMPDecl
&& "ActOnFields - missing ObjCImplementationDecl");
18604 for (unsigned I
= 0, N
= RecFields
.size(); I
!= N
; ++I
)
18605 // Ivar declared in @implementation never belongs to the implementation.
18606 // Only it is in implementation's lexical context.
18607 ClsFields
[I
]->setLexicalDeclContext(IMPDecl
);
18608 CheckImplementationIvars(IMPDecl
, ClsFields
, RecFields
.size(), RBrac
);
18609 IMPDecl
->setIvarLBraceLoc(LBrac
);
18610 IMPDecl
->setIvarRBraceLoc(RBrac
);
18611 } else if (ObjCCategoryDecl
*CDecl
=
18612 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
18613 // case of ivars in class extension; all other cases have been
18614 // reported as errors elsewhere.
18615 // FIXME. Class extension does not have a LocEnd field.
18616 // CDecl->setLocEnd(RBrac);
18617 // Add ivar's to class extension's DeclContext.
18618 // Diagnose redeclaration of private ivars.
18619 ObjCInterfaceDecl
*IDecl
= CDecl
->getClassInterface();
18620 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
18622 if (const ObjCIvarDecl
*ClsIvar
=
18623 IDecl
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
18624 Diag(ClsFields
[i
]->getLocation(),
18625 diag::err_duplicate_ivar_declaration
);
18626 Diag(ClsIvar
->getLocation(), diag::note_previous_definition
);
18629 for (const auto *Ext
: IDecl
->known_extensions()) {
18630 if (const ObjCIvarDecl
*ClsExtIvar
18631 = Ext
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
18632 Diag(ClsFields
[i
]->getLocation(),
18633 diag::err_duplicate_ivar_declaration
);
18634 Diag(ClsExtIvar
->getLocation(), diag::note_previous_definition
);
18639 ClsFields
[i
]->setLexicalDeclContext(CDecl
);
18640 CDecl
->addDecl(ClsFields
[i
]);
18642 CDecl
->setIvarLBraceLoc(LBrac
);
18643 CDecl
->setIvarRBraceLoc(RBrac
);
18648 /// Determine whether the given integral value is representable within
18649 /// the given type T.
18650 static bool isRepresentableIntegerValue(ASTContext
&Context
,
18651 llvm::APSInt
&Value
,
18653 assert((T
->isIntegralType(Context
) || T
->isEnumeralType()) &&
18654 "Integral type required!");
18655 unsigned BitWidth
= Context
.getIntWidth(T
);
18657 if (Value
.isUnsigned() || Value
.isNonNegative()) {
18658 if (T
->isSignedIntegerOrEnumerationType())
18660 return Value
.getActiveBits() <= BitWidth
;
18662 return Value
.getMinSignedBits() <= BitWidth
;
18665 // Given an integral type, return the next larger integral type
18666 // (or a NULL type of no such type exists).
18667 static QualType
getNextLargerIntegralType(ASTContext
&Context
, QualType T
) {
18668 // FIXME: Int128/UInt128 support, which also needs to be introduced into
18669 // enum checking below.
18670 assert((T
->isIntegralType(Context
) ||
18671 T
->isEnumeralType()) && "Integral type required!");
18672 const unsigned NumTypes
= 4;
18673 QualType SignedIntegralTypes
[NumTypes
] = {
18674 Context
.ShortTy
, Context
.IntTy
, Context
.LongTy
, Context
.LongLongTy
18676 QualType UnsignedIntegralTypes
[NumTypes
] = {
18677 Context
.UnsignedShortTy
, Context
.UnsignedIntTy
, Context
.UnsignedLongTy
,
18678 Context
.UnsignedLongLongTy
18681 unsigned BitWidth
= Context
.getTypeSize(T
);
18682 QualType
*Types
= T
->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18683 : UnsignedIntegralTypes
;
18684 for (unsigned I
= 0; I
!= NumTypes
; ++I
)
18685 if (Context
.getTypeSize(Types
[I
]) > BitWidth
)
18691 EnumConstantDecl
*Sema::CheckEnumConstant(EnumDecl
*Enum
,
18692 EnumConstantDecl
*LastEnumConst
,
18693 SourceLocation IdLoc
,
18694 IdentifierInfo
*Id
,
18696 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
18697 llvm::APSInt
EnumVal(IntWidth
);
18700 if (Val
&& DiagnoseUnexpandedParameterPack(Val
, UPPC_EnumeratorValue
))
18704 Val
= DefaultLvalueConversion(Val
).get();
18707 if (Enum
->isDependentType() || Val
->isTypeDependent() ||
18708 Val
->containsErrors())
18709 EltTy
= Context
.DependentTy
;
18711 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18712 // underlying type, but do allow it in all other contexts.
18713 if (getLangOpts().CPlusPlus11
&& Enum
->isFixed()) {
18714 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18715 // constant-expression in the enumerator-definition shall be a converted
18716 // constant expression of the underlying type.
18717 EltTy
= Enum
->getIntegerType();
18718 ExprResult Converted
=
18719 CheckConvertedConstantExpression(Val
, EltTy
, EnumVal
,
18721 if (Converted
.isInvalid())
18724 Val
= Converted
.get();
18725 } else if (!Val
->isValueDependent() &&
18727 VerifyIntegerConstantExpression(Val
, &EnumVal
, AllowFold
)
18729 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18731 if (Enum
->isComplete()) {
18732 EltTy
= Enum
->getIntegerType();
18734 // In Obj-C and Microsoft mode, require the enumeration value to be
18735 // representable in the underlying type of the enumeration. In C++11,
18736 // we perform a non-narrowing conversion as part of converted constant
18737 // expression checking.
18738 if (!isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
18739 if (Context
.getTargetInfo()
18741 .isWindowsMSVCEnvironment()) {
18742 Diag(IdLoc
, diag::ext_enumerator_too_large
) << EltTy
;
18744 Diag(IdLoc
, diag::err_enumerator_too_large
) << EltTy
;
18748 // Cast to the underlying type.
18749 Val
= ImpCastExprToType(Val
, EltTy
,
18750 EltTy
->isBooleanType() ? CK_IntegralToBoolean
18753 } else if (getLangOpts().CPlusPlus
) {
18754 // C++11 [dcl.enum]p5:
18755 // If the underlying type is not fixed, the type of each enumerator
18756 // is the type of its initializing value:
18757 // - If an initializer is specified for an enumerator, the
18758 // initializing value has the same type as the expression.
18759 EltTy
= Val
->getType();
18762 // The expression that defines the value of an enumeration constant
18763 // shall be an integer constant expression that has a value
18764 // representable as an int.
18766 // Complain if the value is not representable in an int.
18767 if (!isRepresentableIntegerValue(Context
, EnumVal
, Context
.IntTy
))
18768 Diag(IdLoc
, diag::ext_enum_value_not_int
)
18769 << toString(EnumVal
, 10) << Val
->getSourceRange()
18770 << (EnumVal
.isUnsigned() || EnumVal
.isNonNegative());
18771 else if (!Context
.hasSameType(Val
->getType(), Context
.IntTy
)) {
18772 // Force the type of the expression to 'int'.
18773 Val
= ImpCastExprToType(Val
, Context
.IntTy
, CK_IntegralCast
).get();
18775 EltTy
= Val
->getType();
18782 if (Enum
->isDependentType())
18783 EltTy
= Context
.DependentTy
;
18784 else if (!LastEnumConst
) {
18785 // C++0x [dcl.enum]p5:
18786 // If the underlying type is not fixed, the type of each enumerator
18787 // is the type of its initializing value:
18788 // - If no initializer is specified for the first enumerator, the
18789 // initializing value has an unspecified integral type.
18791 // GCC uses 'int' for its unspecified integral type, as does
18793 if (Enum
->isFixed()) {
18794 EltTy
= Enum
->getIntegerType();
18797 EltTy
= Context
.IntTy
;
18800 // Assign the last value + 1.
18801 EnumVal
= LastEnumConst
->getInitVal();
18803 EltTy
= LastEnumConst
->getType();
18805 // Check for overflow on increment.
18806 if (EnumVal
< LastEnumConst
->getInitVal()) {
18807 // C++0x [dcl.enum]p5:
18808 // If the underlying type is not fixed, the type of each enumerator
18809 // is the type of its initializing value:
18811 // - Otherwise the type of the initializing value is the same as
18812 // the type of the initializing value of the preceding enumerator
18813 // unless the incremented value is not representable in that type,
18814 // in which case the type is an unspecified integral type
18815 // sufficient to contain the incremented value. If no such type
18816 // exists, the program is ill-formed.
18817 QualType T
= getNextLargerIntegralType(Context
, EltTy
);
18818 if (T
.isNull() || Enum
->isFixed()) {
18819 // There is no integral type larger enough to represent this
18820 // value. Complain, then allow the value to wrap around.
18821 EnumVal
= LastEnumConst
->getInitVal();
18822 EnumVal
= EnumVal
.zext(EnumVal
.getBitWidth() * 2);
18824 if (Enum
->isFixed())
18825 // When the underlying type is fixed, this is ill-formed.
18826 Diag(IdLoc
, diag::err_enumerator_wrapped
)
18827 << toString(EnumVal
, 10)
18830 Diag(IdLoc
, diag::ext_enumerator_increment_too_large
)
18831 << toString(EnumVal
, 10);
18836 // Retrieve the last enumerator's value, extent that type to the
18837 // type that is supposed to be large enough to represent the incremented
18838 // value, then increment.
18839 EnumVal
= LastEnumConst
->getInitVal();
18840 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
18841 EnumVal
= EnumVal
.zextOrTrunc(Context
.getIntWidth(EltTy
));
18844 // If we're not in C++, diagnose the overflow of enumerator values,
18845 // which in C99 means that the enumerator value is not representable in
18846 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18847 // permits enumerator values that are representable in some larger
18849 if (!getLangOpts().CPlusPlus
&& !T
.isNull())
18850 Diag(IdLoc
, diag::warn_enum_value_overflow
);
18851 } else if (!getLangOpts().CPlusPlus
&&
18852 !isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
18853 // Enforce C99 6.7.2.2p2 even when we compute the next value.
18854 Diag(IdLoc
, diag::ext_enum_value_not_int
)
18855 << toString(EnumVal
, 10) << 1;
18860 if (!EltTy
->isDependentType()) {
18861 // Make the enumerator value match the signedness and size of the
18862 // enumerator's type.
18863 EnumVal
= EnumVal
.extOrTrunc(Context
.getIntWidth(EltTy
));
18864 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
18867 return EnumConstantDecl::Create(Context
, Enum
, IdLoc
, Id
, EltTy
,
18871 Sema::SkipBodyInfo
Sema::shouldSkipAnonEnumBody(Scope
*S
, IdentifierInfo
*II
,
18872 SourceLocation IILoc
) {
18873 if (!(getLangOpts().Modules
|| getLangOpts().ModulesLocalVisibility
) ||
18874 !getLangOpts().CPlusPlus
)
18875 return SkipBodyInfo();
18877 // We have an anonymous enum definition. Look up the first enumerator to
18878 // determine if we should merge the definition with an existing one and
18880 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, IILoc
, LookupOrdinaryName
,
18881 forRedeclarationInCurContext());
18882 auto *PrevECD
= dyn_cast_or_null
<EnumConstantDecl
>(PrevDecl
);
18884 return SkipBodyInfo();
18886 EnumDecl
*PrevED
= cast
<EnumDecl
>(PrevECD
->getDeclContext());
18888 if (!PrevED
->getDeclName() && !hasVisibleDefinition(PrevED
, &Hidden
)) {
18890 Skip
.Previous
= Hidden
;
18894 return SkipBodyInfo();
18897 Decl
*Sema::ActOnEnumConstant(Scope
*S
, Decl
*theEnumDecl
, Decl
*lastEnumConst
,
18898 SourceLocation IdLoc
, IdentifierInfo
*Id
,
18899 const ParsedAttributesView
&Attrs
,
18900 SourceLocation EqualLoc
, Expr
*Val
) {
18901 EnumDecl
*TheEnumDecl
= cast
<EnumDecl
>(theEnumDecl
);
18902 EnumConstantDecl
*LastEnumConst
=
18903 cast_or_null
<EnumConstantDecl
>(lastEnumConst
);
18905 // The scope passed in may not be a decl scope. Zip up the scope tree until
18906 // we find one that is.
18907 S
= getNonFieldDeclScope(S
);
18909 // Verify that there isn't already something declared with this name in this
18911 LookupResult
R(*this, Id
, IdLoc
, LookupOrdinaryName
, ForVisibleRedeclaration
);
18913 NamedDecl
*PrevDecl
= R
.getAsSingle
<NamedDecl
>();
18915 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
18916 // Maybe we will complain about the shadowed template parameter.
18917 DiagnoseTemplateParameterShadow(IdLoc
, PrevDecl
);
18918 // Just pretend that we didn't see the previous declaration.
18919 PrevDecl
= nullptr;
18922 // C++ [class.mem]p15:
18923 // If T is the name of a class, then each of the following shall have a name
18924 // different from T:
18925 // - every enumerator of every member of class T that is an unscoped
18927 if (getLangOpts().CPlusPlus
&& !TheEnumDecl
->isScoped())
18928 DiagnoseClassNameShadow(TheEnumDecl
->getDeclContext(),
18929 DeclarationNameInfo(Id
, IdLoc
));
18931 EnumConstantDecl
*New
=
18932 CheckEnumConstant(TheEnumDecl
, LastEnumConst
, IdLoc
, Id
, Val
);
18937 if (!TheEnumDecl
->isScoped() && isa
<ValueDecl
>(PrevDecl
)) {
18938 // Check for other kinds of shadowing not already handled.
18939 CheckShadow(New
, PrevDecl
, R
);
18942 // When in C++, we may get a TagDecl with the same name; in this case the
18943 // enum constant will 'hide' the tag.
18944 assert((getLangOpts().CPlusPlus
|| !isa
<TagDecl
>(PrevDecl
)) &&
18945 "Received TagDecl when not in C++!");
18946 if (!isa
<TagDecl
>(PrevDecl
) && isDeclInScope(PrevDecl
, CurContext
, S
)) {
18947 if (isa
<EnumConstantDecl
>(PrevDecl
))
18948 Diag(IdLoc
, diag::err_redefinition_of_enumerator
) << Id
;
18950 Diag(IdLoc
, diag::err_redefinition
) << Id
;
18951 notePreviousDefinition(PrevDecl
, IdLoc
);
18956 // Process attributes.
18957 ProcessDeclAttributeList(S
, New
, Attrs
);
18958 AddPragmaAttributes(S
, New
);
18960 // Register this decl in the current scope stack.
18961 New
->setAccess(TheEnumDecl
->getAccess());
18962 PushOnScopeChains(New
, S
);
18964 ActOnDocumentableDecl(New
);
18969 // Returns true when the enum initial expression does not trigger the
18970 // duplicate enum warning. A few common cases are exempted as follows:
18971 // Element2 = Element1
18972 // Element2 = Element1 + 1
18973 // Element2 = Element1 - 1
18974 // Where Element2 and Element1 are from the same enum.
18975 static bool ValidDuplicateEnum(EnumConstantDecl
*ECD
, EnumDecl
*Enum
) {
18976 Expr
*InitExpr
= ECD
->getInitExpr();
18979 InitExpr
= InitExpr
->IgnoreImpCasts();
18981 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(InitExpr
)) {
18982 if (!BO
->isAdditiveOp())
18984 IntegerLiteral
*IL
= dyn_cast
<IntegerLiteral
>(BO
->getRHS());
18987 if (IL
->getValue() != 1)
18990 InitExpr
= BO
->getLHS();
18993 // This checks if the elements are from the same enum.
18994 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InitExpr
);
18998 EnumConstantDecl
*EnumConstant
= dyn_cast
<EnumConstantDecl
>(DRE
->getDecl());
19002 if (cast
<EnumDecl
>(TagDecl::castFromDeclContext(ECD
->getDeclContext())) !=
19009 // Emits a warning when an element is implicitly set a value that
19010 // a previous element has already been set to.
19011 static void CheckForDuplicateEnumValues(Sema
&S
, ArrayRef
<Decl
*> Elements
,
19012 EnumDecl
*Enum
, QualType EnumType
) {
19013 // Avoid anonymous enums
19014 if (!Enum
->getIdentifier())
19017 // Only check for small enums.
19018 if (Enum
->getNumPositiveBits() > 63 || Enum
->getNumNegativeBits() > 64)
19021 if (S
.Diags
.isIgnored(diag::warn_duplicate_enum_values
, Enum
->getLocation()))
19024 typedef SmallVector
<EnumConstantDecl
*, 3> ECDVector
;
19025 typedef SmallVector
<std::unique_ptr
<ECDVector
>, 3> DuplicatesVector
;
19027 typedef llvm::PointerUnion
<EnumConstantDecl
*, ECDVector
*> DeclOrVector
;
19029 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19030 typedef std::unordered_map
<int64_t, DeclOrVector
> ValueToVectorMap
;
19032 // Use int64_t as a key to avoid needing special handling for map keys.
19033 auto EnumConstantToKey
= [](const EnumConstantDecl
*D
) {
19034 llvm::APSInt Val
= D
->getInitVal();
19035 return Val
.isSigned() ? Val
.getSExtValue() : Val
.getZExtValue();
19038 DuplicatesVector DupVector
;
19039 ValueToVectorMap EnumMap
;
19041 // Populate the EnumMap with all values represented by enum constants without
19043 for (auto *Element
: Elements
) {
19044 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(Element
);
19046 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19047 // this constant. Skip this enum since it may be ill-formed.
19052 // Constants with initalizers are handled in the next loop.
19053 if (ECD
->getInitExpr())
19056 // Duplicate values are handled in the next loop.
19057 EnumMap
.insert({EnumConstantToKey(ECD
), ECD
});
19060 if (EnumMap
.size() == 0)
19063 // Create vectors for any values that has duplicates.
19064 for (auto *Element
: Elements
) {
19065 // The last loop returned if any constant was null.
19066 EnumConstantDecl
*ECD
= cast
<EnumConstantDecl
>(Element
);
19067 if (!ValidDuplicateEnum(ECD
, Enum
))
19070 auto Iter
= EnumMap
.find(EnumConstantToKey(ECD
));
19071 if (Iter
== EnumMap
.end())
19074 DeclOrVector
& Entry
= Iter
->second
;
19075 if (EnumConstantDecl
*D
= Entry
.dyn_cast
<EnumConstantDecl
*>()) {
19076 // Ensure constants are different.
19080 // Create new vector and push values onto it.
19081 auto Vec
= std::make_unique
<ECDVector
>();
19083 Vec
->push_back(ECD
);
19085 // Update entry to point to the duplicates vector.
19088 // Store the vector somewhere we can consult later for quick emission of
19090 DupVector
.emplace_back(std::move(Vec
));
19094 ECDVector
*Vec
= Entry
.get
<ECDVector
*>();
19095 // Make sure constants are not added more than once.
19096 if (*Vec
->begin() == ECD
)
19099 Vec
->push_back(ECD
);
19102 // Emit diagnostics.
19103 for (const auto &Vec
: DupVector
) {
19104 assert(Vec
->size() > 1 && "ECDVector should have at least 2 elements.");
19106 // Emit warning for one enum constant.
19107 auto *FirstECD
= Vec
->front();
19108 S
.Diag(FirstECD
->getLocation(), diag::warn_duplicate_enum_values
)
19109 << FirstECD
<< toString(FirstECD
->getInitVal(), 10)
19110 << FirstECD
->getSourceRange();
19112 // Emit one note for each of the remaining enum constants with
19114 for (auto *ECD
: llvm::drop_begin(*Vec
))
19115 S
.Diag(ECD
->getLocation(), diag::note_duplicate_element
)
19116 << ECD
<< toString(ECD
->getInitVal(), 10)
19117 << ECD
->getSourceRange();
19121 bool Sema::IsValueInFlagEnum(const EnumDecl
*ED
, const llvm::APInt
&Val
,
19122 bool AllowMask
) const {
19123 assert(ED
->isClosedFlag() && "looking for value in non-flag or open enum");
19124 assert(ED
->isCompleteDefinition() && "expected enum definition");
19126 auto R
= FlagBitsCache
.insert(std::make_pair(ED
, llvm::APInt()));
19127 llvm::APInt
&FlagBits
= R
.first
->second
;
19130 for (auto *E
: ED
->enumerators()) {
19131 const auto &EVal
= E
->getInitVal();
19132 // Only single-bit enumerators introduce new flag values.
19133 if (EVal
.isPowerOf2())
19134 FlagBits
= FlagBits
.zext(EVal
.getBitWidth()) | EVal
;
19138 // A value is in a flag enum if either its bits are a subset of the enum's
19139 // flag bits (the first condition) or we are allowing masks and the same is
19140 // true of its complement (the second condition). When masks are allowed, we
19141 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19143 // While it's true that any value could be used as a mask, the assumption is
19144 // that a mask will have all of the insignificant bits set. Anything else is
19145 // likely a logic error.
19146 llvm::APInt FlagMask
= ~FlagBits
.zextOrTrunc(Val
.getBitWidth());
19147 return !(FlagMask
& Val
) || (AllowMask
&& !(FlagMask
& ~Val
));
19150 void Sema::ActOnEnumBody(SourceLocation EnumLoc
, SourceRange BraceRange
,
19151 Decl
*EnumDeclX
, ArrayRef
<Decl
*> Elements
, Scope
*S
,
19152 const ParsedAttributesView
&Attrs
) {
19153 EnumDecl
*Enum
= cast
<EnumDecl
>(EnumDeclX
);
19154 QualType EnumType
= Context
.getTypeDeclType(Enum
);
19156 ProcessDeclAttributeList(S
, Enum
, Attrs
);
19158 if (Enum
->isDependentType()) {
19159 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
19160 EnumConstantDecl
*ECD
=
19161 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
19162 if (!ECD
) continue;
19164 ECD
->setType(EnumType
);
19167 Enum
->completeDefinition(Context
.DependentTy
, Context
.DependentTy
, 0, 0);
19171 // TODO: If the result value doesn't fit in an int, it must be a long or long
19172 // long value. ISO C does not support this, but GCC does as an extension,
19174 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
19175 unsigned CharWidth
= Context
.getTargetInfo().getCharWidth();
19176 unsigned ShortWidth
= Context
.getTargetInfo().getShortWidth();
19178 // Verify that all the values are okay, compute the size of the values, and
19179 // reverse the list.
19180 unsigned NumNegativeBits
= 0;
19181 unsigned NumPositiveBits
= 0;
19183 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
19184 EnumConstantDecl
*ECD
=
19185 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
19186 if (!ECD
) continue; // Already issued a diagnostic.
19188 const llvm::APSInt
&InitVal
= ECD
->getInitVal();
19190 // Keep track of the size of positive and negative values.
19191 if (InitVal
.isUnsigned() || InitVal
.isNonNegative()) {
19192 // If the enumerator is zero that should still be counted as a positive
19193 // bit since we need a bit to store the value zero.
19194 unsigned ActiveBits
= InitVal
.getActiveBits();
19195 NumPositiveBits
= std::max({NumPositiveBits
, ActiveBits
, 1u});
19197 NumNegativeBits
= std::max(NumNegativeBits
,
19198 (unsigned)InitVal
.getMinSignedBits());
19202 // If we have have an empty set of enumerators we still need one bit.
19203 // From [dcl.enum]p8
19204 // If the enumerator-list is empty, the values of the enumeration are as if
19205 // the enumeration had a single enumerator with value 0
19206 if (!NumPositiveBits
&& !NumNegativeBits
)
19207 NumPositiveBits
= 1;
19209 // Figure out the type that should be used for this enum.
19211 unsigned BestWidth
;
19213 // C++0x N3000 [conv.prom]p3:
19214 // An rvalue of an unscoped enumeration type whose underlying
19215 // type is not fixed can be converted to an rvalue of the first
19216 // of the following types that can represent all the values of
19217 // the enumeration: int, unsigned int, long int, unsigned long
19218 // int, long long int, or unsigned long long int.
19220 // An identifier declared as an enumeration constant has type int.
19221 // The C99 rule is modified by a gcc extension
19222 QualType BestPromotionType
;
19224 bool Packed
= Enum
->hasAttr
<PackedAttr
>();
19225 // -fshort-enums is the equivalent to specifying the packed attribute on all
19226 // enum definitions.
19227 if (LangOpts
.ShortEnums
)
19230 // If the enum already has a type because it is fixed or dictated by the
19231 // target, promote that type instead of analyzing the enumerators.
19232 if (Enum
->isComplete()) {
19233 BestType
= Enum
->getIntegerType();
19234 if (BestType
->isPromotableIntegerType())
19235 BestPromotionType
= Context
.getPromotedIntegerType(BestType
);
19237 BestPromotionType
= BestType
;
19239 BestWidth
= Context
.getIntWidth(BestType
);
19241 else if (NumNegativeBits
) {
19242 // If there is a negative value, figure out the smallest integer type (of
19243 // int/long/longlong) that fits.
19244 // If it's packed, check also if it fits a char or a short.
19245 if (Packed
&& NumNegativeBits
<= CharWidth
&& NumPositiveBits
< CharWidth
) {
19246 BestType
= Context
.SignedCharTy
;
19247 BestWidth
= CharWidth
;
19248 } else if (Packed
&& NumNegativeBits
<= ShortWidth
&&
19249 NumPositiveBits
< ShortWidth
) {
19250 BestType
= Context
.ShortTy
;
19251 BestWidth
= ShortWidth
;
19252 } else if (NumNegativeBits
<= IntWidth
&& NumPositiveBits
< IntWidth
) {
19253 BestType
= Context
.IntTy
;
19254 BestWidth
= IntWidth
;
19256 BestWidth
= Context
.getTargetInfo().getLongWidth();
19258 if (NumNegativeBits
<= BestWidth
&& NumPositiveBits
< BestWidth
) {
19259 BestType
= Context
.LongTy
;
19261 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
19263 if (NumNegativeBits
> BestWidth
|| NumPositiveBits
>= BestWidth
)
19264 Diag(Enum
->getLocation(), diag::ext_enum_too_large
);
19265 BestType
= Context
.LongLongTy
;
19268 BestPromotionType
= (BestWidth
<= IntWidth
? Context
.IntTy
: BestType
);
19270 // If there is no negative value, figure out the smallest type that fits
19271 // all of the enumerator values.
19272 // If it's packed, check also if it fits a char or a short.
19273 if (Packed
&& NumPositiveBits
<= CharWidth
) {
19274 BestType
= Context
.UnsignedCharTy
;
19275 BestPromotionType
= Context
.IntTy
;
19276 BestWidth
= CharWidth
;
19277 } else if (Packed
&& NumPositiveBits
<= ShortWidth
) {
19278 BestType
= Context
.UnsignedShortTy
;
19279 BestPromotionType
= Context
.IntTy
;
19280 BestWidth
= ShortWidth
;
19281 } else if (NumPositiveBits
<= IntWidth
) {
19282 BestType
= Context
.UnsignedIntTy
;
19283 BestWidth
= IntWidth
;
19285 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19286 ? Context
.UnsignedIntTy
: Context
.IntTy
;
19287 } else if (NumPositiveBits
<=
19288 (BestWidth
= Context
.getTargetInfo().getLongWidth())) {
19289 BestType
= Context
.UnsignedLongTy
;
19291 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19292 ? Context
.UnsignedLongTy
: Context
.LongTy
;
19294 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
19295 assert(NumPositiveBits
<= BestWidth
&&
19296 "How could an initializer get larger than ULL?");
19297 BestType
= Context
.UnsignedLongLongTy
;
19299 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19300 ? Context
.UnsignedLongLongTy
: Context
.LongLongTy
;
19304 // Loop over all of the enumerator constants, changing their types to match
19305 // the type of the enum if needed.
19306 for (auto *D
: Elements
) {
19307 auto *ECD
= cast_or_null
<EnumConstantDecl
>(D
);
19308 if (!ECD
) continue; // Already issued a diagnostic.
19310 // Standard C says the enumerators have int type, but we allow, as an
19311 // extension, the enumerators to be larger than int size. If each
19312 // enumerator value fits in an int, type it as an int, otherwise type it the
19313 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19314 // that X has type 'int', not 'unsigned'.
19316 // Determine whether the value fits into an int.
19317 llvm::APSInt InitVal
= ECD
->getInitVal();
19319 // If it fits into an integer type, force it. Otherwise force it to match
19320 // the enum decl type.
19324 if (!getLangOpts().CPlusPlus
&&
19325 !Enum
->isFixed() &&
19326 isRepresentableIntegerValue(Context
, InitVal
, Context
.IntTy
)) {
19327 NewTy
= Context
.IntTy
;
19328 NewWidth
= IntWidth
;
19330 } else if (ECD
->getType() == BestType
) {
19331 // Already the right type!
19332 if (getLangOpts().CPlusPlus
)
19333 // C++ [dcl.enum]p4: Following the closing brace of an
19334 // enum-specifier, each enumerator has the type of its
19336 ECD
->setType(EnumType
);
19340 NewWidth
= BestWidth
;
19341 NewSign
= BestType
->isSignedIntegerOrEnumerationType();
19344 // Adjust the APSInt value.
19345 InitVal
= InitVal
.extOrTrunc(NewWidth
);
19346 InitVal
.setIsSigned(NewSign
);
19347 ECD
->setInitVal(InitVal
);
19349 // Adjust the Expr initializer and type.
19350 if (ECD
->getInitExpr() &&
19351 !Context
.hasSameType(NewTy
, ECD
->getInitExpr()->getType()))
19352 ECD
->setInitExpr(ImplicitCastExpr::Create(
19353 Context
, NewTy
, CK_IntegralCast
, ECD
->getInitExpr(),
19354 /*base paths*/ nullptr, VK_PRValue
, FPOptionsOverride()));
19355 if (getLangOpts().CPlusPlus
)
19356 // C++ [dcl.enum]p4: Following the closing brace of an
19357 // enum-specifier, each enumerator has the type of its
19359 ECD
->setType(EnumType
);
19361 ECD
->setType(NewTy
);
19364 Enum
->completeDefinition(BestType
, BestPromotionType
,
19365 NumPositiveBits
, NumNegativeBits
);
19367 CheckForDuplicateEnumValues(*this, Elements
, Enum
, EnumType
);
19369 if (Enum
->isClosedFlag()) {
19370 for (Decl
*D
: Elements
) {
19371 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(D
);
19372 if (!ECD
) continue; // Already issued a diagnostic.
19374 llvm::APSInt InitVal
= ECD
->getInitVal();
19375 if (InitVal
!= 0 && !InitVal
.isPowerOf2() &&
19376 !IsValueInFlagEnum(Enum
, InitVal
, true))
19377 Diag(ECD
->getLocation(), diag::warn_flag_enum_constant_out_of_range
)
19382 // Now that the enum type is defined, ensure it's not been underaligned.
19383 if (Enum
->hasAttrs())
19384 CheckAlignasUnderalignment(Enum
);
19387 Decl
*Sema::ActOnFileScopeAsmDecl(Expr
*expr
,
19388 SourceLocation StartLoc
,
19389 SourceLocation EndLoc
) {
19390 StringLiteral
*AsmString
= cast
<StringLiteral
>(expr
);
19392 FileScopeAsmDecl
*New
= FileScopeAsmDecl::Create(Context
, CurContext
,
19393 AsmString
, StartLoc
,
19395 CurContext
->addDecl(New
);
19399 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo
* Name
,
19400 IdentifierInfo
* AliasName
,
19401 SourceLocation PragmaLoc
,
19402 SourceLocation NameLoc
,
19403 SourceLocation AliasNameLoc
) {
19404 NamedDecl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
,
19405 LookupOrdinaryName
);
19406 AttributeCommonInfo
Info(AliasName
, SourceRange(AliasNameLoc
),
19407 AttributeCommonInfo::AS_Pragma
);
19408 AsmLabelAttr
*Attr
= AsmLabelAttr::CreateImplicit(
19409 Context
, AliasName
->getName(), /*IsLiteralLabel=*/true, Info
);
19411 // If a declaration that:
19412 // 1) declares a function or a variable
19413 // 2) has external linkage
19414 // already exists, add a label attribute to it.
19415 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
19416 if (isDeclExternC(PrevDecl
))
19417 PrevDecl
->addAttr(Attr
);
19419 Diag(PrevDecl
->getLocation(), diag::warn_redefine_extname_not_applied
)
19420 << /*Variable*/(isa
<FunctionDecl
>(PrevDecl
) ? 0 : 1) << PrevDecl
;
19421 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19423 (void)ExtnameUndeclaredIdentifiers
.insert(std::make_pair(Name
, Attr
));
19426 void Sema::ActOnPragmaWeakID(IdentifierInfo
* Name
,
19427 SourceLocation PragmaLoc
,
19428 SourceLocation NameLoc
) {
19429 Decl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
, LookupOrdinaryName
);
19432 PrevDecl
->addAttr(WeakAttr::CreateImplicit(Context
, PragmaLoc
, AttributeCommonInfo::AS_Pragma
));
19434 (void)WeakUndeclaredIdentifiers
[Name
].insert(WeakInfo(nullptr, NameLoc
));
19438 void Sema::ActOnPragmaWeakAlias(IdentifierInfo
* Name
,
19439 IdentifierInfo
* AliasName
,
19440 SourceLocation PragmaLoc
,
19441 SourceLocation NameLoc
,
19442 SourceLocation AliasNameLoc
) {
19443 Decl
*PrevDecl
= LookupSingleName(TUScope
, AliasName
, AliasNameLoc
,
19444 LookupOrdinaryName
);
19445 WeakInfo W
= WeakInfo(Name
, NameLoc
);
19447 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
19448 if (!PrevDecl
->hasAttr
<AliasAttr
>())
19449 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(PrevDecl
))
19450 DeclApplyPragmaWeak(TUScope
, ND
, W
);
19452 (void)WeakUndeclaredIdentifiers
[AliasName
].insert(W
);
19456 ObjCContainerDecl
*Sema::getObjCDeclContext() const {
19457 return (dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
));
19460 Sema::FunctionEmissionStatus
Sema::getEmissionStatus(FunctionDecl
*FD
,
19462 assert(FD
&& "Expected non-null FunctionDecl");
19464 // SYCL functions can be template, so we check if they have appropriate
19465 // attribute prior to checking if it is a template.
19466 if (LangOpts
.SYCLIsDevice
&& FD
->hasAttr
<SYCLKernelAttr
>())
19467 return FunctionEmissionStatus::Emitted
;
19469 // Templates are emitted when they're instantiated.
19470 if (FD
->isDependentContext())
19471 return FunctionEmissionStatus::TemplateDiscarded
;
19473 // Check whether this function is an externally visible definition.
19474 auto IsEmittedForExternalSymbol
= [this, FD
]() {
19475 // We have to check the GVA linkage of the function's *definition* -- if we
19476 // only have a declaration, we don't know whether or not the function will
19477 // be emitted, because (say) the definition could include "inline".
19478 FunctionDecl
*Def
= FD
->getDefinition();
19480 return Def
&& !isDiscardableGVALinkage(
19481 getASTContext().GetGVALinkageForFunction(Def
));
19484 if (LangOpts
.OpenMPIsDevice
) {
19485 // In OpenMP device mode we will not emit host only functions, or functions
19486 // we don't need due to their linkage.
19487 Optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
19488 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
19489 // DevTy may be changed later by
19490 // #pragma omp declare target to(*) device_type(*).
19491 // Therefore DevTy having no value does not imply host. The emission status
19492 // will be checked again at the end of compilation unit with Final = true.
19494 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_Host
)
19495 return FunctionEmissionStatus::OMPDiscarded
;
19496 // If we have an explicit value for the device type, or we are in a target
19497 // declare context, we need to emit all extern and used symbols.
19498 if (isInOpenMPDeclareTargetContext() || DevTy
)
19499 if (IsEmittedForExternalSymbol())
19500 return FunctionEmissionStatus::Emitted
;
19501 // Device mode only emits what it must, if it wasn't tagged yet and needed,
19504 return FunctionEmissionStatus::OMPDiscarded
;
19505 } else if (LangOpts
.OpenMP
> 45) {
19506 // In OpenMP host compilation prior to 5.0 everything was an emitted host
19507 // function. In 5.0, no_host was introduced which might cause a function to
19509 Optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
19510 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
19512 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_NoHost
)
19513 return FunctionEmissionStatus::OMPDiscarded
;
19516 if (Final
&& LangOpts
.OpenMP
&& !LangOpts
.CUDA
)
19517 return FunctionEmissionStatus::Emitted
;
19519 if (LangOpts
.CUDA
) {
19520 // When compiling for device, host functions are never emitted. Similarly,
19521 // when compiling for host, device and global functions are never emitted.
19522 // (Technically, we do emit a host-side stub for global functions, but this
19523 // doesn't count for our purposes here.)
19524 Sema::CUDAFunctionTarget T
= IdentifyCUDATarget(FD
);
19525 if (LangOpts
.CUDAIsDevice
&& T
== Sema::CFT_Host
)
19526 return FunctionEmissionStatus::CUDADiscarded
;
19527 if (!LangOpts
.CUDAIsDevice
&&
19528 (T
== Sema::CFT_Device
|| T
== Sema::CFT_Global
))
19529 return FunctionEmissionStatus::CUDADiscarded
;
19531 if (IsEmittedForExternalSymbol())
19532 return FunctionEmissionStatus::Emitted
;
19535 // Otherwise, the function is known-emitted if it's in our set of
19536 // known-emitted functions.
19537 return FunctionEmissionStatus::Unknown
;
19540 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl
*Callee
) {
19541 // Host-side references to a __global__ function refer to the stub, so the
19542 // function itself is never emitted and therefore should not be marked.
19543 // If we have host fn calls kernel fn calls host+device, the HD function
19544 // does not get instantiated on the host. We model this by omitting at the
19545 // call to the kernel from the callgraph. This ensures that, when compiling
19546 // for host, only HD functions actually called from the host get marked as
19548 return LangOpts
.CUDA
&& !LangOpts
.CUDAIsDevice
&&
19549 IdentifyCUDATarget(Callee
) == CFT_Global
;