[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Sema / SemaDecl.cpp
blob396566a8f10a9b700309c7c93a87d429ab3d9bf6
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <functional>
54 #include <optional>
55 #include <unordered_map>
57 using namespace clang;
58 using namespace sema;
60 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
61 if (OwnedType) {
62 Decl *Group[2] = { OwnedType, Ptr };
63 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
66 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
69 namespace {
71 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72 public:
73 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74 bool AllowTemplates = false,
75 bool AllowNonTemplates = true)
76 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78 WantExpressionKeywords = false;
79 WantCXXNamedCasts = false;
80 WantRemainingKeywords = false;
83 bool ValidateCandidate(const TypoCorrection &candidate) override {
84 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85 if (!AllowInvalidDecl && ND->isInvalidDecl())
86 return false;
88 if (getAsTypeTemplateDecl(ND))
89 return AllowTemplates;
91 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
92 if (!IsType)
93 return false;
95 if (AllowNonTemplates)
96 return true;
98 // An injected-class-name of a class template (specialization) is valid
99 // as a template or as a non-template.
100 if (AllowTemplates) {
101 auto *RD = dyn_cast<CXXRecordDecl>(ND);
102 if (!RD || !RD->isInjectedClassName())
103 return false;
104 RD = cast<CXXRecordDecl>(RD->getDeclContext());
105 return RD->getDescribedClassTemplate() ||
106 isa<ClassTemplateSpecializationDecl>(RD);
109 return false;
112 return !WantClassName && candidate.isKeyword();
115 std::unique_ptr<CorrectionCandidateCallback> clone() override {
116 return std::make_unique<TypeNameValidatorCCC>(*this);
119 private:
120 bool AllowInvalidDecl;
121 bool WantClassName;
122 bool AllowTemplates;
123 bool AllowNonTemplates;
126 } // end anonymous namespace
128 /// Determine whether the token kind starts a simple-type-specifier.
129 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
130 switch (Kind) {
131 // FIXME: Take into account the current language when deciding whether a
132 // token kind is a valid type specifier
133 case tok::kw_short:
134 case tok::kw_long:
135 case tok::kw___int64:
136 case tok::kw___int128:
137 case tok::kw_signed:
138 case tok::kw_unsigned:
139 case tok::kw_void:
140 case tok::kw_char:
141 case tok::kw_int:
142 case tok::kw_half:
143 case tok::kw_float:
144 case tok::kw_double:
145 case tok::kw___bf16:
146 case tok::kw__Float16:
147 case tok::kw___float128:
148 case tok::kw___ibm128:
149 case tok::kw_wchar_t:
150 case tok::kw_bool:
151 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152 #include "clang/Basic/TransformTypeTraits.def"
153 case tok::kw___auto_type:
154 return true;
156 case tok::annot_typename:
157 case tok::kw_char16_t:
158 case tok::kw_char32_t:
159 case tok::kw_typeof:
160 case tok::annot_decltype:
161 case tok::kw_decltype:
162 return getLangOpts().CPlusPlus;
164 case tok::kw_char8_t:
165 return getLangOpts().Char8;
167 default:
168 break;
171 return false;
174 namespace {
175 enum class UnqualifiedTypeNameLookupResult {
176 NotFound,
177 FoundNonType,
178 FoundType
180 } // end anonymous namespace
182 /// Tries to perform unqualified lookup of the type decls in bases for
183 /// dependent class.
184 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185 /// type decl, \a FoundType if only type decls are found.
186 static UnqualifiedTypeNameLookupResult
187 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
188 SourceLocation NameLoc,
189 const CXXRecordDecl *RD) {
190 if (!RD->hasDefinition())
191 return UnqualifiedTypeNameLookupResult::NotFound;
192 // Look for type decls in base classes.
193 UnqualifiedTypeNameLookupResult FoundTypeDecl =
194 UnqualifiedTypeNameLookupResult::NotFound;
195 for (const auto &Base : RD->bases()) {
196 const CXXRecordDecl *BaseRD = nullptr;
197 if (auto *BaseTT = Base.getType()->getAs<TagType>())
198 BaseRD = BaseTT->getAsCXXRecordDecl();
199 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200 // Look for type decls in dependent base classes that have known primary
201 // templates.
202 if (!TST || !TST->isDependentType())
203 continue;
204 auto *TD = TST->getTemplateName().getAsTemplateDecl();
205 if (!TD)
206 continue;
207 if (auto *BasePrimaryTemplate =
208 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210 BaseRD = BasePrimaryTemplate;
211 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212 if (const ClassTemplatePartialSpecializationDecl *PS =
213 CTD->findPartialSpecialization(Base.getType()))
214 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215 BaseRD = PS;
219 if (BaseRD) {
220 for (NamedDecl *ND : BaseRD->lookup(&II)) {
221 if (!isa<TypeDecl>(ND))
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227 case UnqualifiedTypeNameLookupResult::FoundNonType:
228 return UnqualifiedTypeNameLookupResult::FoundNonType;
229 case UnqualifiedTypeNameLookupResult::FoundType:
230 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231 break;
232 case UnqualifiedTypeNameLookupResult::NotFound:
233 break;
239 return FoundTypeDecl;
242 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
243 const IdentifierInfo &II,
244 SourceLocation NameLoc) {
245 // Lookup in the parent class template context, if any.
246 const CXXRecordDecl *RD = nullptr;
247 UnqualifiedTypeNameLookupResult FoundTypeDecl =
248 UnqualifiedTypeNameLookupResult::NotFound;
249 for (DeclContext *DC = S.CurContext;
250 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
251 DC = DC->getParent()) {
252 // Look for type decls in dependent base classes that have known primary
253 // templates.
254 RD = dyn_cast<CXXRecordDecl>(DC);
255 if (RD && RD->getDescribedClassTemplate())
256 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
258 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259 return nullptr;
261 // We found some types in dependent base classes. Recover as if the user
262 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
263 // lookup during template instantiation.
264 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
266 ASTContext &Context = S.Context;
267 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268 cast<Type>(Context.getRecordType(RD)));
269 QualType T =
270 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
272 CXXScopeSpec SS;
273 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
275 TypeLocBuilder Builder;
276 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
277 DepTL.setNameLoc(NameLoc);
278 DepTL.setElaboratedKeywordLoc(SourceLocation());
279 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
280 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
283 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
284 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
285 SourceLocation NameLoc,
286 bool WantNontrivialTypeSourceInfo = true) {
287 switch (T->getTypeClass()) {
288 case Type::DeducedTemplateSpecialization:
289 case Type::Enum:
290 case Type::InjectedClassName:
291 case Type::Record:
292 case Type::Typedef:
293 case Type::UnresolvedUsing:
294 case Type::Using:
295 break;
296 // These can never be qualified so an ElaboratedType node
297 // would carry no additional meaning.
298 case Type::ObjCInterface:
299 case Type::ObjCTypeParam:
300 case Type::TemplateTypeParm:
301 return ParsedType::make(T);
302 default:
303 llvm_unreachable("Unexpected Type Class");
306 if (!SS || SS->isEmpty())
307 return ParsedType::make(S.Context.getElaboratedType(
308 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
310 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
311 if (!WantNontrivialTypeSourceInfo)
312 return ParsedType::make(ElTy);
314 TypeLocBuilder Builder;
315 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
316 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
317 ElabTL.setElaboratedKeywordLoc(SourceLocation());
318 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
319 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
322 /// If the identifier refers to a type name within this scope,
323 /// return the declaration of that type.
325 /// This routine performs ordinary name lookup of the identifier II
326 /// within the given scope, with optional C++ scope specifier SS, to
327 /// determine whether the name refers to a type. If so, returns an
328 /// opaque pointer (actually a QualType) corresponding to that
329 /// type. Otherwise, returns NULL.
330 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
331 Scope *S, CXXScopeSpec *SS, bool isClassName,
332 bool HasTrailingDot, ParsedType ObjectTypePtr,
333 bool IsCtorOrDtorName,
334 bool WantNontrivialTypeSourceInfo,
335 bool IsClassTemplateDeductionContext,
336 ImplicitTypenameContext AllowImplicitTypename,
337 IdentifierInfo **CorrectedII) {
338 // FIXME: Consider allowing this outside C++1z mode as an extension.
339 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
340 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
341 !isClassName && !HasTrailingDot;
343 // Determine where we will perform name lookup.
344 DeclContext *LookupCtx = nullptr;
345 if (ObjectTypePtr) {
346 QualType ObjectType = ObjectTypePtr.get();
347 if (ObjectType->isRecordType())
348 LookupCtx = computeDeclContext(ObjectType);
349 } else if (SS && SS->isNotEmpty()) {
350 LookupCtx = computeDeclContext(*SS, false);
352 if (!LookupCtx) {
353 if (isDependentScopeSpecifier(*SS)) {
354 // C++ [temp.res]p3:
355 // A qualified-id that refers to a type and in which the
356 // nested-name-specifier depends on a template-parameter (14.6.2)
357 // shall be prefixed by the keyword typename to indicate that the
358 // qualified-id denotes a type, forming an
359 // elaborated-type-specifier (7.1.5.3).
361 // We therefore do not perform any name lookup if the result would
362 // refer to a member of an unknown specialization.
363 // In C++2a, in several contexts a 'typename' is not required. Also
364 // allow this as an extension.
365 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
366 !isClassName && !IsCtorOrDtorName)
367 return nullptr;
368 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
369 if (IsImplicitTypename) {
370 SourceLocation QualifiedLoc = SS->getRange().getBegin();
371 if (getLangOpts().CPlusPlus20)
372 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
373 else
374 Diag(QualifiedLoc, diag::ext_implicit_typename)
375 << SS->getScopeRep() << II.getName()
376 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
379 // We know from the grammar that this name refers to a type,
380 // so build a dependent node to describe the type.
381 if (WantNontrivialTypeSourceInfo)
382 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
383 (ImplicitTypenameContext)IsImplicitTypename)
384 .get();
386 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
387 QualType T = CheckTypenameType(
388 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
389 : ElaboratedTypeKeyword::None,
390 SourceLocation(), QualifierLoc, II, NameLoc);
391 return ParsedType::make(T);
394 return nullptr;
397 if (!LookupCtx->isDependentContext() &&
398 RequireCompleteDeclContext(*SS, LookupCtx))
399 return nullptr;
402 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
403 // lookup for class-names.
404 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
405 LookupOrdinaryName;
406 LookupResult Result(*this, &II, NameLoc, Kind);
407 if (LookupCtx) {
408 // Perform "qualified" name lookup into the declaration context we
409 // computed, which is either the type of the base of a member access
410 // expression or the declaration context associated with a prior
411 // nested-name-specifier.
412 LookupQualifiedName(Result, LookupCtx);
414 if (ObjectTypePtr && Result.empty()) {
415 // C++ [basic.lookup.classref]p3:
416 // If the unqualified-id is ~type-name, the type-name is looked up
417 // in the context of the entire postfix-expression. If the type T of
418 // the object expression is of a class type C, the type-name is also
419 // looked up in the scope of class C. At least one of the lookups shall
420 // find a name that refers to (possibly cv-qualified) T.
421 LookupName(Result, S);
423 } else {
424 // Perform unqualified name lookup.
425 LookupName(Result, S);
427 // For unqualified lookup in a class template in MSVC mode, look into
428 // dependent base classes where the primary class template is known.
429 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
430 if (ParsedType TypeInBase =
431 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
432 return TypeInBase;
436 NamedDecl *IIDecl = nullptr;
437 UsingShadowDecl *FoundUsingShadow = nullptr;
438 switch (Result.getResultKind()) {
439 case LookupResult::NotFound:
440 case LookupResult::NotFoundInCurrentInstantiation:
441 if (CorrectedII) {
442 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
443 AllowDeducedTemplate);
444 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
445 S, SS, CCC, CTK_ErrorRecovery);
446 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
447 TemplateTy Template;
448 bool MemberOfUnknownSpecialization;
449 UnqualifiedId TemplateName;
450 TemplateName.setIdentifier(NewII, NameLoc);
451 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
452 CXXScopeSpec NewSS, *NewSSPtr = SS;
453 if (SS && NNS) {
454 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
455 NewSSPtr = &NewSS;
457 if (Correction && (NNS || NewII != &II) &&
458 // Ignore a correction to a template type as the to-be-corrected
459 // identifier is not a template (typo correction for template names
460 // is handled elsewhere).
461 !(getLangOpts().CPlusPlus && NewSSPtr &&
462 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
463 Template, MemberOfUnknownSpecialization))) {
464 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
465 isClassName, HasTrailingDot, ObjectTypePtr,
466 IsCtorOrDtorName,
467 WantNontrivialTypeSourceInfo,
468 IsClassTemplateDeductionContext);
469 if (Ty) {
470 diagnoseTypo(Correction,
471 PDiag(diag::err_unknown_type_or_class_name_suggest)
472 << Result.getLookupName() << isClassName);
473 if (SS && NNS)
474 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
475 *CorrectedII = NewII;
476 return Ty;
480 // If typo correction failed or was not performed, fall through
481 [[fallthrough]];
482 case LookupResult::FoundOverloaded:
483 case LookupResult::FoundUnresolvedValue:
484 Result.suppressDiagnostics();
485 return nullptr;
487 case LookupResult::Ambiguous:
488 // Recover from type-hiding ambiguities by hiding the type. We'll
489 // do the lookup again when looking for an object, and we can
490 // diagnose the error then. If we don't do this, then the error
491 // about hiding the type will be immediately followed by an error
492 // that only makes sense if the identifier was treated like a type.
493 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
494 Result.suppressDiagnostics();
495 return nullptr;
498 // Look to see if we have a type anywhere in the list of results.
499 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
500 Res != ResEnd; ++Res) {
501 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
502 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
503 RealRes) ||
504 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
505 if (!IIDecl ||
506 // Make the selection of the recovery decl deterministic.
507 RealRes->getLocation() < IIDecl->getLocation()) {
508 IIDecl = RealRes;
509 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
514 if (!IIDecl) {
515 // None of the entities we found is a type, so there is no way
516 // to even assume that the result is a type. In this case, don't
517 // complain about the ambiguity. The parser will either try to
518 // perform this lookup again (e.g., as an object name), which
519 // will produce the ambiguity, or will complain that it expected
520 // a type name.
521 Result.suppressDiagnostics();
522 return nullptr;
525 // We found a type within the ambiguous lookup; diagnose the
526 // ambiguity and then return that type. This might be the right
527 // answer, or it might not be, but it suppresses any attempt to
528 // perform the name lookup again.
529 break;
531 case LookupResult::Found:
532 IIDecl = Result.getFoundDecl();
533 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
534 break;
537 assert(IIDecl && "Didn't find decl");
539 QualType T;
540 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
541 // C++ [class.qual]p2: A lookup that would find the injected-class-name
542 // instead names the constructors of the class, except when naming a class.
543 // This is ill-formed when we're not actually forming a ctor or dtor name.
544 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
545 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
546 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
547 FoundRD->isInjectedClassName() &&
548 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
549 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
550 << &II << /*Type*/1;
552 DiagnoseUseOfDecl(IIDecl, NameLoc);
554 T = Context.getTypeDeclType(TD);
555 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
556 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
557 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
558 if (!HasTrailingDot)
559 T = Context.getObjCInterfaceType(IDecl);
560 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
561 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
562 (void)DiagnoseUseOfDecl(UD, NameLoc);
563 // Recover with 'int'
564 return ParsedType::make(Context.IntTy);
565 } else if (AllowDeducedTemplate) {
566 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
567 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
568 TemplateName Template =
569 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
570 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
571 false);
572 // Don't wrap in a further UsingType.
573 FoundUsingShadow = nullptr;
577 if (T.isNull()) {
578 // If it's not plausibly a type, suppress diagnostics.
579 Result.suppressDiagnostics();
580 return nullptr;
583 if (FoundUsingShadow)
584 T = Context.getUsingType(FoundUsingShadow, T);
586 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
589 // Builds a fake NNS for the given decl context.
590 static NestedNameSpecifier *
591 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
592 for (;; DC = DC->getLookupParent()) {
593 DC = DC->getPrimaryContext();
594 auto *ND = dyn_cast<NamespaceDecl>(DC);
595 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
596 return NestedNameSpecifier::Create(Context, nullptr, ND);
597 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
598 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599 RD->getTypeForDecl());
600 else if (isa<TranslationUnitDecl>(DC))
601 return NestedNameSpecifier::GlobalSpecifier(Context);
603 llvm_unreachable("something isn't in TU scope?");
606 /// Find the parent class with dependent bases of the innermost enclosing method
607 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
608 /// up allowing unqualified dependent type names at class-level, which MSVC
609 /// correctly rejects.
610 static const CXXRecordDecl *
611 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
612 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
613 DC = DC->getPrimaryContext();
614 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
615 if (MD->getParent()->hasAnyDependentBases())
616 return MD->getParent();
618 return nullptr;
621 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
622 SourceLocation NameLoc,
623 bool IsTemplateTypeArg) {
624 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
626 NestedNameSpecifier *NNS = nullptr;
627 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
628 // If we weren't able to parse a default template argument, delay lookup
629 // until instantiation time by making a non-dependent DependentTypeName. We
630 // pretend we saw a NestedNameSpecifier referring to the current scope, and
631 // lookup is retried.
632 // FIXME: This hurts our diagnostic quality, since we get errors like "no
633 // type named 'Foo' in 'current_namespace'" when the user didn't write any
634 // name specifiers.
635 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
636 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
637 } else if (const CXXRecordDecl *RD =
638 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
639 // Build a DependentNameType that will perform lookup into RD at
640 // instantiation time.
641 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
642 RD->getTypeForDecl());
644 // Diagnose that this identifier was undeclared, and retry the lookup during
645 // template instantiation.
646 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
647 << RD;
648 } else {
649 // This is not a situation that we should recover from.
650 return ParsedType();
653 QualType T =
654 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
656 // Build type location information. We synthesized the qualifier, so we have
657 // to build a fake NestedNameSpecifierLoc.
658 NestedNameSpecifierLocBuilder NNSLocBuilder;
659 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
660 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
662 TypeLocBuilder Builder;
663 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
664 DepTL.setNameLoc(NameLoc);
665 DepTL.setElaboratedKeywordLoc(SourceLocation());
666 DepTL.setQualifierLoc(QualifierLoc);
667 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
670 /// isTagName() - This method is called *for error recovery purposes only*
671 /// to determine if the specified name is a valid tag name ("struct foo"). If
672 /// so, this returns the TST for the tag corresponding to it (TST_enum,
673 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
674 /// cases in C where the user forgot to specify the tag.
675 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
676 // Do a tag name lookup in this scope.
677 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678 LookupName(R, S, false);
679 R.suppressDiagnostics();
680 if (R.getResultKind() == LookupResult::Found)
681 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682 switch (TD->getTagKind()) {
683 case TagTypeKind::Struct:
684 return DeclSpec::TST_struct;
685 case TagTypeKind::Interface:
686 return DeclSpec::TST_interface;
687 case TagTypeKind::Union:
688 return DeclSpec::TST_union;
689 case TagTypeKind::Class:
690 return DeclSpec::TST_class;
691 case TagTypeKind::Enum:
692 return DeclSpec::TST_enum;
696 return DeclSpec::TST_unspecified;
699 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
700 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
701 /// then downgrade the missing typename error to a warning.
702 /// This is needed for MSVC compatibility; Example:
703 /// @code
704 /// template<class T> class A {
705 /// public:
706 /// typedef int TYPE;
707 /// };
708 /// template<class T> class B : public A<T> {
709 /// public:
710 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
711 /// };
712 /// @endcode
713 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714 if (CurContext->isRecord()) {
715 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
716 return true;
718 const Type *Ty = SS->getScopeRep()->getAsType();
720 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
721 for (const auto &Base : RD->bases())
722 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
723 return true;
724 return S->isFunctionPrototypeScope();
726 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
729 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
730 SourceLocation IILoc,
731 Scope *S,
732 CXXScopeSpec *SS,
733 ParsedType &SuggestedType,
734 bool IsTemplateName) {
735 // Don't report typename errors for editor placeholders.
736 if (II->isEditorPlaceholder())
737 return;
738 // We don't have anything to suggest (yet).
739 SuggestedType = nullptr;
741 // There may have been a typo in the name of the type. Look up typo
742 // results, in case we have something that we can suggest.
743 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
744 /*AllowTemplates=*/IsTemplateName,
745 /*AllowNonTemplates=*/!IsTemplateName);
746 if (TypoCorrection Corrected =
747 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
748 CCC, CTK_ErrorRecovery)) {
749 // FIXME: Support error recovery for the template-name case.
750 bool CanRecover = !IsTemplateName;
751 if (Corrected.isKeyword()) {
752 // We corrected to a keyword.
753 diagnoseTypo(Corrected,
754 PDiag(IsTemplateName ? diag::err_no_template_suggest
755 : diag::err_unknown_typename_suggest)
756 << II);
757 II = Corrected.getCorrectionAsIdentifierInfo();
758 } else {
759 // We found a similarly-named type or interface; suggest that.
760 if (!SS || !SS->isSet()) {
761 diagnoseTypo(Corrected,
762 PDiag(IsTemplateName ? diag::err_no_template_suggest
763 : diag::err_unknown_typename_suggest)
764 << II, CanRecover);
765 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
766 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
767 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
768 II->getName().equals(CorrectedStr);
769 diagnoseTypo(Corrected,
770 PDiag(IsTemplateName
771 ? diag::err_no_member_template_suggest
772 : diag::err_unknown_nested_typename_suggest)
773 << II << DC << DroppedSpecifier << SS->getRange(),
774 CanRecover);
775 } else {
776 llvm_unreachable("could not have corrected a typo here");
779 if (!CanRecover)
780 return;
782 CXXScopeSpec tmpSS;
783 if (Corrected.getCorrectionSpecifier())
784 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
785 SourceRange(IILoc));
786 // FIXME: Support class template argument deduction here.
787 SuggestedType =
788 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
789 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
790 /*IsCtorOrDtorName=*/false,
791 /*WantNontrivialTypeSourceInfo=*/true);
793 return;
796 if (getLangOpts().CPlusPlus && !IsTemplateName) {
797 // See if II is a class template that the user forgot to pass arguments to.
798 UnqualifiedId Name;
799 Name.setIdentifier(II, IILoc);
800 CXXScopeSpec EmptySS;
801 TemplateTy TemplateResult;
802 bool MemberOfUnknownSpecialization;
803 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
804 Name, nullptr, true, TemplateResult,
805 MemberOfUnknownSpecialization) == TNK_Type_template) {
806 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
807 return;
811 // FIXME: Should we move the logic that tries to recover from a missing tag
812 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
814 if (!SS || (!SS->isSet() && !SS->isInvalid()))
815 Diag(IILoc, IsTemplateName ? diag::err_no_template
816 : diag::err_unknown_typename)
817 << II;
818 else if (DeclContext *DC = computeDeclContext(*SS, false))
819 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
820 : diag::err_typename_nested_not_found)
821 << II << DC << SS->getRange();
822 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
823 SuggestedType =
824 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
825 } else if (isDependentScopeSpecifier(*SS)) {
826 unsigned DiagID = diag::err_typename_missing;
827 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
828 DiagID = diag::ext_typename_missing;
830 Diag(SS->getRange().getBegin(), DiagID)
831 << SS->getScopeRep() << II->getName()
832 << SourceRange(SS->getRange().getBegin(), IILoc)
833 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
834 SuggestedType = ActOnTypenameType(S, SourceLocation(),
835 *SS, *II, IILoc).get();
836 } else {
837 assert(SS && SS->isInvalid() &&
838 "Invalid scope specifier has already been diagnosed");
842 /// Determine whether the given result set contains either a type name
843 /// or
844 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
845 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
846 NextToken.is(tok::less);
848 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
849 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
850 return true;
852 if (CheckTemplate && isa<TemplateDecl>(*I))
853 return true;
856 return false;
859 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
860 Scope *S, CXXScopeSpec &SS,
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc) {
863 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
864 SemaRef.LookupParsedName(R, S, &SS);
865 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
866 StringRef FixItTagName;
867 switch (Tag->getTagKind()) {
868 case TagTypeKind::Class:
869 FixItTagName = "class ";
870 break;
872 case TagTypeKind::Enum:
873 FixItTagName = "enum ";
874 break;
876 case TagTypeKind::Struct:
877 FixItTagName = "struct ";
878 break;
880 case TagTypeKind::Interface:
881 FixItTagName = "__interface ";
882 break;
884 case TagTypeKind::Union:
885 FixItTagName = "union ";
886 break;
889 StringRef TagName = FixItTagName.drop_back();
890 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
891 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
892 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
894 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
895 I != IEnd; ++I)
896 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
897 << Name << TagName;
899 // Replace lookup results with just the tag decl.
900 Result.clear(Sema::LookupTagName);
901 SemaRef.LookupParsedName(Result, S, &SS);
902 return true;
905 return false;
908 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
909 IdentifierInfo *&Name,
910 SourceLocation NameLoc,
911 const Token &NextToken,
912 CorrectionCandidateCallback *CCC) {
913 DeclarationNameInfo NameInfo(Name, NameLoc);
914 ObjCMethodDecl *CurMethod = getCurMethodDecl();
916 assert(NextToken.isNot(tok::coloncolon) &&
917 "parse nested name specifiers before calling ClassifyName");
918 if (getLangOpts().CPlusPlus && SS.isSet() &&
919 isCurrentClassName(*Name, S, &SS)) {
920 // Per [class.qual]p2, this names the constructors of SS, not the
921 // injected-class-name. We don't have a classification for that.
922 // There's not much point caching this result, since the parser
923 // will reject it later.
924 return NameClassification::Unknown();
927 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
928 LookupParsedName(Result, S, &SS, !CurMethod);
930 if (SS.isInvalid())
931 return NameClassification::Error();
933 // For unqualified lookup in a class template in MSVC mode, look into
934 // dependent base classes where the primary class template is known.
935 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
936 if (ParsedType TypeInBase =
937 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
938 return TypeInBase;
941 // Perform lookup for Objective-C instance variables (including automatically
942 // synthesized instance variables), if we're in an Objective-C method.
943 // FIXME: This lookup really, really needs to be folded in to the normal
944 // unqualified lookup mechanism.
945 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
946 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
947 if (Ivar.isInvalid())
948 return NameClassification::Error();
949 if (Ivar.isUsable())
950 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
952 // We defer builtin creation until after ivar lookup inside ObjC methods.
953 if (Result.empty())
954 LookupBuiltin(Result);
957 bool SecondTry = false;
958 bool IsFilteredTemplateName = false;
960 Corrected:
961 switch (Result.getResultKind()) {
962 case LookupResult::NotFound:
963 // If an unqualified-id is followed by a '(', then we have a function
964 // call.
965 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
966 // In C++, this is an ADL-only call.
967 // FIXME: Reference?
968 if (getLangOpts().CPlusPlus)
969 return NameClassification::UndeclaredNonType();
971 // C90 6.3.2.2:
972 // If the expression that precedes the parenthesized argument list in a
973 // function call consists solely of an identifier, and if no
974 // declaration is visible for this identifier, the identifier is
975 // implicitly declared exactly as if, in the innermost block containing
976 // the function call, the declaration
978 // extern int identifier ();
980 // appeared.
982 // We also allow this in C99 as an extension. However, this is not
983 // allowed in all language modes as functions without prototypes may not
984 // be supported.
985 if (getLangOpts().implicitFunctionsAllowed()) {
986 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
987 return NameClassification::NonType(D);
991 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
992 // In C++20 onwards, this could be an ADL-only call to a function
993 // template, and we're required to assume that this is a template name.
995 // FIXME: Find a way to still do typo correction in this case.
996 TemplateName Template =
997 Context.getAssumedTemplateName(NameInfo.getName());
998 return NameClassification::UndeclaredTemplate(Template);
1001 // In C, we first see whether there is a tag type by the same name, in
1002 // which case it's likely that the user just forgot to write "enum",
1003 // "struct", or "union".
1004 if (!getLangOpts().CPlusPlus && !SecondTry &&
1005 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1006 break;
1009 // Perform typo correction to determine if there is another name that is
1010 // close to this name.
1011 if (!SecondTry && CCC) {
1012 SecondTry = true;
1013 if (TypoCorrection Corrected =
1014 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1015 &SS, *CCC, CTK_ErrorRecovery)) {
1016 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1017 unsigned QualifiedDiag = diag::err_no_member_suggest;
1019 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1020 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1022 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1023 UnqualifiedDiag = diag::err_no_template_suggest;
1024 QualifiedDiag = diag::err_no_member_template_suggest;
1025 } else if (UnderlyingFirstDecl &&
1026 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1027 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1028 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1029 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1030 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1033 if (SS.isEmpty()) {
1034 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1035 } else {// FIXME: is this even reachable? Test it.
1036 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1037 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1038 Name->getName().equals(CorrectedStr);
1039 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1040 << Name << computeDeclContext(SS, false)
1041 << DroppedSpecifier << SS.getRange());
1044 // Update the name, so that the caller has the new name.
1045 Name = Corrected.getCorrectionAsIdentifierInfo();
1047 // Typo correction corrected to a keyword.
1048 if (Corrected.isKeyword())
1049 return Name;
1051 // Also update the LookupResult...
1052 // FIXME: This should probably go away at some point
1053 Result.clear();
1054 Result.setLookupName(Corrected.getCorrection());
1055 if (FirstDecl)
1056 Result.addDecl(FirstDecl);
1058 // If we found an Objective-C instance variable, let
1059 // LookupInObjCMethod build the appropriate expression to
1060 // reference the ivar.
1061 // FIXME: This is a gross hack.
1062 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1063 DeclResult R =
1064 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1065 if (R.isInvalid())
1066 return NameClassification::Error();
1067 if (R.isUsable())
1068 return NameClassification::NonType(Ivar);
1071 goto Corrected;
1075 // We failed to correct; just fall through and let the parser deal with it.
1076 Result.suppressDiagnostics();
1077 return NameClassification::Unknown();
1079 case LookupResult::NotFoundInCurrentInstantiation: {
1080 // We performed name lookup into the current instantiation, and there were
1081 // dependent bases, so we treat this result the same way as any other
1082 // dependent nested-name-specifier.
1084 // C++ [temp.res]p2:
1085 // A name used in a template declaration or definition and that is
1086 // dependent on a template-parameter is assumed not to name a type
1087 // unless the applicable name lookup finds a type name or the name is
1088 // qualified by the keyword typename.
1090 // FIXME: If the next token is '<', we might want to ask the parser to
1091 // perform some heroics to see if we actually have a
1092 // template-argument-list, which would indicate a missing 'template'
1093 // keyword here.
1094 return NameClassification::DependentNonType();
1097 case LookupResult::Found:
1098 case LookupResult::FoundOverloaded:
1099 case LookupResult::FoundUnresolvedValue:
1100 break;
1102 case LookupResult::Ambiguous:
1103 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1104 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1105 /*AllowDependent=*/false)) {
1106 // C++ [temp.local]p3:
1107 // A lookup that finds an injected-class-name (10.2) can result in an
1108 // ambiguity in certain cases (for example, if it is found in more than
1109 // one base class). If all of the injected-class-names that are found
1110 // refer to specializations of the same class template, and if the name
1111 // is followed by a template-argument-list, the reference refers to the
1112 // class template itself and not a specialization thereof, and is not
1113 // ambiguous.
1115 // This filtering can make an ambiguous result into an unambiguous one,
1116 // so try again after filtering out template names.
1117 FilterAcceptableTemplateNames(Result);
1118 if (!Result.isAmbiguous()) {
1119 IsFilteredTemplateName = true;
1120 break;
1124 // Diagnose the ambiguity and return an error.
1125 return NameClassification::Error();
1128 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1129 (IsFilteredTemplateName ||
1130 hasAnyAcceptableTemplateNames(
1131 Result, /*AllowFunctionTemplates=*/true,
1132 /*AllowDependent=*/false,
1133 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1134 getLangOpts().CPlusPlus20))) {
1135 // C++ [temp.names]p3:
1136 // After name lookup (3.4) finds that a name is a template-name or that
1137 // an operator-function-id or a literal- operator-id refers to a set of
1138 // overloaded functions any member of which is a function template if
1139 // this is followed by a <, the < is always taken as the delimiter of a
1140 // template-argument-list and never as the less-than operator.
1141 // C++2a [temp.names]p2:
1142 // A name is also considered to refer to a template if it is an
1143 // unqualified-id followed by a < and name lookup finds either one
1144 // or more functions or finds nothing.
1145 if (!IsFilteredTemplateName)
1146 FilterAcceptableTemplateNames(Result);
1148 bool IsFunctionTemplate;
1149 bool IsVarTemplate;
1150 TemplateName Template;
1151 if (Result.end() - Result.begin() > 1) {
1152 IsFunctionTemplate = true;
1153 Template = Context.getOverloadedTemplateName(Result.begin(),
1154 Result.end());
1155 } else if (!Result.empty()) {
1156 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1157 *Result.begin(), /*AllowFunctionTemplates=*/true,
1158 /*AllowDependent=*/false));
1159 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1160 IsVarTemplate = isa<VarTemplateDecl>(TD);
1162 UsingShadowDecl *FoundUsingShadow =
1163 dyn_cast<UsingShadowDecl>(*Result.begin());
1164 assert(!FoundUsingShadow ||
1165 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1166 Template =
1167 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1168 if (SS.isNotEmpty())
1169 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1170 /*TemplateKeyword=*/false,
1171 Template);
1172 } else {
1173 // All results were non-template functions. This is a function template
1174 // name.
1175 IsFunctionTemplate = true;
1176 Template = Context.getAssumedTemplateName(NameInfo.getName());
1179 if (IsFunctionTemplate) {
1180 // Function templates always go through overload resolution, at which
1181 // point we'll perform the various checks (e.g., accessibility) we need
1182 // to based on which function we selected.
1183 Result.suppressDiagnostics();
1185 return NameClassification::FunctionTemplate(Template);
1188 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1189 : NameClassification::TypeTemplate(Template);
1192 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1193 QualType T = Context.getTypeDeclType(Type);
1194 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1195 T = Context.getUsingType(USD, T);
1196 return buildNamedType(*this, &SS, T, NameLoc);
1199 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1200 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1201 DiagnoseUseOfDecl(Type, NameLoc);
1202 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1203 return BuildTypeFor(Type, *Result.begin());
1206 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1207 if (!Class) {
1208 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1209 if (ObjCCompatibleAliasDecl *Alias =
1210 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1211 Class = Alias->getClassInterface();
1214 if (Class) {
1215 DiagnoseUseOfDecl(Class, NameLoc);
1217 if (NextToken.is(tok::period)) {
1218 // Interface. <something> is parsed as a property reference expression.
1219 // Just return "unknown" as a fall-through for now.
1220 Result.suppressDiagnostics();
1221 return NameClassification::Unknown();
1224 QualType T = Context.getObjCInterfaceType(Class);
1225 return ParsedType::make(T);
1228 if (isa<ConceptDecl>(FirstDecl))
1229 return NameClassification::Concept(
1230 TemplateName(cast<TemplateDecl>(FirstDecl)));
1232 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1233 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1234 return NameClassification::Error();
1237 // We can have a type template here if we're classifying a template argument.
1238 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1239 !isa<VarTemplateDecl>(FirstDecl))
1240 return NameClassification::TypeTemplate(
1241 TemplateName(cast<TemplateDecl>(FirstDecl)));
1243 // Check for a tag type hidden by a non-type decl in a few cases where it
1244 // seems likely a type is wanted instead of the non-type that was found.
1245 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1246 if ((NextToken.is(tok::identifier) ||
1247 (NextIsOp &&
1248 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1249 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1250 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1251 DiagnoseUseOfDecl(Type, NameLoc);
1252 return BuildTypeFor(Type, *Result.begin());
1255 // If we already know which single declaration is referenced, just annotate
1256 // that declaration directly. Defer resolving even non-overloaded class
1257 // member accesses, as we need to defer certain access checks until we know
1258 // the context.
1259 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1260 if (Result.isSingleResult() && !ADL &&
1261 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1262 return NameClassification::NonType(Result.getRepresentativeDecl());
1264 // Otherwise, this is an overload set that we will need to resolve later.
1265 Result.suppressDiagnostics();
1266 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1267 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1268 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1269 Result.begin(), Result.end()));
1272 ExprResult
1273 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1274 SourceLocation NameLoc) {
1275 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1276 CXXScopeSpec SS;
1277 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1278 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1281 ExprResult
1282 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1283 IdentifierInfo *Name,
1284 SourceLocation NameLoc,
1285 bool IsAddressOfOperand) {
1286 DeclarationNameInfo NameInfo(Name, NameLoc);
1287 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1288 NameInfo, IsAddressOfOperand,
1289 /*TemplateArgs=*/nullptr);
1292 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1293 NamedDecl *Found,
1294 SourceLocation NameLoc,
1295 const Token &NextToken) {
1296 if (getCurMethodDecl() && SS.isEmpty())
1297 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1298 return BuildIvarRefExpr(S, NameLoc, Ivar);
1300 // Reconstruct the lookup result.
1301 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1302 Result.addDecl(Found);
1303 Result.resolveKind();
1305 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1306 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1309 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1310 // For an implicit class member access, transform the result into a member
1311 // access expression if necessary.
1312 auto *ULE = cast<UnresolvedLookupExpr>(E);
1313 if ((*ULE->decls_begin())->isCXXClassMember()) {
1314 CXXScopeSpec SS;
1315 SS.Adopt(ULE->getQualifierLoc());
1317 // Reconstruct the lookup result.
1318 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1319 LookupOrdinaryName);
1320 Result.setNamingClass(ULE->getNamingClass());
1321 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1322 Result.addDecl(*I, I.getAccess());
1323 Result.resolveKind();
1324 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1325 nullptr, S);
1328 // Otherwise, this is already in the form we needed, and no further checks
1329 // are necessary.
1330 return ULE;
1333 Sema::TemplateNameKindForDiagnostics
1334 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1335 auto *TD = Name.getAsTemplateDecl();
1336 if (!TD)
1337 return TemplateNameKindForDiagnostics::DependentTemplate;
1338 if (isa<ClassTemplateDecl>(TD))
1339 return TemplateNameKindForDiagnostics::ClassTemplate;
1340 if (isa<FunctionTemplateDecl>(TD))
1341 return TemplateNameKindForDiagnostics::FunctionTemplate;
1342 if (isa<VarTemplateDecl>(TD))
1343 return TemplateNameKindForDiagnostics::VarTemplate;
1344 if (isa<TypeAliasTemplateDecl>(TD))
1345 return TemplateNameKindForDiagnostics::AliasTemplate;
1346 if (isa<TemplateTemplateParmDecl>(TD))
1347 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1348 if (isa<ConceptDecl>(TD))
1349 return TemplateNameKindForDiagnostics::Concept;
1350 return TemplateNameKindForDiagnostics::DependentTemplate;
1353 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1354 assert(DC->getLexicalParent() == CurContext &&
1355 "The next DeclContext should be lexically contained in the current one.");
1356 CurContext = DC;
1357 S->setEntity(DC);
1360 void Sema::PopDeclContext() {
1361 assert(CurContext && "DeclContext imbalance!");
1363 CurContext = CurContext->getLexicalParent();
1364 assert(CurContext && "Popped translation unit!");
1367 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1368 Decl *D) {
1369 // Unlike PushDeclContext, the context to which we return is not necessarily
1370 // the containing DC of TD, because the new context will be some pre-existing
1371 // TagDecl definition instead of a fresh one.
1372 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1373 CurContext = cast<TagDecl>(D)->getDefinition();
1374 assert(CurContext && "skipping definition of undefined tag");
1375 // Start lookups from the parent of the current context; we don't want to look
1376 // into the pre-existing complete definition.
1377 S->setEntity(CurContext->getLookupParent());
1378 return Result;
1381 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1382 CurContext = static_cast<decltype(CurContext)>(Context);
1385 /// EnterDeclaratorContext - Used when we must lookup names in the context
1386 /// of a declarator's nested name specifier.
1388 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1389 // C++0x [basic.lookup.unqual]p13:
1390 // A name used in the definition of a static data member of class
1391 // X (after the qualified-id of the static member) is looked up as
1392 // if the name was used in a member function of X.
1393 // C++0x [basic.lookup.unqual]p14:
1394 // If a variable member of a namespace is defined outside of the
1395 // scope of its namespace then any name used in the definition of
1396 // the variable member (after the declarator-id) is looked up as
1397 // if the definition of the variable member occurred in its
1398 // namespace.
1399 // Both of these imply that we should push a scope whose context
1400 // is the semantic context of the declaration. We can't use
1401 // PushDeclContext here because that context is not necessarily
1402 // lexically contained in the current context. Fortunately,
1403 // the containing scope should have the appropriate information.
1405 assert(!S->getEntity() && "scope already has entity");
1407 #ifndef NDEBUG
1408 Scope *Ancestor = S->getParent();
1409 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1410 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1411 #endif
1413 CurContext = DC;
1414 S->setEntity(DC);
1416 if (S->getParent()->isTemplateParamScope()) {
1417 // Also set the corresponding entities for all immediately-enclosing
1418 // template parameter scopes.
1419 EnterTemplatedContext(S->getParent(), DC);
1423 void Sema::ExitDeclaratorContext(Scope *S) {
1424 assert(S->getEntity() == CurContext && "Context imbalance!");
1426 // Switch back to the lexical context. The safety of this is
1427 // enforced by an assert in EnterDeclaratorContext.
1428 Scope *Ancestor = S->getParent();
1429 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1430 CurContext = Ancestor->getEntity();
1432 // We don't need to do anything with the scope, which is going to
1433 // disappear.
1436 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1437 assert(S->isTemplateParamScope() &&
1438 "expected to be initializing a template parameter scope");
1440 // C++20 [temp.local]p7:
1441 // In the definition of a member of a class template that appears outside
1442 // of the class template definition, the name of a member of the class
1443 // template hides the name of a template-parameter of any enclosing class
1444 // templates (but not a template-parameter of the member if the member is a
1445 // class or function template).
1446 // C++20 [temp.local]p9:
1447 // In the definition of a class template or in the definition of a member
1448 // of such a template that appears outside of the template definition, for
1449 // each non-dependent base class (13.8.2.1), if the name of the base class
1450 // or the name of a member of the base class is the same as the name of a
1451 // template-parameter, the base class name or member name hides the
1452 // template-parameter name (6.4.10).
1454 // This means that a template parameter scope should be searched immediately
1455 // after searching the DeclContext for which it is a template parameter
1456 // scope. For example, for
1457 // template<typename T> template<typename U> template<typename V>
1458 // void N::A<T>::B<U>::f(...)
1459 // we search V then B<U> (and base classes) then U then A<T> (and base
1460 // classes) then T then N then ::.
1461 unsigned ScopeDepth = getTemplateDepth(S);
1462 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1463 DeclContext *SearchDCAfterScope = DC;
1464 for (; DC; DC = DC->getLookupParent()) {
1465 if (const TemplateParameterList *TPL =
1466 cast<Decl>(DC)->getDescribedTemplateParams()) {
1467 unsigned DCDepth = TPL->getDepth() + 1;
1468 if (DCDepth > ScopeDepth)
1469 continue;
1470 if (ScopeDepth == DCDepth)
1471 SearchDCAfterScope = DC = DC->getLookupParent();
1472 break;
1475 S->setLookupEntity(SearchDCAfterScope);
1479 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1480 // We assume that the caller has already called
1481 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1482 FunctionDecl *FD = D->getAsFunction();
1483 if (!FD)
1484 return;
1486 // Same implementation as PushDeclContext, but enters the context
1487 // from the lexical parent, rather than the top-level class.
1488 assert(CurContext == FD->getLexicalParent() &&
1489 "The next DeclContext should be lexically contained in the current one.");
1490 CurContext = FD;
1491 S->setEntity(CurContext);
1493 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1494 ParmVarDecl *Param = FD->getParamDecl(P);
1495 // If the parameter has an identifier, then add it to the scope
1496 if (Param->getIdentifier()) {
1497 S->AddDecl(Param);
1498 IdResolver.AddDecl(Param);
1503 void Sema::ActOnExitFunctionContext() {
1504 // Same implementation as PopDeclContext, but returns to the lexical parent,
1505 // rather than the top-level class.
1506 assert(CurContext && "DeclContext imbalance!");
1507 CurContext = CurContext->getLexicalParent();
1508 assert(CurContext && "Popped translation unit!");
1511 /// Determine whether overloading is allowed for a new function
1512 /// declaration considering prior declarations of the same name.
1514 /// This routine determines whether overloading is possible, not
1515 /// whether a new declaration actually overloads a previous one.
1516 /// It will return true in C++ (where overloads are alway permitted)
1517 /// or, as a C extension, when either the new declaration or a
1518 /// previous one is declared with the 'overloadable' attribute.
1519 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1520 ASTContext &Context,
1521 const FunctionDecl *New) {
1522 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1523 return true;
1525 // Multiversion function declarations are not overloads in the
1526 // usual sense of that term, but lookup will report that an
1527 // overload set was found if more than one multiversion function
1528 // declaration is present for the same name. It is therefore
1529 // inadequate to assume that some prior declaration(s) had
1530 // the overloadable attribute; checking is required. Since one
1531 // declaration is permitted to omit the attribute, it is necessary
1532 // to check at least two; hence the 'any_of' check below. Note that
1533 // the overloadable attribute is implicitly added to declarations
1534 // that were required to have it but did not.
1535 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1536 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1537 return ND->hasAttr<OverloadableAttr>();
1539 } else if (Previous.getResultKind() == LookupResult::Found)
1540 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1542 return false;
1545 /// Add this decl to the scope shadowed decl chains.
1546 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1547 // Move up the scope chain until we find the nearest enclosing
1548 // non-transparent context. The declaration will be introduced into this
1549 // scope.
1550 while (S->getEntity() && S->getEntity()->isTransparentContext())
1551 S = S->getParent();
1553 // Add scoped declarations into their context, so that they can be
1554 // found later. Declarations without a context won't be inserted
1555 // into any context.
1556 if (AddToContext)
1557 CurContext->addDecl(D);
1559 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1560 // are function-local declarations.
1561 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1562 return;
1564 // Template instantiations should also not be pushed into scope.
1565 if (isa<FunctionDecl>(D) &&
1566 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1567 return;
1569 // If this replaces anything in the current scope,
1570 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1571 IEnd = IdResolver.end();
1572 for (; I != IEnd; ++I) {
1573 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1574 S->RemoveDecl(*I);
1575 IdResolver.RemoveDecl(*I);
1577 // Should only need to replace one decl.
1578 break;
1582 S->AddDecl(D);
1584 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1585 // Implicitly-generated labels may end up getting generated in an order that
1586 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1587 // the label at the appropriate place in the identifier chain.
1588 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1589 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1590 if (IDC == CurContext) {
1591 if (!S->isDeclScope(*I))
1592 continue;
1593 } else if (IDC->Encloses(CurContext))
1594 break;
1597 IdResolver.InsertDeclAfter(I, D);
1598 } else {
1599 IdResolver.AddDecl(D);
1601 warnOnReservedIdentifier(D);
1604 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1605 bool AllowInlineNamespace) const {
1606 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1609 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1610 DeclContext *TargetDC = DC->getPrimaryContext();
1611 do {
1612 if (DeclContext *ScopeDC = S->getEntity())
1613 if (ScopeDC->getPrimaryContext() == TargetDC)
1614 return S;
1615 } while ((S = S->getParent()));
1617 return nullptr;
1620 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1621 DeclContext*,
1622 ASTContext&);
1624 /// Filters out lookup results that don't fall within the given scope
1625 /// as determined by isDeclInScope.
1626 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1627 bool ConsiderLinkage,
1628 bool AllowInlineNamespace) {
1629 LookupResult::Filter F = R.makeFilter();
1630 while (F.hasNext()) {
1631 NamedDecl *D = F.next();
1633 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1634 continue;
1636 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1637 continue;
1639 F.erase();
1642 F.done();
1645 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1646 /// have compatible owning modules.
1647 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1648 // [module.interface]p7:
1649 // A declaration is attached to a module as follows:
1650 // - If the declaration is a non-dependent friend declaration that nominates a
1651 // function with a declarator-id that is a qualified-id or template-id or that
1652 // nominates a class other than with an elaborated-type-specifier with neither
1653 // a nested-name-specifier nor a simple-template-id, it is attached to the
1654 // module to which the friend is attached ([basic.link]).
1655 if (New->getFriendObjectKind() &&
1656 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1657 New->setLocalOwningModule(Old->getOwningModule());
1658 makeMergedDefinitionVisible(New);
1659 return false;
1662 Module *NewM = New->getOwningModule();
1663 Module *OldM = Old->getOwningModule();
1665 if (NewM && NewM->isPrivateModule())
1666 NewM = NewM->Parent;
1667 if (OldM && OldM->isPrivateModule())
1668 OldM = OldM->Parent;
1670 if (NewM == OldM)
1671 return false;
1673 if (NewM && OldM) {
1674 // A module implementation unit has visibility of the decls in its
1675 // implicitly imported interface.
1676 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1677 return false;
1679 // Partitions are part of the module, but a partition could import another
1680 // module, so verify that the PMIs agree.
1681 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1682 NewM->getPrimaryModuleInterfaceName() ==
1683 OldM->getPrimaryModuleInterfaceName())
1684 return false;
1687 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1688 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1689 if (NewIsModuleInterface || OldIsModuleInterface) {
1690 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1691 // if a declaration of D [...] appears in the purview of a module, all
1692 // other such declarations shall appear in the purview of the same module
1693 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1694 << New
1695 << NewIsModuleInterface
1696 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1697 << OldIsModuleInterface
1698 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1699 Diag(Old->getLocation(), diag::note_previous_declaration);
1700 New->setInvalidDecl();
1701 return true;
1704 return false;
1707 // [module.interface]p6:
1708 // A redeclaration of an entity X is implicitly exported if X was introduced by
1709 // an exported declaration; otherwise it shall not be exported.
1710 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1711 // [module.interface]p1:
1712 // An export-declaration shall inhabit a namespace scope.
1714 // So it is meaningless to talk about redeclaration which is not at namespace
1715 // scope.
1716 if (!New->getLexicalDeclContext()
1717 ->getNonTransparentContext()
1718 ->isFileContext() ||
1719 !Old->getLexicalDeclContext()
1720 ->getNonTransparentContext()
1721 ->isFileContext())
1722 return false;
1724 bool IsNewExported = New->isInExportDeclContext();
1725 bool IsOldExported = Old->isInExportDeclContext();
1727 // It should be irrevelant if both of them are not exported.
1728 if (!IsNewExported && !IsOldExported)
1729 return false;
1731 if (IsOldExported)
1732 return false;
1734 assert(IsNewExported);
1736 auto Lk = Old->getFormalLinkage();
1737 int S = 0;
1738 if (Lk == Linkage::Internal)
1739 S = 1;
1740 else if (Lk == Linkage::Module)
1741 S = 2;
1742 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1743 Diag(Old->getLocation(), diag::note_previous_declaration);
1744 return true;
1747 // A wrapper function for checking the semantic restrictions of
1748 // a redeclaration within a module.
1749 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1750 if (CheckRedeclarationModuleOwnership(New, Old))
1751 return true;
1753 if (CheckRedeclarationExported(New, Old))
1754 return true;
1756 return false;
1759 // Check the redefinition in C++20 Modules.
1761 // [basic.def.odr]p14:
1762 // For any definable item D with definitions in multiple translation units,
1763 // - if D is a non-inline non-templated function or variable, or
1764 // - if the definitions in different translation units do not satisfy the
1765 // following requirements,
1766 // the program is ill-formed; a diagnostic is required only if the definable
1767 // item is attached to a named module and a prior definition is reachable at
1768 // the point where a later definition occurs.
1769 // - Each such definition shall not be attached to a named module
1770 // ([module.unit]).
1771 // - Each such definition shall consist of the same sequence of tokens, ...
1772 // ...
1774 // Return true if the redefinition is not allowed. Return false otherwise.
1775 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1776 const NamedDecl *Old) const {
1777 assert(getASTContext().isSameEntity(New, Old) &&
1778 "New and Old are not the same definition, we should diagnostic it "
1779 "immediately instead of checking it.");
1780 assert(const_cast<Sema *>(this)->isReachable(New) &&
1781 const_cast<Sema *>(this)->isReachable(Old) &&
1782 "We shouldn't see unreachable definitions here.");
1784 Module *NewM = New->getOwningModule();
1785 Module *OldM = Old->getOwningModule();
1787 // We only checks for named modules here. The header like modules is skipped.
1788 // FIXME: This is not right if we import the header like modules in the module
1789 // purview.
1791 // For example, assuming "header.h" provides definition for `D`.
1792 // ```C++
1793 // //--- M.cppm
1794 // export module M;
1795 // import "header.h"; // or #include "header.h" but import it by clang modules
1796 // actually.
1798 // //--- Use.cpp
1799 // import M;
1800 // import "header.h"; // or uses clang modules.
1801 // ```
1803 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1804 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1805 // reject it. But the current implementation couldn't detect the case since we
1806 // don't record the information about the importee modules.
1808 // But this might not be painful in practice. Since the design of C++20 Named
1809 // Modules suggests us to use headers in global module fragment instead of
1810 // module purview.
1811 if (NewM && NewM->isHeaderLikeModule())
1812 NewM = nullptr;
1813 if (OldM && OldM->isHeaderLikeModule())
1814 OldM = nullptr;
1816 if (!NewM && !OldM)
1817 return true;
1819 // [basic.def.odr]p14.3
1820 // Each such definition shall not be attached to a named module
1821 // ([module.unit]).
1822 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1823 return true;
1825 // Then New and Old lives in the same TU if their share one same module unit.
1826 if (NewM)
1827 NewM = NewM->getTopLevelModule();
1828 if (OldM)
1829 OldM = OldM->getTopLevelModule();
1830 return OldM == NewM;
1833 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1834 if (D->getDeclContext()->isFileContext())
1835 return false;
1837 return isa<UsingShadowDecl>(D) ||
1838 isa<UnresolvedUsingTypenameDecl>(D) ||
1839 isa<UnresolvedUsingValueDecl>(D);
1842 /// Removes using shadow declarations not at class scope from the lookup
1843 /// results.
1844 static void RemoveUsingDecls(LookupResult &R) {
1845 LookupResult::Filter F = R.makeFilter();
1846 while (F.hasNext())
1847 if (isUsingDeclNotAtClassScope(F.next()))
1848 F.erase();
1850 F.done();
1853 /// Check for this common pattern:
1854 /// @code
1855 /// class S {
1856 /// S(const S&); // DO NOT IMPLEMENT
1857 /// void operator=(const S&); // DO NOT IMPLEMENT
1858 /// };
1859 /// @endcode
1860 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1861 // FIXME: Should check for private access too but access is set after we get
1862 // the decl here.
1863 if (D->doesThisDeclarationHaveABody())
1864 return false;
1866 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1867 return CD->isCopyConstructor();
1868 return D->isCopyAssignmentOperator();
1871 // We need this to handle
1873 // typedef struct {
1874 // void *foo() { return 0; }
1875 // } A;
1877 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1878 // for example. If 'A', foo will have external linkage. If we have '*A',
1879 // foo will have no linkage. Since we can't know until we get to the end
1880 // of the typedef, this function finds out if D might have non-external linkage.
1881 // Callers should verify at the end of the TU if it D has external linkage or
1882 // not.
1883 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1884 const DeclContext *DC = D->getDeclContext();
1885 while (!DC->isTranslationUnit()) {
1886 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1887 if (!RD->hasNameForLinkage())
1888 return true;
1890 DC = DC->getParent();
1893 return !D->isExternallyVisible();
1896 // FIXME: This needs to be refactored; some other isInMainFile users want
1897 // these semantics.
1898 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1899 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1900 return false;
1901 return S.SourceMgr.isInMainFile(Loc);
1904 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1905 assert(D);
1907 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1908 return false;
1910 // Ignore all entities declared within templates, and out-of-line definitions
1911 // of members of class templates.
1912 if (D->getDeclContext()->isDependentContext() ||
1913 D->getLexicalDeclContext()->isDependentContext())
1914 return false;
1916 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1917 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1918 return false;
1919 // A non-out-of-line declaration of a member specialization was implicitly
1920 // instantiated; it's the out-of-line declaration that we're interested in.
1921 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1922 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1923 return false;
1925 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1926 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1927 return false;
1928 } else {
1929 // 'static inline' functions are defined in headers; don't warn.
1930 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1931 return false;
1934 if (FD->doesThisDeclarationHaveABody() &&
1935 Context.DeclMustBeEmitted(FD))
1936 return false;
1937 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1938 // Constants and utility variables are defined in headers with internal
1939 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1940 // like "inline".)
1941 if (!isMainFileLoc(*this, VD->getLocation()))
1942 return false;
1944 if (Context.DeclMustBeEmitted(VD))
1945 return false;
1947 if (VD->isStaticDataMember() &&
1948 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1949 return false;
1950 if (VD->isStaticDataMember() &&
1951 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1952 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1953 return false;
1955 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1956 return false;
1957 } else {
1958 return false;
1961 // Only warn for unused decls internal to the translation unit.
1962 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1963 // for inline functions defined in the main source file, for instance.
1964 return mightHaveNonExternalLinkage(D);
1967 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1968 if (!D)
1969 return;
1971 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1972 const FunctionDecl *First = FD->getFirstDecl();
1973 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1974 return; // First should already be in the vector.
1977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1978 const VarDecl *First = VD->getFirstDecl();
1979 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1980 return; // First should already be in the vector.
1983 if (ShouldWarnIfUnusedFileScopedDecl(D))
1984 UnusedFileScopedDecls.push_back(D);
1987 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1988 const NamedDecl *D) {
1989 if (D->isInvalidDecl())
1990 return false;
1992 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1993 // For a decomposition declaration, warn if none of the bindings are
1994 // referenced, instead of if the variable itself is referenced (which
1995 // it is, by the bindings' expressions).
1996 bool IsAllPlaceholders = true;
1997 for (auto *BD : DD->bindings()) {
1998 if (BD->isReferenced())
1999 return false;
2000 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
2002 if (IsAllPlaceholders)
2003 return false;
2004 } else if (!D->getDeclName()) {
2005 return false;
2006 } else if (D->isReferenced() || D->isUsed()) {
2007 return false;
2010 if (D->isPlaceholderVar(LangOpts))
2011 return false;
2013 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2014 D->hasAttr<CleanupAttr>())
2015 return false;
2017 if (isa<LabelDecl>(D))
2018 return true;
2020 // Except for labels, we only care about unused decls that are local to
2021 // functions.
2022 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2023 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2024 // For dependent types, the diagnostic is deferred.
2025 WithinFunction =
2026 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2027 if (!WithinFunction)
2028 return false;
2030 if (isa<TypedefNameDecl>(D))
2031 return true;
2033 // White-list anything that isn't a local variable.
2034 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2035 return false;
2037 // Types of valid local variables should be complete, so this should succeed.
2038 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2040 const Expr *Init = VD->getInit();
2041 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2042 Init = Cleanups->getSubExpr();
2044 const auto *Ty = VD->getType().getTypePtr();
2046 // Only look at the outermost level of typedef.
2047 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2048 // Allow anything marked with __attribute__((unused)).
2049 if (TT->getDecl()->hasAttr<UnusedAttr>())
2050 return false;
2053 // Warn for reference variables whose initializtion performs lifetime
2054 // extension.
2055 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2056 if (MTE->getExtendingDecl()) {
2057 Ty = VD->getType().getNonReferenceType().getTypePtr();
2058 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2062 // If we failed to complete the type for some reason, or if the type is
2063 // dependent, don't diagnose the variable.
2064 if (Ty->isIncompleteType() || Ty->isDependentType())
2065 return false;
2067 // Look at the element type to ensure that the warning behaviour is
2068 // consistent for both scalars and arrays.
2069 Ty = Ty->getBaseElementTypeUnsafe();
2071 if (const TagType *TT = Ty->getAs<TagType>()) {
2072 const TagDecl *Tag = TT->getDecl();
2073 if (Tag->hasAttr<UnusedAttr>())
2074 return false;
2076 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2077 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2078 return false;
2080 if (Init) {
2081 const CXXConstructExpr *Construct =
2082 dyn_cast<CXXConstructExpr>(Init);
2083 if (Construct && !Construct->isElidable()) {
2084 CXXConstructorDecl *CD = Construct->getConstructor();
2085 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2086 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2087 return false;
2090 // Suppress the warning if we don't know how this is constructed, and
2091 // it could possibly be non-trivial constructor.
2092 if (Init->isTypeDependent()) {
2093 for (const CXXConstructorDecl *Ctor : RD->ctors())
2094 if (!Ctor->isTrivial())
2095 return false;
2098 // Suppress the warning if the constructor is unresolved because
2099 // its arguments are dependent.
2100 if (isa<CXXUnresolvedConstructExpr>(Init))
2101 return false;
2106 // TODO: __attribute__((unused)) templates?
2109 return true;
2112 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2113 FixItHint &Hint) {
2114 if (isa<LabelDecl>(D)) {
2115 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2116 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2117 /*SkipTrailingWhitespaceAndNewline=*/false);
2118 if (AfterColon.isInvalid())
2119 return;
2120 Hint = FixItHint::CreateRemoval(
2121 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2125 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2126 DiagnoseUnusedNestedTypedefs(
2127 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2130 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2131 DiagReceiverTy DiagReceiver) {
2132 if (D->getTypeForDecl()->isDependentType())
2133 return;
2135 for (auto *TmpD : D->decls()) {
2136 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2137 DiagnoseUnusedDecl(T, DiagReceiver);
2138 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2139 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2143 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2144 DiagnoseUnusedDecl(
2145 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2148 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2149 /// unless they are marked attr(unused).
2150 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2151 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2152 return;
2154 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2155 // typedefs can be referenced later on, so the diagnostics are emitted
2156 // at end-of-translation-unit.
2157 UnusedLocalTypedefNameCandidates.insert(TD);
2158 return;
2161 FixItHint Hint;
2162 GenerateFixForUnusedDecl(D, Context, Hint);
2164 unsigned DiagID;
2165 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2166 DiagID = diag::warn_unused_exception_param;
2167 else if (isa<LabelDecl>(D))
2168 DiagID = diag::warn_unused_label;
2169 else
2170 DiagID = diag::warn_unused_variable;
2172 SourceLocation DiagLoc = D->getLocation();
2173 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2176 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2177 DiagReceiverTy DiagReceiver) {
2178 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2179 // it's not really unused.
2180 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2181 return;
2183 // In C++, `_` variables behave as if they were maybe_unused
2184 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2185 return;
2187 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2189 if (Ty->isReferenceType() || Ty->isDependentType())
2190 return;
2192 if (const TagType *TT = Ty->getAs<TagType>()) {
2193 const TagDecl *Tag = TT->getDecl();
2194 if (Tag->hasAttr<UnusedAttr>())
2195 return;
2196 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2197 // mimic gcc's behavior.
2198 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2199 if (!RD->hasAttr<WarnUnusedAttr>())
2200 return;
2204 // Don't warn about __block Objective-C pointer variables, as they might
2205 // be assigned in the block but not used elsewhere for the purpose of lifetime
2206 // extension.
2207 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2208 return;
2210 // Don't warn about Objective-C pointer variables with precise lifetime
2211 // semantics; they can be used to ensure ARC releases the object at a known
2212 // time, which may mean assignment but no other references.
2213 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2214 return;
2216 auto iter = RefsMinusAssignments.find(VD);
2217 if (iter == RefsMinusAssignments.end())
2218 return;
2220 assert(iter->getSecond() >= 0 &&
2221 "Found a negative number of references to a VarDecl");
2222 if (iter->getSecond() != 0)
2223 return;
2224 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2225 : diag::warn_unused_but_set_variable;
2226 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2229 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2230 Sema::DiagReceiverTy DiagReceiver) {
2231 // Verify that we have no forward references left. If so, there was a goto
2232 // or address of a label taken, but no definition of it. Label fwd
2233 // definitions are indicated with a null substmt which is also not a resolved
2234 // MS inline assembly label name.
2235 bool Diagnose = false;
2236 if (L->isMSAsmLabel())
2237 Diagnose = !L->isResolvedMSAsmLabel();
2238 else
2239 Diagnose = L->getStmt() == nullptr;
2240 if (Diagnose)
2241 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2242 << L);
2245 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2246 S->applyNRVO();
2248 if (S->decl_empty()) return;
2249 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2250 "Scope shouldn't contain decls!");
2252 /// We visit the decls in non-deterministic order, but we want diagnostics
2253 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2254 /// and sort the diagnostics before emitting them, after we visited all decls.
2255 struct LocAndDiag {
2256 SourceLocation Loc;
2257 std::optional<SourceLocation> PreviousDeclLoc;
2258 PartialDiagnostic PD;
2260 SmallVector<LocAndDiag, 16> DeclDiags;
2261 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2262 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2264 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2265 SourceLocation PreviousDeclLoc,
2266 PartialDiagnostic PD) {
2267 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2270 for (auto *TmpD : S->decls()) {
2271 assert(TmpD && "This decl didn't get pushed??");
2273 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2274 NamedDecl *D = cast<NamedDecl>(TmpD);
2276 // Diagnose unused variables in this scope.
2277 if (!S->hasUnrecoverableErrorOccurred()) {
2278 DiagnoseUnusedDecl(D, addDiag);
2279 if (const auto *RD = dyn_cast<RecordDecl>(D))
2280 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2281 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2282 DiagnoseUnusedButSetDecl(VD, addDiag);
2283 RefsMinusAssignments.erase(VD);
2287 if (!D->getDeclName()) continue;
2289 // If this was a forward reference to a label, verify it was defined.
2290 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2291 CheckPoppedLabel(LD, *this, addDiag);
2293 // Remove this name from our lexical scope, and warn on it if we haven't
2294 // already.
2295 IdResolver.RemoveDecl(D);
2296 auto ShadowI = ShadowingDecls.find(D);
2297 if (ShadowI != ShadowingDecls.end()) {
2298 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2299 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2300 PDiag(diag::warn_ctor_parm_shadows_field)
2301 << D << FD << FD->getParent());
2303 ShadowingDecls.erase(ShadowI);
2307 llvm::sort(DeclDiags,
2308 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2309 // The particular order for diagnostics is not important, as long
2310 // as the order is deterministic. Using the raw location is going
2311 // to generally be in source order unless there are macro
2312 // expansions involved.
2313 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2315 for (const LocAndDiag &D : DeclDiags) {
2316 Diag(D.Loc, D.PD);
2317 if (D.PreviousDeclLoc)
2318 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2322 /// Look for an Objective-C class in the translation unit.
2324 /// \param Id The name of the Objective-C class we're looking for. If
2325 /// typo-correction fixes this name, the Id will be updated
2326 /// to the fixed name.
2328 /// \param IdLoc The location of the name in the translation unit.
2330 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2331 /// if there is no class with the given name.
2333 /// \returns The declaration of the named Objective-C class, or NULL if the
2334 /// class could not be found.
2335 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2336 SourceLocation IdLoc,
2337 bool DoTypoCorrection) {
2338 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2339 // creation from this context.
2340 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2342 if (!IDecl && DoTypoCorrection) {
2343 // Perform typo correction at the given location, but only if we
2344 // find an Objective-C class name.
2345 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2346 if (TypoCorrection C =
2347 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2348 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2349 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2350 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2351 Id = IDecl->getIdentifier();
2354 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2355 // This routine must always return a class definition, if any.
2356 if (Def && Def->getDefinition())
2357 Def = Def->getDefinition();
2358 return Def;
2361 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2362 /// from S, where a non-field would be declared. This routine copes
2363 /// with the difference between C and C++ scoping rules in structs and
2364 /// unions. For example, the following code is well-formed in C but
2365 /// ill-formed in C++:
2366 /// @code
2367 /// struct S6 {
2368 /// enum { BAR } e;
2369 /// };
2371 /// void test_S6() {
2372 /// struct S6 a;
2373 /// a.e = BAR;
2374 /// }
2375 /// @endcode
2376 /// For the declaration of BAR, this routine will return a different
2377 /// scope. The scope S will be the scope of the unnamed enumeration
2378 /// within S6. In C++, this routine will return the scope associated
2379 /// with S6, because the enumeration's scope is a transparent
2380 /// context but structures can contain non-field names. In C, this
2381 /// routine will return the translation unit scope, since the
2382 /// enumeration's scope is a transparent context and structures cannot
2383 /// contain non-field names.
2384 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2385 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2386 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2387 (S->isClassScope() && !getLangOpts().CPlusPlus))
2388 S = S->getParent();
2389 return S;
2392 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2393 ASTContext::GetBuiltinTypeError Error) {
2394 switch (Error) {
2395 case ASTContext::GE_None:
2396 return "";
2397 case ASTContext::GE_Missing_type:
2398 return BuiltinInfo.getHeaderName(ID);
2399 case ASTContext::GE_Missing_stdio:
2400 return "stdio.h";
2401 case ASTContext::GE_Missing_setjmp:
2402 return "setjmp.h";
2403 case ASTContext::GE_Missing_ucontext:
2404 return "ucontext.h";
2406 llvm_unreachable("unhandled error kind");
2409 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2410 unsigned ID, SourceLocation Loc) {
2411 DeclContext *Parent = Context.getTranslationUnitDecl();
2413 if (getLangOpts().CPlusPlus) {
2414 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2415 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2416 CLinkageDecl->setImplicit();
2417 Parent->addDecl(CLinkageDecl);
2418 Parent = CLinkageDecl;
2421 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2422 /*TInfo=*/nullptr, SC_Extern,
2423 getCurFPFeatures().isFPConstrained(),
2424 false, Type->isFunctionProtoType());
2425 New->setImplicit();
2426 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2428 // Create Decl objects for each parameter, adding them to the
2429 // FunctionDecl.
2430 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2431 SmallVector<ParmVarDecl *, 16> Params;
2432 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2433 ParmVarDecl *parm = ParmVarDecl::Create(
2434 Context, New, SourceLocation(), SourceLocation(), nullptr,
2435 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2436 parm->setScopeInfo(0, i);
2437 Params.push_back(parm);
2439 New->setParams(Params);
2442 AddKnownFunctionAttributes(New);
2443 return New;
2446 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2447 /// file scope. lazily create a decl for it. ForRedeclaration is true
2448 /// if we're creating this built-in in anticipation of redeclaring the
2449 /// built-in.
2450 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2451 Scope *S, bool ForRedeclaration,
2452 SourceLocation Loc) {
2453 LookupNecessaryTypesForBuiltin(S, ID);
2455 ASTContext::GetBuiltinTypeError Error;
2456 QualType R = Context.GetBuiltinType(ID, Error);
2457 if (Error) {
2458 if (!ForRedeclaration)
2459 return nullptr;
2461 // If we have a builtin without an associated type we should not emit a
2462 // warning when we were not able to find a type for it.
2463 if (Error == ASTContext::GE_Missing_type ||
2464 Context.BuiltinInfo.allowTypeMismatch(ID))
2465 return nullptr;
2467 // If we could not find a type for setjmp it is because the jmp_buf type was
2468 // not defined prior to the setjmp declaration.
2469 if (Error == ASTContext::GE_Missing_setjmp) {
2470 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2475 // Generally, we emit a warning that the declaration requires the
2476 // appropriate header.
2477 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2478 << getHeaderName(Context.BuiltinInfo, ID, Error)
2479 << Context.BuiltinInfo.getName(ID);
2480 return nullptr;
2483 if (!ForRedeclaration &&
2484 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2485 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2486 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2487 : diag::ext_implicit_lib_function_decl)
2488 << Context.BuiltinInfo.getName(ID) << R;
2489 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490 Diag(Loc, diag::note_include_header_or_declare)
2491 << Header << Context.BuiltinInfo.getName(ID);
2494 if (R.isNull())
2495 return nullptr;
2497 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2498 RegisterLocallyScopedExternCDecl(New, S);
2500 // TUScope is the translation-unit scope to insert this function into.
2501 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502 // relate Scopes to DeclContexts, and probably eliminate CurContext
2503 // entirely, but we're not there yet.
2504 DeclContext *SavedContext = CurContext;
2505 CurContext = New->getDeclContext();
2506 PushOnScopeChains(New, TUScope);
2507 CurContext = SavedContext;
2508 return New;
2511 /// Typedef declarations don't have linkage, but they still denote the same
2512 /// entity if their types are the same.
2513 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514 /// isSameEntity.
2515 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2516 TypedefNameDecl *Decl,
2517 LookupResult &Previous) {
2518 // This is only interesting when modules are enabled.
2519 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2520 return;
2522 // Empty sets are uninteresting.
2523 if (Previous.empty())
2524 return;
2526 LookupResult::Filter Filter = Previous.makeFilter();
2527 while (Filter.hasNext()) {
2528 NamedDecl *Old = Filter.next();
2530 // Non-hidden declarations are never ignored.
2531 if (S.isVisible(Old))
2532 continue;
2534 // Declarations of the same entity are not ignored, even if they have
2535 // different linkages.
2536 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2537 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2538 Decl->getUnderlyingType()))
2539 continue;
2541 // If both declarations give a tag declaration a typedef name for linkage
2542 // purposes, then they declare the same entity.
2543 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544 Decl->getAnonDeclWithTypedefName())
2545 continue;
2548 Filter.erase();
2551 Filter.done();
2554 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2555 QualType OldType;
2556 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2557 OldType = OldTypedef->getUnderlyingType();
2558 else
2559 OldType = Context.getTypeDeclType(Old);
2560 QualType NewType = New->getUnderlyingType();
2562 if (NewType->isVariablyModifiedType()) {
2563 // Must not redefine a typedef with a variably-modified type.
2564 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2565 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2566 << Kind << NewType;
2567 if (Old->getLocation().isValid())
2568 notePreviousDefinition(Old, New->getLocation());
2569 New->setInvalidDecl();
2570 return true;
2573 if (OldType != NewType &&
2574 !OldType->isDependentType() &&
2575 !NewType->isDependentType() &&
2576 !Context.hasSameType(OldType, NewType)) {
2577 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2578 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2579 << Kind << NewType << OldType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2585 return false;
2588 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2589 /// same name and scope as a previous declaration 'Old'. Figure out
2590 /// how to resolve this situation, merging decls or emitting
2591 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2593 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2594 LookupResult &OldDecls) {
2595 // If the new decl is known invalid already, don't bother doing any
2596 // merging checks.
2597 if (New->isInvalidDecl()) return;
2599 // Allow multiple definitions for ObjC built-in typedefs.
2600 // FIXME: Verify the underlying types are equivalent!
2601 if (getLangOpts().ObjC) {
2602 const IdentifierInfo *TypeID = New->getIdentifier();
2603 switch (TypeID->getLength()) {
2604 default: break;
2605 case 2:
2607 if (!TypeID->isStr("id"))
2608 break;
2609 QualType T = New->getUnderlyingType();
2610 if (!T->isPointerType())
2611 break;
2612 if (!T->isVoidPointerType()) {
2613 QualType PT = T->castAs<PointerType>()->getPointeeType();
2614 if (!PT->isStructureType())
2615 break;
2617 Context.setObjCIdRedefinitionType(T);
2618 // Install the built-in type for 'id', ignoring the current definition.
2619 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2620 return;
2622 case 5:
2623 if (!TypeID->isStr("Class"))
2624 break;
2625 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2626 // Install the built-in type for 'Class', ignoring the current definition.
2627 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2628 return;
2629 case 3:
2630 if (!TypeID->isStr("SEL"))
2631 break;
2632 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2633 // Install the built-in type for 'SEL', ignoring the current definition.
2634 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2635 return;
2637 // Fall through - the typedef name was not a builtin type.
2640 // Verify the old decl was also a type.
2641 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2642 if (!Old) {
2643 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2644 << New->getDeclName();
2646 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2647 if (OldD->getLocation().isValid())
2648 notePreviousDefinition(OldD, New->getLocation());
2650 return New->setInvalidDecl();
2653 // If the old declaration is invalid, just give up here.
2654 if (Old->isInvalidDecl())
2655 return New->setInvalidDecl();
2657 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2658 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2659 auto *NewTag = New->getAnonDeclWithTypedefName();
2660 NamedDecl *Hidden = nullptr;
2661 if (OldTag && NewTag &&
2662 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2663 !hasVisibleDefinition(OldTag, &Hidden)) {
2664 // There is a definition of this tag, but it is not visible. Use it
2665 // instead of our tag.
2666 New->setTypeForDecl(OldTD->getTypeForDecl());
2667 if (OldTD->isModed())
2668 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2669 OldTD->getUnderlyingType());
2670 else
2671 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2673 // Make the old tag definition visible.
2674 makeMergedDefinitionVisible(Hidden);
2676 // If this was an unscoped enumeration, yank all of its enumerators
2677 // out of the scope.
2678 if (isa<EnumDecl>(NewTag)) {
2679 Scope *EnumScope = getNonFieldDeclScope(S);
2680 for (auto *D : NewTag->decls()) {
2681 auto *ED = cast<EnumConstantDecl>(D);
2682 assert(EnumScope->isDeclScope(ED));
2683 EnumScope->RemoveDecl(ED);
2684 IdResolver.RemoveDecl(ED);
2685 ED->getLexicalDeclContext()->removeDecl(ED);
2691 // If the typedef types are not identical, reject them in all languages and
2692 // with any extensions enabled.
2693 if (isIncompatibleTypedef(Old, New))
2694 return;
2696 // The types match. Link up the redeclaration chain and merge attributes if
2697 // the old declaration was a typedef.
2698 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2699 New->setPreviousDecl(Typedef);
2700 mergeDeclAttributes(New, Old);
2703 if (getLangOpts().MicrosoftExt)
2704 return;
2706 if (getLangOpts().CPlusPlus) {
2707 // C++ [dcl.typedef]p2:
2708 // In a given non-class scope, a typedef specifier can be used to
2709 // redefine the name of any type declared in that scope to refer
2710 // to the type to which it already refers.
2711 if (!isa<CXXRecordDecl>(CurContext))
2712 return;
2714 // C++0x [dcl.typedef]p4:
2715 // In a given class scope, a typedef specifier can be used to redefine
2716 // any class-name declared in that scope that is not also a typedef-name
2717 // to refer to the type to which it already refers.
2719 // This wording came in via DR424, which was a correction to the
2720 // wording in DR56, which accidentally banned code like:
2722 // struct S {
2723 // typedef struct A { } A;
2724 // };
2726 // in the C++03 standard. We implement the C++0x semantics, which
2727 // allow the above but disallow
2729 // struct S {
2730 // typedef int I;
2731 // typedef int I;
2732 // };
2734 // since that was the intent of DR56.
2735 if (!isa<TypedefNameDecl>(Old))
2736 return;
2738 Diag(New->getLocation(), diag::err_redefinition)
2739 << New->getDeclName();
2740 notePreviousDefinition(Old, New->getLocation());
2741 return New->setInvalidDecl();
2744 // Modules always permit redefinition of typedefs, as does C11.
2745 if (getLangOpts().Modules || getLangOpts().C11)
2746 return;
2748 // If we have a redefinition of a typedef in C, emit a warning. This warning
2749 // is normally mapped to an error, but can be controlled with
2750 // -Wtypedef-redefinition. If either the original or the redefinition is
2751 // in a system header, don't emit this for compatibility with GCC.
2752 if (getDiagnostics().getSuppressSystemWarnings() &&
2753 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2754 (Old->isImplicit() ||
2755 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2756 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2757 return;
2759 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2760 << New->getDeclName();
2761 notePreviousDefinition(Old, New->getLocation());
2764 /// DeclhasAttr - returns true if decl Declaration already has the target
2765 /// attribute.
2766 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2767 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2768 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2769 for (const auto *i : D->attrs())
2770 if (i->getKind() == A->getKind()) {
2771 if (Ann) {
2772 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2773 return true;
2774 continue;
2776 // FIXME: Don't hardcode this check
2777 if (OA && isa<OwnershipAttr>(i))
2778 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2779 return true;
2782 return false;
2785 static bool isAttributeTargetADefinition(Decl *D) {
2786 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2787 return VD->isThisDeclarationADefinition();
2788 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2789 return TD->isCompleteDefinition() || TD->isBeingDefined();
2790 return true;
2793 /// Merge alignment attributes from \p Old to \p New, taking into account the
2794 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2796 /// \return \c true if any attributes were added to \p New.
2797 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2798 // Look for alignas attributes on Old, and pick out whichever attribute
2799 // specifies the strictest alignment requirement.
2800 AlignedAttr *OldAlignasAttr = nullptr;
2801 AlignedAttr *OldStrictestAlignAttr = nullptr;
2802 unsigned OldAlign = 0;
2803 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2804 // FIXME: We have no way of representing inherited dependent alignments
2805 // in a case like:
2806 // template<int A, int B> struct alignas(A) X;
2807 // template<int A, int B> struct alignas(B) X {};
2808 // For now, we just ignore any alignas attributes which are not on the
2809 // definition in such a case.
2810 if (I->isAlignmentDependent())
2811 return false;
2813 if (I->isAlignas())
2814 OldAlignasAttr = I;
2816 unsigned Align = I->getAlignment(S.Context);
2817 if (Align > OldAlign) {
2818 OldAlign = Align;
2819 OldStrictestAlignAttr = I;
2823 // Look for alignas attributes on New.
2824 AlignedAttr *NewAlignasAttr = nullptr;
2825 unsigned NewAlign = 0;
2826 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2827 if (I->isAlignmentDependent())
2828 return false;
2830 if (I->isAlignas())
2831 NewAlignasAttr = I;
2833 unsigned Align = I->getAlignment(S.Context);
2834 if (Align > NewAlign)
2835 NewAlign = Align;
2838 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2839 // Both declarations have 'alignas' attributes. We require them to match.
2840 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2841 // fall short. (If two declarations both have alignas, they must both match
2842 // every definition, and so must match each other if there is a definition.)
2844 // If either declaration only contains 'alignas(0)' specifiers, then it
2845 // specifies the natural alignment for the type.
2846 if (OldAlign == 0 || NewAlign == 0) {
2847 QualType Ty;
2848 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2849 Ty = VD->getType();
2850 else
2851 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2853 if (OldAlign == 0)
2854 OldAlign = S.Context.getTypeAlign(Ty);
2855 if (NewAlign == 0)
2856 NewAlign = S.Context.getTypeAlign(Ty);
2859 if (OldAlign != NewAlign) {
2860 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2861 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2862 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2863 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2867 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2868 // C++11 [dcl.align]p6:
2869 // if any declaration of an entity has an alignment-specifier,
2870 // every defining declaration of that entity shall specify an
2871 // equivalent alignment.
2872 // C11 6.7.5/7:
2873 // If the definition of an object does not have an alignment
2874 // specifier, any other declaration of that object shall also
2875 // have no alignment specifier.
2876 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2877 << OldAlignasAttr;
2878 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2879 << OldAlignasAttr;
2882 bool AnyAdded = false;
2884 // Ensure we have an attribute representing the strictest alignment.
2885 if (OldAlign > NewAlign) {
2886 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2887 Clone->setInherited(true);
2888 New->addAttr(Clone);
2889 AnyAdded = true;
2892 // Ensure we have an alignas attribute if the old declaration had one.
2893 if (OldAlignasAttr && !NewAlignasAttr &&
2894 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2895 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2896 Clone->setInherited(true);
2897 New->addAttr(Clone);
2898 AnyAdded = true;
2901 return AnyAdded;
2904 #define WANT_DECL_MERGE_LOGIC
2905 #include "clang/Sema/AttrParsedAttrImpl.inc"
2906 #undef WANT_DECL_MERGE_LOGIC
2908 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2909 const InheritableAttr *Attr,
2910 Sema::AvailabilityMergeKind AMK) {
2911 // Diagnose any mutual exclusions between the attribute that we want to add
2912 // and attributes that already exist on the declaration.
2913 if (!DiagnoseMutualExclusions(S, D, Attr))
2914 return false;
2916 // This function copies an attribute Attr from a previous declaration to the
2917 // new declaration D if the new declaration doesn't itself have that attribute
2918 // yet or if that attribute allows duplicates.
2919 // If you're adding a new attribute that requires logic different from
2920 // "use explicit attribute on decl if present, else use attribute from
2921 // previous decl", for example if the attribute needs to be consistent
2922 // between redeclarations, you need to call a custom merge function here.
2923 InheritableAttr *NewAttr = nullptr;
2924 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2925 NewAttr = S.mergeAvailabilityAttr(
2926 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2927 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2928 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2929 AA->getPriority());
2930 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2931 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2932 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2933 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2934 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2935 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2936 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2937 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2938 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2939 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2940 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2941 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2942 FA->getFirstArg());
2943 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2944 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2945 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2946 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2947 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2948 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2949 IA->getInheritanceModel());
2950 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2951 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2952 &S.Context.Idents.get(AA->getSpelling()));
2953 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2954 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2955 isa<CUDAGlobalAttr>(Attr))) {
2956 // CUDA target attributes are part of function signature for
2957 // overloading purposes and must not be merged.
2958 return false;
2959 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2960 NewAttr = S.mergeMinSizeAttr(D, *MA);
2961 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2962 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2963 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2964 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2965 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2966 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2967 else if (isa<AlignedAttr>(Attr))
2968 // AlignedAttrs are handled separately, because we need to handle all
2969 // such attributes on a declaration at the same time.
2970 NewAttr = nullptr;
2971 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2972 (AMK == Sema::AMK_Override ||
2973 AMK == Sema::AMK_ProtocolImplementation ||
2974 AMK == Sema::AMK_OptionalProtocolImplementation))
2975 NewAttr = nullptr;
2976 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2977 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2978 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2979 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2980 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2981 NewAttr = S.mergeImportNameAttr(D, *INA);
2982 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2983 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2984 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2985 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2986 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2987 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2988 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2989 NewAttr =
2990 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2991 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2992 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2993 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2994 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2996 if (NewAttr) {
2997 NewAttr->setInherited(true);
2998 D->addAttr(NewAttr);
2999 if (isa<MSInheritanceAttr>(NewAttr))
3000 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
3001 return true;
3004 return false;
3007 static const NamedDecl *getDefinition(const Decl *D) {
3008 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3009 return TD->getDefinition();
3010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3011 const VarDecl *Def = VD->getDefinition();
3012 if (Def)
3013 return Def;
3014 return VD->getActingDefinition();
3016 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3017 const FunctionDecl *Def = nullptr;
3018 if (FD->isDefined(Def, true))
3019 return Def;
3021 return nullptr;
3024 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3025 for (const auto *Attribute : D->attrs())
3026 if (Attribute->getKind() == Kind)
3027 return true;
3028 return false;
3031 /// checkNewAttributesAfterDef - If we already have a definition, check that
3032 /// there are no new attributes in this declaration.
3033 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3034 if (!New->hasAttrs())
3035 return;
3037 const NamedDecl *Def = getDefinition(Old);
3038 if (!Def || Def == New)
3039 return;
3041 AttrVec &NewAttributes = New->getAttrs();
3042 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3043 const Attr *NewAttribute = NewAttributes[I];
3045 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3046 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3047 Sema::SkipBodyInfo SkipBody;
3048 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3050 // If we're skipping this definition, drop the "alias" attribute.
3051 if (SkipBody.ShouldSkip) {
3052 NewAttributes.erase(NewAttributes.begin() + I);
3053 --E;
3054 continue;
3056 } else {
3057 VarDecl *VD = cast<VarDecl>(New);
3058 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3059 VarDecl::TentativeDefinition
3060 ? diag::err_alias_after_tentative
3061 : diag::err_redefinition;
3062 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3063 if (Diag == diag::err_redefinition)
3064 S.notePreviousDefinition(Def, VD->getLocation());
3065 else
3066 S.Diag(Def->getLocation(), diag::note_previous_definition);
3067 VD->setInvalidDecl();
3069 ++I;
3070 continue;
3073 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3074 // Tentative definitions are only interesting for the alias check above.
3075 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3076 ++I;
3077 continue;
3081 if (hasAttribute(Def, NewAttribute->getKind())) {
3082 ++I;
3083 continue; // regular attr merging will take care of validating this.
3086 if (isa<C11NoReturnAttr>(NewAttribute)) {
3087 // C's _Noreturn is allowed to be added to a function after it is defined.
3088 ++I;
3089 continue;
3090 } else if (isa<UuidAttr>(NewAttribute)) {
3091 // msvc will allow a subsequent definition to add an uuid to a class
3092 ++I;
3093 continue;
3094 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3095 if (AA->isAlignas()) {
3096 // C++11 [dcl.align]p6:
3097 // if any declaration of an entity has an alignment-specifier,
3098 // every defining declaration of that entity shall specify an
3099 // equivalent alignment.
3100 // C11 6.7.5/7:
3101 // If the definition of an object does not have an alignment
3102 // specifier, any other declaration of that object shall also
3103 // have no alignment specifier.
3104 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3105 << AA;
3106 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3107 << AA;
3108 NewAttributes.erase(NewAttributes.begin() + I);
3109 --E;
3110 continue;
3112 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3113 // If there is a C definition followed by a redeclaration with this
3114 // attribute then there are two different definitions. In C++, prefer the
3115 // standard diagnostics.
3116 if (!S.getLangOpts().CPlusPlus) {
3117 S.Diag(NewAttribute->getLocation(),
3118 diag::err_loader_uninitialized_redeclaration);
3119 S.Diag(Def->getLocation(), diag::note_previous_definition);
3120 NewAttributes.erase(NewAttributes.begin() + I);
3121 --E;
3122 continue;
3124 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3125 cast<VarDecl>(New)->isInline() &&
3126 !cast<VarDecl>(New)->isInlineSpecified()) {
3127 // Don't warn about applying selectany to implicitly inline variables.
3128 // Older compilers and language modes would require the use of selectany
3129 // to make such variables inline, and it would have no effect if we
3130 // honored it.
3131 ++I;
3132 continue;
3133 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3134 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3135 // declarations after definitions.
3136 ++I;
3137 continue;
3140 S.Diag(NewAttribute->getLocation(),
3141 diag::warn_attribute_precede_definition);
3142 S.Diag(Def->getLocation(), diag::note_previous_definition);
3143 NewAttributes.erase(NewAttributes.begin() + I);
3144 --E;
3148 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3149 const ConstInitAttr *CIAttr,
3150 bool AttrBeforeInit) {
3151 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3153 // Figure out a good way to write this specifier on the old declaration.
3154 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3155 // enough of the attribute list spelling information to extract that without
3156 // heroics.
3157 std::string SuitableSpelling;
3158 if (S.getLangOpts().CPlusPlus20)
3159 SuitableSpelling = std::string(
3160 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3161 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3162 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3163 InsertLoc, {tok::l_square, tok::l_square,
3164 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3165 S.PP.getIdentifierInfo("require_constant_initialization"),
3166 tok::r_square, tok::r_square}));
3167 if (SuitableSpelling.empty())
3168 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3169 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3170 S.PP.getIdentifierInfo("require_constant_initialization"),
3171 tok::r_paren, tok::r_paren}));
3172 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3173 SuitableSpelling = "constinit";
3174 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3175 SuitableSpelling = "[[clang::require_constant_initialization]]";
3176 if (SuitableSpelling.empty())
3177 SuitableSpelling = "__attribute__((require_constant_initialization))";
3178 SuitableSpelling += " ";
3180 if (AttrBeforeInit) {
3181 // extern constinit int a;
3182 // int a = 0; // error (missing 'constinit'), accepted as extension
3183 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3184 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3185 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3186 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3187 } else {
3188 // int a = 0;
3189 // constinit extern int a; // error (missing 'constinit')
3190 S.Diag(CIAttr->getLocation(),
3191 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3192 : diag::warn_require_const_init_added_too_late)
3193 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3194 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3195 << CIAttr->isConstinit()
3196 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3200 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3201 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3202 AvailabilityMergeKind AMK) {
3203 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3204 UsedAttr *NewAttr = OldAttr->clone(Context);
3205 NewAttr->setInherited(true);
3206 New->addAttr(NewAttr);
3208 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3209 RetainAttr *NewAttr = OldAttr->clone(Context);
3210 NewAttr->setInherited(true);
3211 New->addAttr(NewAttr);
3214 if (!Old->hasAttrs() && !New->hasAttrs())
3215 return;
3217 // [dcl.constinit]p1:
3218 // If the [constinit] specifier is applied to any declaration of a
3219 // variable, it shall be applied to the initializing declaration.
3220 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3221 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3222 if (bool(OldConstInit) != bool(NewConstInit)) {
3223 const auto *OldVD = cast<VarDecl>(Old);
3224 auto *NewVD = cast<VarDecl>(New);
3226 // Find the initializing declaration. Note that we might not have linked
3227 // the new declaration into the redeclaration chain yet.
3228 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3229 if (!InitDecl &&
3230 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3231 InitDecl = NewVD;
3233 if (InitDecl == NewVD) {
3234 // This is the initializing declaration. If it would inherit 'constinit',
3235 // that's ill-formed. (Note that we do not apply this to the attribute
3236 // form).
3237 if (OldConstInit && OldConstInit->isConstinit())
3238 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3239 /*AttrBeforeInit=*/true);
3240 } else if (NewConstInit) {
3241 // This is the first time we've been told that this declaration should
3242 // have a constant initializer. If we already saw the initializing
3243 // declaration, this is too late.
3244 if (InitDecl && InitDecl != NewVD) {
3245 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3246 /*AttrBeforeInit=*/false);
3247 NewVD->dropAttr<ConstInitAttr>();
3252 // Attributes declared post-definition are currently ignored.
3253 checkNewAttributesAfterDef(*this, New, Old);
3255 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3256 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3257 if (!OldA->isEquivalent(NewA)) {
3258 // This redeclaration changes __asm__ label.
3259 Diag(New->getLocation(), diag::err_different_asm_label);
3260 Diag(OldA->getLocation(), diag::note_previous_declaration);
3262 } else if (Old->isUsed()) {
3263 // This redeclaration adds an __asm__ label to a declaration that has
3264 // already been ODR-used.
3265 Diag(New->getLocation(), diag::err_late_asm_label_name)
3266 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3270 // Re-declaration cannot add abi_tag's.
3271 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3272 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3273 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3274 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3275 Diag(NewAbiTagAttr->getLocation(),
3276 diag::err_new_abi_tag_on_redeclaration)
3277 << NewTag;
3278 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3281 } else {
3282 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3283 Diag(Old->getLocation(), diag::note_previous_declaration);
3287 // This redeclaration adds a section attribute.
3288 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3289 if (auto *VD = dyn_cast<VarDecl>(New)) {
3290 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3291 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3292 Diag(Old->getLocation(), diag::note_previous_declaration);
3297 // Redeclaration adds code-seg attribute.
3298 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3299 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3300 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3301 Diag(New->getLocation(), diag::warn_mismatched_section)
3302 << 0 /*codeseg*/;
3303 Diag(Old->getLocation(), diag::note_previous_declaration);
3306 if (!Old->hasAttrs())
3307 return;
3309 bool foundAny = New->hasAttrs();
3311 // Ensure that any moving of objects within the allocated map is done before
3312 // we process them.
3313 if (!foundAny) New->setAttrs(AttrVec());
3315 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3316 // Ignore deprecated/unavailable/availability attributes if requested.
3317 AvailabilityMergeKind LocalAMK = AMK_None;
3318 if (isa<DeprecatedAttr>(I) ||
3319 isa<UnavailableAttr>(I) ||
3320 isa<AvailabilityAttr>(I)) {
3321 switch (AMK) {
3322 case AMK_None:
3323 continue;
3325 case AMK_Redeclaration:
3326 case AMK_Override:
3327 case AMK_ProtocolImplementation:
3328 case AMK_OptionalProtocolImplementation:
3329 LocalAMK = AMK;
3330 break;
3334 // Already handled.
3335 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3336 continue;
3338 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3339 foundAny = true;
3342 if (mergeAlignedAttrs(*this, New, Old))
3343 foundAny = true;
3345 if (!foundAny) New->dropAttrs();
3348 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3349 /// to the new one.
3350 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3351 const ParmVarDecl *oldDecl,
3352 Sema &S) {
3353 // C++11 [dcl.attr.depend]p2:
3354 // The first declaration of a function shall specify the
3355 // carries_dependency attribute for its declarator-id if any declaration
3356 // of the function specifies the carries_dependency attribute.
3357 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3358 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3359 S.Diag(CDA->getLocation(),
3360 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3361 // Find the first declaration of the parameter.
3362 // FIXME: Should we build redeclaration chains for function parameters?
3363 const FunctionDecl *FirstFD =
3364 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3365 const ParmVarDecl *FirstVD =
3366 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3367 S.Diag(FirstVD->getLocation(),
3368 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3371 if (!oldDecl->hasAttrs())
3372 return;
3374 bool foundAny = newDecl->hasAttrs();
3376 // Ensure that any moving of objects within the allocated map is
3377 // done before we process them.
3378 if (!foundAny) newDecl->setAttrs(AttrVec());
3380 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3381 if (!DeclHasAttr(newDecl, I)) {
3382 InheritableAttr *newAttr =
3383 cast<InheritableParamAttr>(I->clone(S.Context));
3384 newAttr->setInherited(true);
3385 newDecl->addAttr(newAttr);
3386 foundAny = true;
3390 if (!foundAny) newDecl->dropAttrs();
3393 static bool EquivalentArrayTypes(QualType Old, QualType New,
3394 const ASTContext &Ctx) {
3396 auto NoSizeInfo = [&Ctx](QualType Ty) {
3397 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3398 return true;
3399 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3400 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3401 return false;
3404 // `type[]` is equivalent to `type *` and `type[*]`.
3405 if (NoSizeInfo(Old) && NoSizeInfo(New))
3406 return true;
3408 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3409 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3410 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3411 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3412 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3413 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3414 return false;
3415 return true;
3418 // Only compare size, ignore Size modifiers and CVR.
3419 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3420 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3421 Ctx.getAsConstantArrayType(New)->getSize();
3424 // Don't try to compare dependent sized array
3425 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3426 return true;
3429 return Old == New;
3432 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3433 const ParmVarDecl *OldParam,
3434 Sema &S) {
3435 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3436 if (auto Newnullability = NewParam->getType()->getNullability()) {
3437 if (*Oldnullability != *Newnullability) {
3438 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3439 << DiagNullabilityKind(
3440 *Newnullability,
3441 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3442 != 0))
3443 << DiagNullabilityKind(
3444 *Oldnullability,
3445 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3446 != 0));
3447 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3449 } else {
3450 QualType NewT = NewParam->getType();
3451 NewT = S.Context.getAttributedType(
3452 AttributedType::getNullabilityAttrKind(*Oldnullability),
3453 NewT, NewT);
3454 NewParam->setType(NewT);
3457 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3458 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3459 if (OldParamDT && NewParamDT &&
3460 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3461 QualType OldParamOT = OldParamDT->getOriginalType();
3462 QualType NewParamOT = NewParamDT->getOriginalType();
3463 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3464 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3465 << NewParam << NewParamOT;
3466 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3467 << OldParamOT;
3472 namespace {
3474 /// Used in MergeFunctionDecl to keep track of function parameters in
3475 /// C.
3476 struct GNUCompatibleParamWarning {
3477 ParmVarDecl *OldParm;
3478 ParmVarDecl *NewParm;
3479 QualType PromotedType;
3482 } // end anonymous namespace
3484 // Determine whether the previous declaration was a definition, implicit
3485 // declaration, or a declaration.
3486 template <typename T>
3487 static std::pair<diag::kind, SourceLocation>
3488 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3489 diag::kind PrevDiag;
3490 SourceLocation OldLocation = Old->getLocation();
3491 if (Old->isThisDeclarationADefinition())
3492 PrevDiag = diag::note_previous_definition;
3493 else if (Old->isImplicit()) {
3494 PrevDiag = diag::note_previous_implicit_declaration;
3495 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3496 if (FD->getBuiltinID())
3497 PrevDiag = diag::note_previous_builtin_declaration;
3499 if (OldLocation.isInvalid())
3500 OldLocation = New->getLocation();
3501 } else
3502 PrevDiag = diag::note_previous_declaration;
3503 return std::make_pair(PrevDiag, OldLocation);
3506 /// canRedefineFunction - checks if a function can be redefined. Currently,
3507 /// only extern inline functions can be redefined, and even then only in
3508 /// GNU89 mode.
3509 static bool canRedefineFunction(const FunctionDecl *FD,
3510 const LangOptions& LangOpts) {
3511 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3512 !LangOpts.CPlusPlus &&
3513 FD->isInlineSpecified() &&
3514 FD->getStorageClass() == SC_Extern);
3517 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3518 const AttributedType *AT = T->getAs<AttributedType>();
3519 while (AT && !AT->isCallingConv())
3520 AT = AT->getModifiedType()->getAs<AttributedType>();
3521 return AT;
3524 template <typename T>
3525 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3526 const DeclContext *DC = Old->getDeclContext();
3527 if (DC->isRecord())
3528 return false;
3530 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3531 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3532 return true;
3533 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3534 return true;
3535 return false;
3538 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3539 static bool isExternC(VarTemplateDecl *) { return false; }
3540 static bool isExternC(FunctionTemplateDecl *) { return false; }
3542 /// Check whether a redeclaration of an entity introduced by a
3543 /// using-declaration is valid, given that we know it's not an overload
3544 /// (nor a hidden tag declaration).
3545 template<typename ExpectedDecl>
3546 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3547 ExpectedDecl *New) {
3548 // C++11 [basic.scope.declarative]p4:
3549 // Given a set of declarations in a single declarative region, each of
3550 // which specifies the same unqualified name,
3551 // -- they shall all refer to the same entity, or all refer to functions
3552 // and function templates; or
3553 // -- exactly one declaration shall declare a class name or enumeration
3554 // name that is not a typedef name and the other declarations shall all
3555 // refer to the same variable or enumerator, or all refer to functions
3556 // and function templates; in this case the class name or enumeration
3557 // name is hidden (3.3.10).
3559 // C++11 [namespace.udecl]p14:
3560 // If a function declaration in namespace scope or block scope has the
3561 // same name and the same parameter-type-list as a function introduced
3562 // by a using-declaration, and the declarations do not declare the same
3563 // function, the program is ill-formed.
3565 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566 if (Old &&
3567 !Old->getDeclContext()->getRedeclContext()->Equals(
3568 New->getDeclContext()->getRedeclContext()) &&
3569 !(isExternC(Old) && isExternC(New)))
3570 Old = nullptr;
3572 if (!Old) {
3573 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576 return true;
3578 return false;
3581 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3582 const FunctionDecl *B) {
3583 assert(A->getNumParams() == B->getNumParams());
3585 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3586 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3587 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3588 if (AttrA == AttrB)
3589 return true;
3590 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3591 AttrA->isDynamic() == AttrB->isDynamic();
3594 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3597 /// If necessary, adjust the semantic declaration context for a qualified
3598 /// declaration to name the correct inline namespace within the qualifier.
3599 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3600 DeclaratorDecl *OldD) {
3601 // The only case where we need to update the DeclContext is when
3602 // redeclaration lookup for a qualified name finds a declaration
3603 // in an inline namespace within the context named by the qualifier:
3605 // inline namespace N { int f(); }
3606 // int ::f(); // Sema DC needs adjusting from :: to N::.
3608 // For unqualified declarations, the semantic context *can* change
3609 // along the redeclaration chain (for local extern declarations,
3610 // extern "C" declarations, and friend declarations in particular).
3611 if (!NewD->getQualifier())
3612 return;
3614 // NewD is probably already in the right context.
3615 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3616 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3617 if (NamedDC->Equals(SemaDC))
3618 return;
3620 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3621 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3622 "unexpected context for redeclaration");
3624 auto *LexDC = NewD->getLexicalDeclContext();
3625 auto FixSemaDC = [=](NamedDecl *D) {
3626 if (!D)
3627 return;
3628 D->setDeclContext(SemaDC);
3629 D->setLexicalDeclContext(LexDC);
3632 FixSemaDC(NewD);
3633 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3634 FixSemaDC(FD->getDescribedFunctionTemplate());
3635 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3636 FixSemaDC(VD->getDescribedVarTemplate());
3639 /// MergeFunctionDecl - We just parsed a function 'New' from
3640 /// declarator D which has the same name and scope as a previous
3641 /// declaration 'Old'. Figure out how to resolve this situation,
3642 /// merging decls or emitting diagnostics as appropriate.
3644 /// In C++, New and Old must be declarations that are not
3645 /// overloaded. Use IsOverload to determine whether New and Old are
3646 /// overloaded, and to select the Old declaration that New should be
3647 /// merged with.
3649 /// Returns true if there was an error, false otherwise.
3650 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3651 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3652 // Verify the old decl was also a function.
3653 FunctionDecl *Old = OldD->getAsFunction();
3654 if (!Old) {
3655 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3656 if (New->getFriendObjectKind()) {
3657 Diag(New->getLocation(), diag::err_using_decl_friend);
3658 Diag(Shadow->getTargetDecl()->getLocation(),
3659 diag::note_using_decl_target);
3660 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3661 << 0;
3662 return true;
3665 // Check whether the two declarations might declare the same function or
3666 // function template.
3667 if (FunctionTemplateDecl *NewTemplate =
3668 New->getDescribedFunctionTemplate()) {
3669 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3670 NewTemplate))
3671 return true;
3672 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3673 ->getAsFunction();
3674 } else {
3675 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3676 return true;
3677 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3679 } else {
3680 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3681 << New->getDeclName();
3682 notePreviousDefinition(OldD, New->getLocation());
3683 return true;
3687 // If the old declaration was found in an inline namespace and the new
3688 // declaration was qualified, update the DeclContext to match.
3689 adjustDeclContextForDeclaratorDecl(New, Old);
3691 // If the old declaration is invalid, just give up here.
3692 if (Old->isInvalidDecl())
3693 return true;
3695 // Disallow redeclaration of some builtins.
3696 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3697 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3698 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3699 << Old << Old->getType();
3700 return true;
3703 diag::kind PrevDiag;
3704 SourceLocation OldLocation;
3705 std::tie(PrevDiag, OldLocation) =
3706 getNoteDiagForInvalidRedeclaration(Old, New);
3708 // Don't complain about this if we're in GNU89 mode and the old function
3709 // is an extern inline function.
3710 // Don't complain about specializations. They are not supposed to have
3711 // storage classes.
3712 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3713 New->getStorageClass() == SC_Static &&
3714 Old->hasExternalFormalLinkage() &&
3715 !New->getTemplateSpecializationInfo() &&
3716 !canRedefineFunction(Old, getLangOpts())) {
3717 if (getLangOpts().MicrosoftExt) {
3718 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3719 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3720 } else {
3721 Diag(New->getLocation(), diag::err_static_non_static) << New;
3722 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3723 return true;
3727 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3728 if (!Old->hasAttr<InternalLinkageAttr>()) {
3729 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3730 << ILA;
3731 Diag(Old->getLocation(), diag::note_previous_declaration);
3732 New->dropAttr<InternalLinkageAttr>();
3735 if (auto *EA = New->getAttr<ErrorAttr>()) {
3736 if (!Old->hasAttr<ErrorAttr>()) {
3737 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3738 Diag(Old->getLocation(), diag::note_previous_declaration);
3739 New->dropAttr<ErrorAttr>();
3743 if (CheckRedeclarationInModule(New, Old))
3744 return true;
3746 if (!getLangOpts().CPlusPlus) {
3747 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3748 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3749 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3750 << New << OldOvl;
3752 // Try our best to find a decl that actually has the overloadable
3753 // attribute for the note. In most cases (e.g. programs with only one
3754 // broken declaration/definition), this won't matter.
3756 // FIXME: We could do this if we juggled some extra state in
3757 // OverloadableAttr, rather than just removing it.
3758 const Decl *DiagOld = Old;
3759 if (OldOvl) {
3760 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3761 const auto *A = D->getAttr<OverloadableAttr>();
3762 return A && !A->isImplicit();
3764 // If we've implicitly added *all* of the overloadable attrs to this
3765 // chain, emitting a "previous redecl" note is pointless.
3766 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3769 if (DiagOld)
3770 Diag(DiagOld->getLocation(),
3771 diag::note_attribute_overloadable_prev_overload)
3772 << OldOvl;
3774 if (OldOvl)
3775 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3776 else
3777 New->dropAttr<OverloadableAttr>();
3781 // It is not permitted to redeclare an SME function with different SME
3782 // attributes.
3783 if (IsInvalidSMECallConversion(Old->getType(), New->getType(),
3784 AArch64SMECallConversionKind::MatchExactly)) {
3785 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3786 << New->getType() << Old->getType();
3787 Diag(OldLocation, diag::note_previous_declaration);
3788 return true;
3791 // If a function is first declared with a calling convention, but is later
3792 // declared or defined without one, all following decls assume the calling
3793 // convention of the first.
3795 // It's OK if a function is first declared without a calling convention,
3796 // but is later declared or defined with the default calling convention.
3798 // To test if either decl has an explicit calling convention, we look for
3799 // AttributedType sugar nodes on the type as written. If they are missing or
3800 // were canonicalized away, we assume the calling convention was implicit.
3802 // Note also that we DO NOT return at this point, because we still have
3803 // other tests to run.
3804 QualType OldQType = Context.getCanonicalType(Old->getType());
3805 QualType NewQType = Context.getCanonicalType(New->getType());
3806 const FunctionType *OldType = cast<FunctionType>(OldQType);
3807 const FunctionType *NewType = cast<FunctionType>(NewQType);
3808 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3809 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3810 bool RequiresAdjustment = false;
3812 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3813 FunctionDecl *First = Old->getFirstDecl();
3814 const FunctionType *FT =
3815 First->getType().getCanonicalType()->castAs<FunctionType>();
3816 FunctionType::ExtInfo FI = FT->getExtInfo();
3817 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3818 if (!NewCCExplicit) {
3819 // Inherit the CC from the previous declaration if it was specified
3820 // there but not here.
3821 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3822 RequiresAdjustment = true;
3823 } else if (Old->getBuiltinID()) {
3824 // Builtin attribute isn't propagated to the new one yet at this point,
3825 // so we check if the old one is a builtin.
3827 // Calling Conventions on a Builtin aren't really useful and setting a
3828 // default calling convention and cdecl'ing some builtin redeclarations is
3829 // common, so warn and ignore the calling convention on the redeclaration.
3830 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3831 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3832 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3833 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3834 RequiresAdjustment = true;
3835 } else {
3836 // Calling conventions aren't compatible, so complain.
3837 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3838 Diag(New->getLocation(), diag::err_cconv_change)
3839 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3840 << !FirstCCExplicit
3841 << (!FirstCCExplicit ? "" :
3842 FunctionType::getNameForCallConv(FI.getCC()));
3844 // Put the note on the first decl, since it is the one that matters.
3845 Diag(First->getLocation(), diag::note_previous_declaration);
3846 return true;
3850 // FIXME: diagnose the other way around?
3851 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3852 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3853 RequiresAdjustment = true;
3856 // Merge regparm attribute.
3857 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3858 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3859 if (NewTypeInfo.getHasRegParm()) {
3860 Diag(New->getLocation(), diag::err_regparm_mismatch)
3861 << NewType->getRegParmType()
3862 << OldType->getRegParmType();
3863 Diag(OldLocation, diag::note_previous_declaration);
3864 return true;
3867 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3868 RequiresAdjustment = true;
3871 // Merge ns_returns_retained attribute.
3872 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3873 if (NewTypeInfo.getProducesResult()) {
3874 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3875 << "'ns_returns_retained'";
3876 Diag(OldLocation, diag::note_previous_declaration);
3877 return true;
3880 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3881 RequiresAdjustment = true;
3884 if (OldTypeInfo.getNoCallerSavedRegs() !=
3885 NewTypeInfo.getNoCallerSavedRegs()) {
3886 if (NewTypeInfo.getNoCallerSavedRegs()) {
3887 AnyX86NoCallerSavedRegistersAttr *Attr =
3888 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3889 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3890 Diag(OldLocation, diag::note_previous_declaration);
3891 return true;
3894 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3895 RequiresAdjustment = true;
3898 if (RequiresAdjustment) {
3899 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3900 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3901 New->setType(QualType(AdjustedType, 0));
3902 NewQType = Context.getCanonicalType(New->getType());
3905 // If this redeclaration makes the function inline, we may need to add it to
3906 // UndefinedButUsed.
3907 if (!Old->isInlined() && New->isInlined() &&
3908 !New->hasAttr<GNUInlineAttr>() &&
3909 !getLangOpts().GNUInline &&
3910 Old->isUsed(false) &&
3911 !Old->isDefined() && !New->isThisDeclarationADefinition())
3912 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3913 SourceLocation()));
3915 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3916 // about it.
3917 if (New->hasAttr<GNUInlineAttr>() &&
3918 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3919 UndefinedButUsed.erase(Old->getCanonicalDecl());
3922 // If pass_object_size params don't match up perfectly, this isn't a valid
3923 // redeclaration.
3924 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3925 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3926 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3927 << New->getDeclName();
3928 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3929 return true;
3932 if (getLangOpts().CPlusPlus) {
3933 OldQType = Context.getCanonicalType(Old->getType());
3934 NewQType = Context.getCanonicalType(New->getType());
3936 // Go back to the type source info to compare the declared return types,
3937 // per C++1y [dcl.type.auto]p13:
3938 // Redeclarations or specializations of a function or function template
3939 // with a declared return type that uses a placeholder type shall also
3940 // use that placeholder, not a deduced type.
3941 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3942 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3943 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3944 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3945 OldDeclaredReturnType)) {
3946 QualType ResQT;
3947 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3948 OldDeclaredReturnType->isObjCObjectPointerType())
3949 // FIXME: This does the wrong thing for a deduced return type.
3950 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3951 if (ResQT.isNull()) {
3952 if (New->isCXXClassMember() && New->isOutOfLine())
3953 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3954 << New << New->getReturnTypeSourceRange();
3955 else
3956 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3957 << New->getReturnTypeSourceRange();
3958 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3959 << Old->getReturnTypeSourceRange();
3960 return true;
3962 else
3963 NewQType = ResQT;
3966 QualType OldReturnType = OldType->getReturnType();
3967 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3968 if (OldReturnType != NewReturnType) {
3969 // If this function has a deduced return type and has already been
3970 // defined, copy the deduced value from the old declaration.
3971 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3972 if (OldAT && OldAT->isDeduced()) {
3973 QualType DT = OldAT->getDeducedType();
3974 if (DT.isNull()) {
3975 New->setType(SubstAutoTypeDependent(New->getType()));
3976 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3977 } else {
3978 New->setType(SubstAutoType(New->getType(), DT));
3979 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3984 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3985 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3986 if (OldMethod && NewMethod) {
3987 // Preserve triviality.
3988 NewMethod->setTrivial(OldMethod->isTrivial());
3990 // MSVC allows explicit template specialization at class scope:
3991 // 2 CXXMethodDecls referring to the same function will be injected.
3992 // We don't want a redeclaration error.
3993 bool IsClassScopeExplicitSpecialization =
3994 OldMethod->isFunctionTemplateSpecialization() &&
3995 NewMethod->isFunctionTemplateSpecialization();
3996 bool isFriend = NewMethod->getFriendObjectKind();
3998 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3999 !IsClassScopeExplicitSpecialization) {
4000 // -- Member function declarations with the same name and the
4001 // same parameter types cannot be overloaded if any of them
4002 // is a static member function declaration.
4003 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4004 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4005 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4006 return true;
4009 // C++ [class.mem]p1:
4010 // [...] A member shall not be declared twice in the
4011 // member-specification, except that a nested class or member
4012 // class template can be declared and then later defined.
4013 if (!inTemplateInstantiation()) {
4014 unsigned NewDiag;
4015 if (isa<CXXConstructorDecl>(OldMethod))
4016 NewDiag = diag::err_constructor_redeclared;
4017 else if (isa<CXXDestructorDecl>(NewMethod))
4018 NewDiag = diag::err_destructor_redeclared;
4019 else if (isa<CXXConversionDecl>(NewMethod))
4020 NewDiag = diag::err_conv_function_redeclared;
4021 else
4022 NewDiag = diag::err_member_redeclared;
4024 Diag(New->getLocation(), NewDiag);
4025 } else {
4026 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4027 << New << New->getType();
4029 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4030 return true;
4032 // Complain if this is an explicit declaration of a special
4033 // member that was initially declared implicitly.
4035 // As an exception, it's okay to befriend such methods in order
4036 // to permit the implicit constructor/destructor/operator calls.
4037 } else if (OldMethod->isImplicit()) {
4038 if (isFriend) {
4039 NewMethod->setImplicit();
4040 } else {
4041 Diag(NewMethod->getLocation(),
4042 diag::err_definition_of_implicitly_declared_member)
4043 << New << getSpecialMember(OldMethod);
4044 return true;
4046 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4047 Diag(NewMethod->getLocation(),
4048 diag::err_definition_of_explicitly_defaulted_member)
4049 << getSpecialMember(OldMethod);
4050 return true;
4054 // C++1z [over.load]p2
4055 // Certain function declarations cannot be overloaded:
4056 // -- Function declarations that differ only in the return type,
4057 // the exception specification, or both cannot be overloaded.
4059 // Check the exception specifications match. This may recompute the type of
4060 // both Old and New if it resolved exception specifications, so grab the
4061 // types again after this. Because this updates the type, we do this before
4062 // any of the other checks below, which may update the "de facto" NewQType
4063 // but do not necessarily update the type of New.
4064 if (CheckEquivalentExceptionSpec(Old, New))
4065 return true;
4067 // C++11 [dcl.attr.noreturn]p1:
4068 // The first declaration of a function shall specify the noreturn
4069 // attribute if any declaration of that function specifies the noreturn
4070 // attribute.
4071 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4072 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4073 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4074 << NRA;
4075 Diag(Old->getLocation(), diag::note_previous_declaration);
4078 // C++11 [dcl.attr.depend]p2:
4079 // The first declaration of a function shall specify the
4080 // carries_dependency attribute for its declarator-id if any declaration
4081 // of the function specifies the carries_dependency attribute.
4082 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4083 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4084 Diag(CDA->getLocation(),
4085 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4086 Diag(Old->getFirstDecl()->getLocation(),
4087 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4090 // (C++98 8.3.5p3):
4091 // All declarations for a function shall agree exactly in both the
4092 // return type and the parameter-type-list.
4093 // We also want to respect all the extended bits except noreturn.
4095 // noreturn should now match unless the old type info didn't have it.
4096 QualType OldQTypeForComparison = OldQType;
4097 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4098 auto *OldType = OldQType->castAs<FunctionProtoType>();
4099 const FunctionType *OldTypeForComparison
4100 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4101 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4102 assert(OldQTypeForComparison.isCanonical());
4105 if (haveIncompatibleLanguageLinkages(Old, New)) {
4106 // As a special case, retain the language linkage from previous
4107 // declarations of a friend function as an extension.
4109 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4110 // and is useful because there's otherwise no way to specify language
4111 // linkage within class scope.
4113 // Check cautiously as the friend object kind isn't yet complete.
4114 if (New->getFriendObjectKind() != Decl::FOK_None) {
4115 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4116 Diag(OldLocation, PrevDiag);
4117 } else {
4118 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4119 Diag(OldLocation, PrevDiag);
4120 return true;
4124 // If the function types are compatible, merge the declarations. Ignore the
4125 // exception specifier because it was already checked above in
4126 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4127 // about incompatible types under -fms-compatibility.
4128 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4129 NewQType))
4130 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4132 // If the types are imprecise (due to dependent constructs in friends or
4133 // local extern declarations), it's OK if they differ. We'll check again
4134 // during instantiation.
4135 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4136 return false;
4138 // Fall through for conflicting redeclarations and redefinitions.
4141 // C: Function types need to be compatible, not identical. This handles
4142 // duplicate function decls like "void f(int); void f(enum X);" properly.
4143 if (!getLangOpts().CPlusPlus) {
4144 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4145 // type is specified by a function definition that contains a (possibly
4146 // empty) identifier list, both shall agree in the number of parameters
4147 // and the type of each parameter shall be compatible with the type that
4148 // results from the application of default argument promotions to the
4149 // type of the corresponding identifier. ...
4150 // This cannot be handled by ASTContext::typesAreCompatible() because that
4151 // doesn't know whether the function type is for a definition or not when
4152 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4153 // we need to cover here is that the number of arguments agree as the
4154 // default argument promotion rules were already checked by
4155 // ASTContext::typesAreCompatible().
4156 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4157 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4158 if (Old->hasInheritedPrototype())
4159 Old = Old->getCanonicalDecl();
4160 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4161 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4162 return true;
4165 // If we are merging two functions where only one of them has a prototype,
4166 // we may have enough information to decide to issue a diagnostic that the
4167 // function without a protoype will change behavior in C23. This handles
4168 // cases like:
4169 // void i(); void i(int j);
4170 // void i(int j); void i();
4171 // void i(); void i(int j) {}
4172 // See ActOnFinishFunctionBody() for other cases of the behavior change
4173 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4174 // type without a prototype.
4175 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4176 !New->isImplicit() && !Old->isImplicit()) {
4177 const FunctionDecl *WithProto, *WithoutProto;
4178 if (New->hasWrittenPrototype()) {
4179 WithProto = New;
4180 WithoutProto = Old;
4181 } else {
4182 WithProto = Old;
4183 WithoutProto = New;
4186 if (WithProto->getNumParams() != 0) {
4187 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4188 // The one without the prototype will be changing behavior in C23, so
4189 // warn about that one so long as it's a user-visible declaration.
4190 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4191 if (WithoutProto == New)
4192 IsWithoutProtoADef = NewDeclIsDefn;
4193 else
4194 IsWithProtoADef = NewDeclIsDefn;
4195 Diag(WithoutProto->getLocation(),
4196 diag::warn_non_prototype_changes_behavior)
4197 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4198 << (WithoutProto == Old) << IsWithProtoADef;
4200 // The reason the one without the prototype will be changing behavior
4201 // is because of the one with the prototype, so note that so long as
4202 // it's a user-visible declaration. There is one exception to this:
4203 // when the new declaration is a definition without a prototype, the
4204 // old declaration with a prototype is not the cause of the issue,
4205 // and that does not need to be noted because the one with a
4206 // prototype will not change behavior in C23.
4207 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4208 !IsWithoutProtoADef)
4209 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4214 if (Context.typesAreCompatible(OldQType, NewQType)) {
4215 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4216 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4217 const FunctionProtoType *OldProto = nullptr;
4218 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4219 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4220 // The old declaration provided a function prototype, but the
4221 // new declaration does not. Merge in the prototype.
4222 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4223 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4224 OldProto->getParamTypes(),
4225 OldProto->getExtProtoInfo());
4226 New->setType(NewQType);
4227 New->setHasInheritedPrototype();
4229 // Synthesize parameters with the same types.
4230 SmallVector<ParmVarDecl *, 16> Params;
4231 for (const auto &ParamType : OldProto->param_types()) {
4232 ParmVarDecl *Param = ParmVarDecl::Create(
4233 Context, New, SourceLocation(), SourceLocation(), nullptr,
4234 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4235 Param->setScopeInfo(0, Params.size());
4236 Param->setImplicit();
4237 Params.push_back(Param);
4240 New->setParams(Params);
4243 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4247 // Check if the function types are compatible when pointer size address
4248 // spaces are ignored.
4249 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4250 return false;
4252 // GNU C permits a K&R definition to follow a prototype declaration
4253 // if the declared types of the parameters in the K&R definition
4254 // match the types in the prototype declaration, even when the
4255 // promoted types of the parameters from the K&R definition differ
4256 // from the types in the prototype. GCC then keeps the types from
4257 // the prototype.
4259 // If a variadic prototype is followed by a non-variadic K&R definition,
4260 // the K&R definition becomes variadic. This is sort of an edge case, but
4261 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4262 // C99 6.9.1p8.
4263 if (!getLangOpts().CPlusPlus &&
4264 Old->hasPrototype() && !New->hasPrototype() &&
4265 New->getType()->getAs<FunctionProtoType>() &&
4266 Old->getNumParams() == New->getNumParams()) {
4267 SmallVector<QualType, 16> ArgTypes;
4268 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4269 const FunctionProtoType *OldProto
4270 = Old->getType()->getAs<FunctionProtoType>();
4271 const FunctionProtoType *NewProto
4272 = New->getType()->getAs<FunctionProtoType>();
4274 // Determine whether this is the GNU C extension.
4275 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4276 NewProto->getReturnType());
4277 bool LooseCompatible = !MergedReturn.isNull();
4278 for (unsigned Idx = 0, End = Old->getNumParams();
4279 LooseCompatible && Idx != End; ++Idx) {
4280 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4281 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4282 if (Context.typesAreCompatible(OldParm->getType(),
4283 NewProto->getParamType(Idx))) {
4284 ArgTypes.push_back(NewParm->getType());
4285 } else if (Context.typesAreCompatible(OldParm->getType(),
4286 NewParm->getType(),
4287 /*CompareUnqualified=*/true)) {
4288 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4289 NewProto->getParamType(Idx) };
4290 Warnings.push_back(Warn);
4291 ArgTypes.push_back(NewParm->getType());
4292 } else
4293 LooseCompatible = false;
4296 if (LooseCompatible) {
4297 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4298 Diag(Warnings[Warn].NewParm->getLocation(),
4299 diag::ext_param_promoted_not_compatible_with_prototype)
4300 << Warnings[Warn].PromotedType
4301 << Warnings[Warn].OldParm->getType();
4302 if (Warnings[Warn].OldParm->getLocation().isValid())
4303 Diag(Warnings[Warn].OldParm->getLocation(),
4304 diag::note_previous_declaration);
4307 if (MergeTypeWithOld)
4308 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4309 OldProto->getExtProtoInfo()));
4310 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4313 // Fall through to diagnose conflicting types.
4316 // A function that has already been declared has been redeclared or
4317 // defined with a different type; show an appropriate diagnostic.
4319 // If the previous declaration was an implicitly-generated builtin
4320 // declaration, then at the very least we should use a specialized note.
4321 unsigned BuiltinID;
4322 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4323 // If it's actually a library-defined builtin function like 'malloc'
4324 // or 'printf', just warn about the incompatible redeclaration.
4325 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4326 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4327 Diag(OldLocation, diag::note_previous_builtin_declaration)
4328 << Old << Old->getType();
4329 return false;
4332 PrevDiag = diag::note_previous_builtin_declaration;
4335 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4336 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4337 return true;
4340 /// Completes the merge of two function declarations that are
4341 /// known to be compatible.
4343 /// This routine handles the merging of attributes and other
4344 /// properties of function declarations from the old declaration to
4345 /// the new declaration, once we know that New is in fact a
4346 /// redeclaration of Old.
4348 /// \returns false
4349 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4350 Scope *S, bool MergeTypeWithOld) {
4351 // Merge the attributes
4352 mergeDeclAttributes(New, Old);
4354 // Merge "pure" flag.
4355 if (Old->isPure())
4356 New->setPure();
4358 // Merge "used" flag.
4359 if (Old->getMostRecentDecl()->isUsed(false))
4360 New->setIsUsed();
4362 // Merge attributes from the parameters. These can mismatch with K&R
4363 // declarations.
4364 if (New->getNumParams() == Old->getNumParams())
4365 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4366 ParmVarDecl *NewParam = New->getParamDecl(i);
4367 ParmVarDecl *OldParam = Old->getParamDecl(i);
4368 mergeParamDeclAttributes(NewParam, OldParam, *this);
4369 mergeParamDeclTypes(NewParam, OldParam, *this);
4372 if (getLangOpts().CPlusPlus)
4373 return MergeCXXFunctionDecl(New, Old, S);
4375 // Merge the function types so the we get the composite types for the return
4376 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4377 // was visible.
4378 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4379 if (!Merged.isNull() && MergeTypeWithOld)
4380 New->setType(Merged);
4382 return false;
4385 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4386 ObjCMethodDecl *oldMethod) {
4387 // Merge the attributes, including deprecated/unavailable
4388 AvailabilityMergeKind MergeKind =
4389 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4390 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4391 : AMK_ProtocolImplementation)
4392 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4393 : AMK_Override;
4395 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4397 // Merge attributes from the parameters.
4398 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4399 oe = oldMethod->param_end();
4400 for (ObjCMethodDecl::param_iterator
4401 ni = newMethod->param_begin(), ne = newMethod->param_end();
4402 ni != ne && oi != oe; ++ni, ++oi)
4403 mergeParamDeclAttributes(*ni, *oi, *this);
4405 CheckObjCMethodOverride(newMethod, oldMethod);
4408 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4409 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4411 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4412 ? diag::err_redefinition_different_type
4413 : diag::err_redeclaration_different_type)
4414 << New->getDeclName() << New->getType() << Old->getType();
4416 diag::kind PrevDiag;
4417 SourceLocation OldLocation;
4418 std::tie(PrevDiag, OldLocation)
4419 = getNoteDiagForInvalidRedeclaration(Old, New);
4420 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4421 New->setInvalidDecl();
4424 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4425 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4426 /// emitting diagnostics as appropriate.
4428 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4429 /// to here in AddInitializerToDecl. We can't check them before the initializer
4430 /// is attached.
4431 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4432 bool MergeTypeWithOld) {
4433 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4434 return;
4436 QualType MergedT;
4437 if (getLangOpts().CPlusPlus) {
4438 if (New->getType()->isUndeducedType()) {
4439 // We don't know what the new type is until the initializer is attached.
4440 return;
4441 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4442 // These could still be something that needs exception specs checked.
4443 return MergeVarDeclExceptionSpecs(New, Old);
4445 // C++ [basic.link]p10:
4446 // [...] the types specified by all declarations referring to a given
4447 // object or function shall be identical, except that declarations for an
4448 // array object can specify array types that differ by the presence or
4449 // absence of a major array bound (8.3.4).
4450 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4451 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4452 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4454 // We are merging a variable declaration New into Old. If it has an array
4455 // bound, and that bound differs from Old's bound, we should diagnose the
4456 // mismatch.
4457 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4458 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4459 PrevVD = PrevVD->getPreviousDecl()) {
4460 QualType PrevVDTy = PrevVD->getType();
4461 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4462 continue;
4464 if (!Context.hasSameType(New->getType(), PrevVDTy))
4465 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4469 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4470 if (Context.hasSameType(OldArray->getElementType(),
4471 NewArray->getElementType()))
4472 MergedT = New->getType();
4474 // FIXME: Check visibility. New is hidden but has a complete type. If New
4475 // has no array bound, it should not inherit one from Old, if Old is not
4476 // visible.
4477 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4478 if (Context.hasSameType(OldArray->getElementType(),
4479 NewArray->getElementType()))
4480 MergedT = Old->getType();
4483 else if (New->getType()->isObjCObjectPointerType() &&
4484 Old->getType()->isObjCObjectPointerType()) {
4485 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4486 Old->getType());
4488 } else {
4489 // C 6.2.7p2:
4490 // All declarations that refer to the same object or function shall have
4491 // compatible type.
4492 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4494 if (MergedT.isNull()) {
4495 // It's OK if we couldn't merge types if either type is dependent, for a
4496 // block-scope variable. In other cases (static data members of class
4497 // templates, variable templates, ...), we require the types to be
4498 // equivalent.
4499 // FIXME: The C++ standard doesn't say anything about this.
4500 if ((New->getType()->isDependentType() ||
4501 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4502 // If the old type was dependent, we can't merge with it, so the new type
4503 // becomes dependent for now. We'll reproduce the original type when we
4504 // instantiate the TypeSourceInfo for the variable.
4505 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4506 New->setType(Context.DependentTy);
4507 return;
4509 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4512 // Don't actually update the type on the new declaration if the old
4513 // declaration was an extern declaration in a different scope.
4514 if (MergeTypeWithOld)
4515 New->setType(MergedT);
4518 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4519 LookupResult &Previous) {
4520 // C11 6.2.7p4:
4521 // For an identifier with internal or external linkage declared
4522 // in a scope in which a prior declaration of that identifier is
4523 // visible, if the prior declaration specifies internal or
4524 // external linkage, the type of the identifier at the later
4525 // declaration becomes the composite type.
4527 // If the variable isn't visible, we do not merge with its type.
4528 if (Previous.isShadowed())
4529 return false;
4531 if (S.getLangOpts().CPlusPlus) {
4532 // C++11 [dcl.array]p3:
4533 // If there is a preceding declaration of the entity in the same
4534 // scope in which the bound was specified, an omitted array bound
4535 // is taken to be the same as in that earlier declaration.
4536 return NewVD->isPreviousDeclInSameBlockScope() ||
4537 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4538 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4539 } else {
4540 // If the old declaration was function-local, don't merge with its
4541 // type unless we're in the same function.
4542 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4543 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4547 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4548 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4549 /// situation, merging decls or emitting diagnostics as appropriate.
4551 /// Tentative definition rules (C99 6.9.2p2) are checked by
4552 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4553 /// definitions here, since the initializer hasn't been attached.
4555 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4556 // If the new decl is already invalid, don't do any other checking.
4557 if (New->isInvalidDecl())
4558 return;
4560 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4561 return;
4563 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4565 // Verify the old decl was also a variable or variable template.
4566 VarDecl *Old = nullptr;
4567 VarTemplateDecl *OldTemplate = nullptr;
4568 if (Previous.isSingleResult()) {
4569 if (NewTemplate) {
4570 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4571 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4573 if (auto *Shadow =
4574 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4575 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4576 return New->setInvalidDecl();
4577 } else {
4578 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4580 if (auto *Shadow =
4581 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4582 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4583 return New->setInvalidDecl();
4586 if (!Old) {
4587 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4588 << New->getDeclName();
4589 notePreviousDefinition(Previous.getRepresentativeDecl(),
4590 New->getLocation());
4591 return New->setInvalidDecl();
4594 // If the old declaration was found in an inline namespace and the new
4595 // declaration was qualified, update the DeclContext to match.
4596 adjustDeclContextForDeclaratorDecl(New, Old);
4598 // Ensure the template parameters are compatible.
4599 if (NewTemplate &&
4600 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4601 OldTemplate->getTemplateParameters(),
4602 /*Complain=*/true, TPL_TemplateMatch))
4603 return New->setInvalidDecl();
4605 // C++ [class.mem]p1:
4606 // A member shall not be declared twice in the member-specification [...]
4608 // Here, we need only consider static data members.
4609 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4610 Diag(New->getLocation(), diag::err_duplicate_member)
4611 << New->getIdentifier();
4612 Diag(Old->getLocation(), diag::note_previous_declaration);
4613 New->setInvalidDecl();
4616 mergeDeclAttributes(New, Old);
4617 // Warn if an already-declared variable is made a weak_import in a subsequent
4618 // declaration
4619 if (New->hasAttr<WeakImportAttr>() &&
4620 Old->getStorageClass() == SC_None &&
4621 !Old->hasAttr<WeakImportAttr>()) {
4622 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4623 Diag(Old->getLocation(), diag::note_previous_declaration);
4624 // Remove weak_import attribute on new declaration.
4625 New->dropAttr<WeakImportAttr>();
4628 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4629 if (!Old->hasAttr<InternalLinkageAttr>()) {
4630 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4631 << ILA;
4632 Diag(Old->getLocation(), diag::note_previous_declaration);
4633 New->dropAttr<InternalLinkageAttr>();
4636 // Merge the types.
4637 VarDecl *MostRecent = Old->getMostRecentDecl();
4638 if (MostRecent != Old) {
4639 MergeVarDeclTypes(New, MostRecent,
4640 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4641 if (New->isInvalidDecl())
4642 return;
4645 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4646 if (New->isInvalidDecl())
4647 return;
4649 diag::kind PrevDiag;
4650 SourceLocation OldLocation;
4651 std::tie(PrevDiag, OldLocation) =
4652 getNoteDiagForInvalidRedeclaration(Old, New);
4654 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4655 if (New->getStorageClass() == SC_Static &&
4656 !New->isStaticDataMember() &&
4657 Old->hasExternalFormalLinkage()) {
4658 if (getLangOpts().MicrosoftExt) {
4659 Diag(New->getLocation(), diag::ext_static_non_static)
4660 << New->getDeclName();
4661 Diag(OldLocation, PrevDiag);
4662 } else {
4663 Diag(New->getLocation(), diag::err_static_non_static)
4664 << New->getDeclName();
4665 Diag(OldLocation, PrevDiag);
4666 return New->setInvalidDecl();
4669 // C99 6.2.2p4:
4670 // For an identifier declared with the storage-class specifier
4671 // extern in a scope in which a prior declaration of that
4672 // identifier is visible,23) if the prior declaration specifies
4673 // internal or external linkage, the linkage of the identifier at
4674 // the later declaration is the same as the linkage specified at
4675 // the prior declaration. If no prior declaration is visible, or
4676 // if the prior declaration specifies no linkage, then the
4677 // identifier has external linkage.
4678 if (New->hasExternalStorage() && Old->hasLinkage())
4679 /* Okay */;
4680 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4681 !New->isStaticDataMember() &&
4682 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4683 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4684 Diag(OldLocation, PrevDiag);
4685 return New->setInvalidDecl();
4688 // Check if extern is followed by non-extern and vice-versa.
4689 if (New->hasExternalStorage() &&
4690 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4691 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4692 Diag(OldLocation, PrevDiag);
4693 return New->setInvalidDecl();
4695 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4696 !New->hasExternalStorage()) {
4697 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4698 Diag(OldLocation, PrevDiag);
4699 return New->setInvalidDecl();
4702 if (CheckRedeclarationInModule(New, Old))
4703 return;
4705 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4707 // FIXME: The test for external storage here seems wrong? We still
4708 // need to check for mismatches.
4709 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4710 // Don't complain about out-of-line definitions of static members.
4711 !(Old->getLexicalDeclContext()->isRecord() &&
4712 !New->getLexicalDeclContext()->isRecord())) {
4713 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4714 Diag(OldLocation, PrevDiag);
4715 return New->setInvalidDecl();
4718 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4719 if (VarDecl *Def = Old->getDefinition()) {
4720 // C++1z [dcl.fcn.spec]p4:
4721 // If the definition of a variable appears in a translation unit before
4722 // its first declaration as inline, the program is ill-formed.
4723 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4724 Diag(Def->getLocation(), diag::note_previous_definition);
4728 // If this redeclaration makes the variable inline, we may need to add it to
4729 // UndefinedButUsed.
4730 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4731 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4732 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4733 SourceLocation()));
4735 if (New->getTLSKind() != Old->getTLSKind()) {
4736 if (!Old->getTLSKind()) {
4737 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4738 Diag(OldLocation, PrevDiag);
4739 } else if (!New->getTLSKind()) {
4740 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4741 Diag(OldLocation, PrevDiag);
4742 } else {
4743 // Do not allow redeclaration to change the variable between requiring
4744 // static and dynamic initialization.
4745 // FIXME: GCC allows this, but uses the TLS keyword on the first
4746 // declaration to determine the kind. Do we need to be compatible here?
4747 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4748 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4749 Diag(OldLocation, PrevDiag);
4753 // C++ doesn't have tentative definitions, so go right ahead and check here.
4754 if (getLangOpts().CPlusPlus) {
4755 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4756 Old->getCanonicalDecl()->isConstexpr()) {
4757 // This definition won't be a definition any more once it's been merged.
4758 Diag(New->getLocation(),
4759 diag::warn_deprecated_redundant_constexpr_static_def);
4760 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4761 VarDecl *Def = Old->getDefinition();
4762 if (Def && checkVarDeclRedefinition(Def, New))
4763 return;
4767 if (haveIncompatibleLanguageLinkages(Old, New)) {
4768 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4769 Diag(OldLocation, PrevDiag);
4770 New->setInvalidDecl();
4771 return;
4774 // Merge "used" flag.
4775 if (Old->getMostRecentDecl()->isUsed(false))
4776 New->setIsUsed();
4778 // Keep a chain of previous declarations.
4779 New->setPreviousDecl(Old);
4780 if (NewTemplate)
4781 NewTemplate->setPreviousDecl(OldTemplate);
4783 // Inherit access appropriately.
4784 New->setAccess(Old->getAccess());
4785 if (NewTemplate)
4786 NewTemplate->setAccess(New->getAccess());
4788 if (Old->isInline())
4789 New->setImplicitlyInline();
4792 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4793 SourceManager &SrcMgr = getSourceManager();
4794 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4795 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4796 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4797 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4798 auto &HSI = PP.getHeaderSearchInfo();
4799 StringRef HdrFilename =
4800 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4802 auto noteFromModuleOrInclude = [&](Module *Mod,
4803 SourceLocation IncLoc) -> bool {
4804 // Redefinition errors with modules are common with non modular mapped
4805 // headers, example: a non-modular header H in module A that also gets
4806 // included directly in a TU. Pointing twice to the same header/definition
4807 // is confusing, try to get better diagnostics when modules is on.
4808 if (IncLoc.isValid()) {
4809 if (Mod) {
4810 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4811 << HdrFilename.str() << Mod->getFullModuleName();
4812 if (!Mod->DefinitionLoc.isInvalid())
4813 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4814 << Mod->getFullModuleName();
4815 } else {
4816 Diag(IncLoc, diag::note_redefinition_include_same_file)
4817 << HdrFilename.str();
4819 return true;
4822 return false;
4825 // Is it the same file and same offset? Provide more information on why
4826 // this leads to a redefinition error.
4827 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4828 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4829 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4830 bool EmittedDiag =
4831 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4832 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4834 // If the header has no guards, emit a note suggesting one.
4835 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4836 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4838 if (EmittedDiag)
4839 return;
4842 // Redefinition coming from different files or couldn't do better above.
4843 if (Old->getLocation().isValid())
4844 Diag(Old->getLocation(), diag::note_previous_definition);
4847 /// We've just determined that \p Old and \p New both appear to be definitions
4848 /// of the same variable. Either diagnose or fix the problem.
4849 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4850 if (!hasVisibleDefinition(Old) &&
4851 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4852 isa<VarTemplateSpecializationDecl>(New) ||
4853 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4854 New->getDeclContext()->isDependentContext())) {
4855 // The previous definition is hidden, and multiple definitions are
4856 // permitted (in separate TUs). Demote this to a declaration.
4857 New->demoteThisDefinitionToDeclaration();
4859 // Make the canonical definition visible.
4860 if (auto *OldTD = Old->getDescribedVarTemplate())
4861 makeMergedDefinitionVisible(OldTD);
4862 makeMergedDefinitionVisible(Old);
4863 return false;
4864 } else {
4865 Diag(New->getLocation(), diag::err_redefinition) << New;
4866 notePreviousDefinition(Old, New->getLocation());
4867 New->setInvalidDecl();
4868 return true;
4872 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4873 /// no declarator (e.g. "struct foo;") is parsed.
4874 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4875 DeclSpec &DS,
4876 const ParsedAttributesView &DeclAttrs,
4877 RecordDecl *&AnonRecord) {
4878 return ParsedFreeStandingDeclSpec(
4879 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4882 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4883 // disambiguate entities defined in different scopes.
4884 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4885 // compatibility.
4886 // We will pick our mangling number depending on which version of MSVC is being
4887 // targeted.
4888 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4889 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4890 ? S->getMSCurManglingNumber()
4891 : S->getMSLastManglingNumber();
4894 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4895 if (!Context.getLangOpts().CPlusPlus)
4896 return;
4898 if (isa<CXXRecordDecl>(Tag->getParent())) {
4899 // If this tag is the direct child of a class, number it if
4900 // it is anonymous.
4901 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4902 return;
4903 MangleNumberingContext &MCtx =
4904 Context.getManglingNumberContext(Tag->getParent());
4905 Context.setManglingNumber(
4906 Tag, MCtx.getManglingNumber(
4907 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4908 return;
4911 // If this tag isn't a direct child of a class, number it if it is local.
4912 MangleNumberingContext *MCtx;
4913 Decl *ManglingContextDecl;
4914 std::tie(MCtx, ManglingContextDecl) =
4915 getCurrentMangleNumberContext(Tag->getDeclContext());
4916 if (MCtx) {
4917 Context.setManglingNumber(
4918 Tag, MCtx->getManglingNumber(
4919 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4923 namespace {
4924 struct NonCLikeKind {
4925 enum {
4926 None,
4927 BaseClass,
4928 DefaultMemberInit,
4929 Lambda,
4930 Friend,
4931 OtherMember,
4932 Invalid,
4933 } Kind = None;
4934 SourceRange Range;
4936 explicit operator bool() { return Kind != None; }
4940 /// Determine whether a class is C-like, according to the rules of C++
4941 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4942 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4943 if (RD->isInvalidDecl())
4944 return {NonCLikeKind::Invalid, {}};
4946 // C++ [dcl.typedef]p9: [P1766R1]
4947 // An unnamed class with a typedef name for linkage purposes shall not
4949 // -- have any base classes
4950 if (RD->getNumBases())
4951 return {NonCLikeKind::BaseClass,
4952 SourceRange(RD->bases_begin()->getBeginLoc(),
4953 RD->bases_end()[-1].getEndLoc())};
4954 bool Invalid = false;
4955 for (Decl *D : RD->decls()) {
4956 // Don't complain about things we already diagnosed.
4957 if (D->isInvalidDecl()) {
4958 Invalid = true;
4959 continue;
4962 // -- have any [...] default member initializers
4963 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4964 if (FD->hasInClassInitializer()) {
4965 auto *Init = FD->getInClassInitializer();
4966 return {NonCLikeKind::DefaultMemberInit,
4967 Init ? Init->getSourceRange() : D->getSourceRange()};
4969 continue;
4972 // FIXME: We don't allow friend declarations. This violates the wording of
4973 // P1766, but not the intent.
4974 if (isa<FriendDecl>(D))
4975 return {NonCLikeKind::Friend, D->getSourceRange()};
4977 // -- declare any members other than non-static data members, member
4978 // enumerations, or member classes,
4979 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4980 isa<EnumDecl>(D))
4981 continue;
4982 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4983 if (!MemberRD) {
4984 if (D->isImplicit())
4985 continue;
4986 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4989 // -- contain a lambda-expression,
4990 if (MemberRD->isLambda())
4991 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4993 // and all member classes shall also satisfy these requirements
4994 // (recursively).
4995 if (MemberRD->isThisDeclarationADefinition()) {
4996 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4997 return Kind;
5001 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5004 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5005 TypedefNameDecl *NewTD) {
5006 if (TagFromDeclSpec->isInvalidDecl())
5007 return;
5009 // Do nothing if the tag already has a name for linkage purposes.
5010 if (TagFromDeclSpec->hasNameForLinkage())
5011 return;
5013 // A well-formed anonymous tag must always be a TUK_Definition.
5014 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5016 // The type must match the tag exactly; no qualifiers allowed.
5017 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5018 Context.getTagDeclType(TagFromDeclSpec))) {
5019 if (getLangOpts().CPlusPlus)
5020 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5021 return;
5024 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5025 // An unnamed class with a typedef name for linkage purposes shall [be
5026 // C-like].
5028 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5029 // shouldn't happen, but there are constructs that the language rule doesn't
5030 // disallow for which we can't reasonably avoid computing linkage early.
5031 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5032 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5033 : NonCLikeKind();
5034 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5035 if (NonCLike || ChangesLinkage) {
5036 if (NonCLike.Kind == NonCLikeKind::Invalid)
5037 return;
5039 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5040 if (ChangesLinkage) {
5041 // If the linkage changes, we can't accept this as an extension.
5042 if (NonCLike.Kind == NonCLikeKind::None)
5043 DiagID = diag::err_typedef_changes_linkage;
5044 else
5045 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5048 SourceLocation FixitLoc =
5049 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5050 llvm::SmallString<40> TextToInsert;
5051 TextToInsert += ' ';
5052 TextToInsert += NewTD->getIdentifier()->getName();
5054 Diag(FixitLoc, DiagID)
5055 << isa<TypeAliasDecl>(NewTD)
5056 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5057 if (NonCLike.Kind != NonCLikeKind::None) {
5058 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5059 << NonCLike.Kind - 1 << NonCLike.Range;
5061 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5062 << NewTD << isa<TypeAliasDecl>(NewTD);
5064 if (ChangesLinkage)
5065 return;
5068 // Otherwise, set this as the anon-decl typedef for the tag.
5069 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5072 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5073 DeclSpec::TST T = DS.getTypeSpecType();
5074 switch (T) {
5075 case DeclSpec::TST_class:
5076 return 0;
5077 case DeclSpec::TST_struct:
5078 return 1;
5079 case DeclSpec::TST_interface:
5080 return 2;
5081 case DeclSpec::TST_union:
5082 return 3;
5083 case DeclSpec::TST_enum:
5084 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5085 if (ED->isScopedUsingClassTag())
5086 return 5;
5087 if (ED->isScoped())
5088 return 6;
5090 return 4;
5091 default:
5092 llvm_unreachable("unexpected type specifier");
5095 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5096 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5097 /// parameters to cope with template friend declarations.
5098 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5099 DeclSpec &DS,
5100 const ParsedAttributesView &DeclAttrs,
5101 MultiTemplateParamsArg TemplateParams,
5102 bool IsExplicitInstantiation,
5103 RecordDecl *&AnonRecord) {
5104 Decl *TagD = nullptr;
5105 TagDecl *Tag = nullptr;
5106 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5107 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5108 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5109 DS.getTypeSpecType() == DeclSpec::TST_union ||
5110 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5111 TagD = DS.getRepAsDecl();
5113 if (!TagD) // We probably had an error
5114 return nullptr;
5116 // Note that the above type specs guarantee that the
5117 // type rep is a Decl, whereas in many of the others
5118 // it's a Type.
5119 if (isa<TagDecl>(TagD))
5120 Tag = cast<TagDecl>(TagD);
5121 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5122 Tag = CTD->getTemplatedDecl();
5125 if (Tag) {
5126 handleTagNumbering(Tag, S);
5127 Tag->setFreeStanding();
5128 if (Tag->isInvalidDecl())
5129 return Tag;
5132 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5133 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5134 // or incomplete types shall not be restrict-qualified."
5135 if (TypeQuals & DeclSpec::TQ_restrict)
5136 Diag(DS.getRestrictSpecLoc(),
5137 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5138 << DS.getSourceRange();
5141 if (DS.isInlineSpecified())
5142 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5143 << getLangOpts().CPlusPlus17;
5145 if (DS.hasConstexprSpecifier()) {
5146 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5147 // and definitions of functions and variables.
5148 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5149 // the declaration of a function or function template
5150 if (Tag)
5151 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5152 << GetDiagnosticTypeSpecifierID(DS)
5153 << static_cast<int>(DS.getConstexprSpecifier());
5154 else
5155 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5156 << static_cast<int>(DS.getConstexprSpecifier());
5157 // Don't emit warnings after this error.
5158 return TagD;
5161 DiagnoseFunctionSpecifiers(DS);
5163 if (DS.isFriendSpecified()) {
5164 // If we're dealing with a decl but not a TagDecl, assume that
5165 // whatever routines created it handled the friendship aspect.
5166 if (TagD && !Tag)
5167 return nullptr;
5168 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5171 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5172 bool IsExplicitSpecialization =
5173 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5174 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5175 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5176 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5177 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5178 // nested-name-specifier unless it is an explicit instantiation
5179 // or an explicit specialization.
5181 // FIXME: We allow class template partial specializations here too, per the
5182 // obvious intent of DR1819.
5184 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5185 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5186 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5187 return nullptr;
5190 // Track whether this decl-specifier declares anything.
5191 bool DeclaresAnything = true;
5193 // Handle anonymous struct definitions.
5194 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5195 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5196 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5197 if (getLangOpts().CPlusPlus ||
5198 Record->getDeclContext()->isRecord()) {
5199 // If CurContext is a DeclContext that can contain statements,
5200 // RecursiveASTVisitor won't visit the decls that
5201 // BuildAnonymousStructOrUnion() will put into CurContext.
5202 // Also store them here so that they can be part of the
5203 // DeclStmt that gets created in this case.
5204 // FIXME: Also return the IndirectFieldDecls created by
5205 // BuildAnonymousStructOr union, for the same reason?
5206 if (CurContext->isFunctionOrMethod())
5207 AnonRecord = Record;
5208 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5209 Context.getPrintingPolicy());
5212 DeclaresAnything = false;
5216 // C11 6.7.2.1p2:
5217 // A struct-declaration that does not declare an anonymous structure or
5218 // anonymous union shall contain a struct-declarator-list.
5220 // This rule also existed in C89 and C99; the grammar for struct-declaration
5221 // did not permit a struct-declaration without a struct-declarator-list.
5222 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5223 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5224 // Check for Microsoft C extension: anonymous struct/union member.
5225 // Handle 2 kinds of anonymous struct/union:
5226 // struct STRUCT;
5227 // union UNION;
5228 // and
5229 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5230 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5231 if ((Tag && Tag->getDeclName()) ||
5232 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5233 RecordDecl *Record = nullptr;
5234 if (Tag)
5235 Record = dyn_cast<RecordDecl>(Tag);
5236 else if (const RecordType *RT =
5237 DS.getRepAsType().get()->getAsStructureType())
5238 Record = RT->getDecl();
5239 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5240 Record = UT->getDecl();
5242 if (Record && getLangOpts().MicrosoftExt) {
5243 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5244 << Record->isUnion() << DS.getSourceRange();
5245 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5248 DeclaresAnything = false;
5252 // Skip all the checks below if we have a type error.
5253 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5254 (TagD && TagD->isInvalidDecl()))
5255 return TagD;
5257 if (getLangOpts().CPlusPlus &&
5258 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5259 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5260 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5261 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5262 DeclaresAnything = false;
5264 if (!DS.isMissingDeclaratorOk()) {
5265 // Customize diagnostic for a typedef missing a name.
5266 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5267 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5268 << DS.getSourceRange();
5269 else
5270 DeclaresAnything = false;
5273 if (DS.isModulePrivateSpecified() &&
5274 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5275 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5276 << llvm::to_underlying(Tag->getTagKind())
5277 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5279 ActOnDocumentableDecl(TagD);
5281 // C 6.7/2:
5282 // A declaration [...] shall declare at least a declarator [...], a tag,
5283 // or the members of an enumeration.
5284 // C++ [dcl.dcl]p3:
5285 // [If there are no declarators], and except for the declaration of an
5286 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5287 // names into the program, or shall redeclare a name introduced by a
5288 // previous declaration.
5289 if (!DeclaresAnything) {
5290 // In C, we allow this as a (popular) extension / bug. Don't bother
5291 // producing further diagnostics for redundant qualifiers after this.
5292 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5293 ? diag::err_no_declarators
5294 : diag::ext_no_declarators)
5295 << DS.getSourceRange();
5296 return TagD;
5299 // C++ [dcl.stc]p1:
5300 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5301 // init-declarator-list of the declaration shall not be empty.
5302 // C++ [dcl.fct.spec]p1:
5303 // If a cv-qualifier appears in a decl-specifier-seq, the
5304 // init-declarator-list of the declaration shall not be empty.
5306 // Spurious qualifiers here appear to be valid in C.
5307 unsigned DiagID = diag::warn_standalone_specifier;
5308 if (getLangOpts().CPlusPlus)
5309 DiagID = diag::ext_standalone_specifier;
5311 // Note that a linkage-specification sets a storage class, but
5312 // 'extern "C" struct foo;' is actually valid and not theoretically
5313 // useless.
5314 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5315 if (SCS == DeclSpec::SCS_mutable)
5316 // Since mutable is not a viable storage class specifier in C, there is
5317 // no reason to treat it as an extension. Instead, diagnose as an error.
5318 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5319 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5320 Diag(DS.getStorageClassSpecLoc(), DiagID)
5321 << DeclSpec::getSpecifierName(SCS);
5324 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5325 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5326 << DeclSpec::getSpecifierName(TSCS);
5327 if (DS.getTypeQualifiers()) {
5328 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5329 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5330 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5331 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5332 // Restrict is covered above.
5333 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5334 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5335 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5336 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5339 // Warn about ignored type attributes, for example:
5340 // __attribute__((aligned)) struct A;
5341 // Attributes should be placed after tag to apply to type declaration.
5342 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5343 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5344 if (TypeSpecType == DeclSpec::TST_class ||
5345 TypeSpecType == DeclSpec::TST_struct ||
5346 TypeSpecType == DeclSpec::TST_interface ||
5347 TypeSpecType == DeclSpec::TST_union ||
5348 TypeSpecType == DeclSpec::TST_enum) {
5349 for (const ParsedAttr &AL : DS.getAttributes())
5350 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5351 ? diag::err_declspec_keyword_has_no_effect
5352 : diag::warn_declspec_attribute_ignored)
5353 << AL << GetDiagnosticTypeSpecifierID(DS);
5354 for (const ParsedAttr &AL : DeclAttrs)
5355 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5356 ? diag::err_declspec_keyword_has_no_effect
5357 : diag::warn_declspec_attribute_ignored)
5358 << AL << GetDiagnosticTypeSpecifierID(DS);
5362 return TagD;
5365 /// We are trying to inject an anonymous member into the given scope;
5366 /// check if there's an existing declaration that can't be overloaded.
5368 /// \return true if this is a forbidden redeclaration
5369 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5370 DeclContext *Owner,
5371 DeclarationName Name,
5372 SourceLocation NameLoc, bool IsUnion,
5373 StorageClass SC) {
5374 LookupResult R(SemaRef, Name, NameLoc,
5375 Owner->isRecord() ? Sema::LookupMemberName
5376 : Sema::LookupOrdinaryName,
5377 Sema::ForVisibleRedeclaration);
5378 if (!SemaRef.LookupName(R, S)) return false;
5380 // Pick a representative declaration.
5381 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5382 assert(PrevDecl && "Expected a non-null Decl");
5384 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5385 return false;
5387 if (SC == StorageClass::SC_None &&
5388 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5389 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5390 if (!Owner->isRecord())
5391 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5392 return false;
5395 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5396 << IsUnion << Name;
5397 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5399 return true;
5402 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5403 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5404 DiagPlaceholderFieldDeclDefinitions(RD);
5407 /// Emit diagnostic warnings for placeholder members.
5408 /// We can only do that after the class is fully constructed,
5409 /// as anonymous union/structs can insert placeholders
5410 /// in their parent scope (which might be a Record).
5411 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5412 if (!getLangOpts().CPlusPlus)
5413 return;
5415 // This function can be parsed before we have validated the
5416 // structure as an anonymous struct
5417 if (Record->isAnonymousStructOrUnion())
5418 return;
5420 const NamedDecl *First = 0;
5421 for (const Decl *D : Record->decls()) {
5422 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5423 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5424 continue;
5425 if (!First)
5426 First = ND;
5427 else
5428 DiagPlaceholderVariableDefinition(ND->getLocation());
5432 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5433 /// anonymous struct or union AnonRecord into the owning context Owner
5434 /// and scope S. This routine will be invoked just after we realize
5435 /// that an unnamed union or struct is actually an anonymous union or
5436 /// struct, e.g.,
5438 /// @code
5439 /// union {
5440 /// int i;
5441 /// float f;
5442 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5443 /// // f into the surrounding scope.x
5444 /// @endcode
5446 /// This routine is recursive, injecting the names of nested anonymous
5447 /// structs/unions into the owning context and scope as well.
5448 static bool
5449 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5450 RecordDecl *AnonRecord, AccessSpecifier AS,
5451 StorageClass SC,
5452 SmallVectorImpl<NamedDecl *> &Chaining) {
5453 bool Invalid = false;
5455 // Look every FieldDecl and IndirectFieldDecl with a name.
5456 for (auto *D : AnonRecord->decls()) {
5457 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5458 cast<NamedDecl>(D)->getDeclName()) {
5459 ValueDecl *VD = cast<ValueDecl>(D);
5460 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5461 VD->getLocation(), AnonRecord->isUnion(),
5462 SC)) {
5463 // C++ [class.union]p2:
5464 // The names of the members of an anonymous union shall be
5465 // distinct from the names of any other entity in the
5466 // scope in which the anonymous union is declared.
5467 Invalid = true;
5468 } else {
5469 // C++ [class.union]p2:
5470 // For the purpose of name lookup, after the anonymous union
5471 // definition, the members of the anonymous union are
5472 // considered to have been defined in the scope in which the
5473 // anonymous union is declared.
5474 unsigned OldChainingSize = Chaining.size();
5475 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5476 Chaining.append(IF->chain_begin(), IF->chain_end());
5477 else
5478 Chaining.push_back(VD);
5480 assert(Chaining.size() >= 2);
5481 NamedDecl **NamedChain =
5482 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5483 for (unsigned i = 0; i < Chaining.size(); i++)
5484 NamedChain[i] = Chaining[i];
5486 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5487 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5488 VD->getType(), {NamedChain, Chaining.size()});
5490 for (const auto *Attr : VD->attrs())
5491 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5493 IndirectField->setAccess(AS);
5494 IndirectField->setImplicit();
5495 SemaRef.PushOnScopeChains(IndirectField, S);
5497 // That includes picking up the appropriate access specifier.
5498 if (AS != AS_none) IndirectField->setAccess(AS);
5500 Chaining.resize(OldChainingSize);
5505 return Invalid;
5508 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5509 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5510 /// illegal input values are mapped to SC_None.
5511 static StorageClass
5512 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5513 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5514 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5515 "Parser allowed 'typedef' as storage class VarDecl.");
5516 switch (StorageClassSpec) {
5517 case DeclSpec::SCS_unspecified: return SC_None;
5518 case DeclSpec::SCS_extern:
5519 if (DS.isExternInLinkageSpec())
5520 return SC_None;
5521 return SC_Extern;
5522 case DeclSpec::SCS_static: return SC_Static;
5523 case DeclSpec::SCS_auto: return SC_Auto;
5524 case DeclSpec::SCS_register: return SC_Register;
5525 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5526 // Illegal SCSs map to None: error reporting is up to the caller.
5527 case DeclSpec::SCS_mutable: // Fall through.
5528 case DeclSpec::SCS_typedef: return SC_None;
5530 llvm_unreachable("unknown storage class specifier");
5533 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5534 assert(Record->hasInClassInitializer());
5536 for (const auto *I : Record->decls()) {
5537 const auto *FD = dyn_cast<FieldDecl>(I);
5538 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5539 FD = IFD->getAnonField();
5540 if (FD && FD->hasInClassInitializer())
5541 return FD->getLocation();
5544 llvm_unreachable("couldn't find in-class initializer");
5547 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5548 SourceLocation DefaultInitLoc) {
5549 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5550 return;
5552 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5553 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5556 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5557 CXXRecordDecl *AnonUnion) {
5558 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5559 return;
5561 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5564 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5565 /// anonymous structure or union. Anonymous unions are a C++ feature
5566 /// (C++ [class.union]) and a C11 feature; anonymous structures
5567 /// are a C11 feature and GNU C++ extension.
5568 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5569 AccessSpecifier AS,
5570 RecordDecl *Record,
5571 const PrintingPolicy &Policy) {
5572 DeclContext *Owner = Record->getDeclContext();
5574 // Diagnose whether this anonymous struct/union is an extension.
5575 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5576 Diag(Record->getLocation(), diag::ext_anonymous_union);
5577 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5578 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5579 else if (!Record->isUnion() && !getLangOpts().C11)
5580 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5582 // C and C++ require different kinds of checks for anonymous
5583 // structs/unions.
5584 bool Invalid = false;
5585 if (getLangOpts().CPlusPlus) {
5586 const char *PrevSpec = nullptr;
5587 if (Record->isUnion()) {
5588 // C++ [class.union]p6:
5589 // C++17 [class.union.anon]p2:
5590 // Anonymous unions declared in a named namespace or in the
5591 // global namespace shall be declared static.
5592 unsigned DiagID;
5593 DeclContext *OwnerScope = Owner->getRedeclContext();
5594 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5595 (OwnerScope->isTranslationUnit() ||
5596 (OwnerScope->isNamespace() &&
5597 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5598 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5599 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5601 // Recover by adding 'static'.
5602 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5603 PrevSpec, DiagID, Policy);
5605 // C++ [class.union]p6:
5606 // A storage class is not allowed in a declaration of an
5607 // anonymous union in a class scope.
5608 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5609 isa<RecordDecl>(Owner)) {
5610 Diag(DS.getStorageClassSpecLoc(),
5611 diag::err_anonymous_union_with_storage_spec)
5612 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5614 // Recover by removing the storage specifier.
5615 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5616 SourceLocation(),
5617 PrevSpec, DiagID, Context.getPrintingPolicy());
5621 // Ignore const/volatile/restrict qualifiers.
5622 if (DS.getTypeQualifiers()) {
5623 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5624 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5625 << Record->isUnion() << "const"
5626 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5627 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5628 Diag(DS.getVolatileSpecLoc(),
5629 diag::ext_anonymous_struct_union_qualified)
5630 << Record->isUnion() << "volatile"
5631 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5632 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5633 Diag(DS.getRestrictSpecLoc(),
5634 diag::ext_anonymous_struct_union_qualified)
5635 << Record->isUnion() << "restrict"
5636 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5637 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5638 Diag(DS.getAtomicSpecLoc(),
5639 diag::ext_anonymous_struct_union_qualified)
5640 << Record->isUnion() << "_Atomic"
5641 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5642 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5643 Diag(DS.getUnalignedSpecLoc(),
5644 diag::ext_anonymous_struct_union_qualified)
5645 << Record->isUnion() << "__unaligned"
5646 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5648 DS.ClearTypeQualifiers();
5651 // C++ [class.union]p2:
5652 // The member-specification of an anonymous union shall only
5653 // define non-static data members. [Note: nested types and
5654 // functions cannot be declared within an anonymous union. ]
5655 for (auto *Mem : Record->decls()) {
5656 // Ignore invalid declarations; we already diagnosed them.
5657 if (Mem->isInvalidDecl())
5658 continue;
5660 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5661 // C++ [class.union]p3:
5662 // An anonymous union shall not have private or protected
5663 // members (clause 11).
5664 assert(FD->getAccess() != AS_none);
5665 if (FD->getAccess() != AS_public) {
5666 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5667 << Record->isUnion() << (FD->getAccess() == AS_protected);
5668 Invalid = true;
5671 // C++ [class.union]p1
5672 // An object of a class with a non-trivial constructor, a non-trivial
5673 // copy constructor, a non-trivial destructor, or a non-trivial copy
5674 // assignment operator cannot be a member of a union, nor can an
5675 // array of such objects.
5676 if (CheckNontrivialField(FD))
5677 Invalid = true;
5678 } else if (Mem->isImplicit()) {
5679 // Any implicit members are fine.
5680 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5681 // This is a type that showed up in an
5682 // elaborated-type-specifier inside the anonymous struct or
5683 // union, but which actually declares a type outside of the
5684 // anonymous struct or union. It's okay.
5685 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5686 if (!MemRecord->isAnonymousStructOrUnion() &&
5687 MemRecord->getDeclName()) {
5688 // Visual C++ allows type definition in anonymous struct or union.
5689 if (getLangOpts().MicrosoftExt)
5690 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5691 << Record->isUnion();
5692 else {
5693 // This is a nested type declaration.
5694 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5695 << Record->isUnion();
5696 Invalid = true;
5698 } else {
5699 // This is an anonymous type definition within another anonymous type.
5700 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5701 // not part of standard C++.
5702 Diag(MemRecord->getLocation(),
5703 diag::ext_anonymous_record_with_anonymous_type)
5704 << Record->isUnion();
5706 } else if (isa<AccessSpecDecl>(Mem)) {
5707 // Any access specifier is fine.
5708 } else if (isa<StaticAssertDecl>(Mem)) {
5709 // In C++1z, static_assert declarations are also fine.
5710 } else {
5711 // We have something that isn't a non-static data
5712 // member. Complain about it.
5713 unsigned DK = diag::err_anonymous_record_bad_member;
5714 if (isa<TypeDecl>(Mem))
5715 DK = diag::err_anonymous_record_with_type;
5716 else if (isa<FunctionDecl>(Mem))
5717 DK = diag::err_anonymous_record_with_function;
5718 else if (isa<VarDecl>(Mem))
5719 DK = diag::err_anonymous_record_with_static;
5721 // Visual C++ allows type definition in anonymous struct or union.
5722 if (getLangOpts().MicrosoftExt &&
5723 DK == diag::err_anonymous_record_with_type)
5724 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5725 << Record->isUnion();
5726 else {
5727 Diag(Mem->getLocation(), DK) << Record->isUnion();
5728 Invalid = true;
5733 // C++11 [class.union]p8 (DR1460):
5734 // At most one variant member of a union may have a
5735 // brace-or-equal-initializer.
5736 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5737 Owner->isRecord())
5738 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5739 cast<CXXRecordDecl>(Record));
5742 if (!Record->isUnion() && !Owner->isRecord()) {
5743 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5744 << getLangOpts().CPlusPlus;
5745 Invalid = true;
5748 // C++ [dcl.dcl]p3:
5749 // [If there are no declarators], and except for the declaration of an
5750 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5751 // names into the program
5752 // C++ [class.mem]p2:
5753 // each such member-declaration shall either declare at least one member
5754 // name of the class or declare at least one unnamed bit-field
5756 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5757 if (getLangOpts().CPlusPlus && Record->field_empty())
5758 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5760 // Mock up a declarator.
5761 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5762 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5763 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5764 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5766 // Create a declaration for this anonymous struct/union.
5767 NamedDecl *Anon = nullptr;
5768 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5769 Anon = FieldDecl::Create(
5770 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5771 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5772 /*BitWidth=*/nullptr, /*Mutable=*/false,
5773 /*InitStyle=*/ICIS_NoInit);
5774 Anon->setAccess(AS);
5775 ProcessDeclAttributes(S, Anon, Dc);
5777 if (getLangOpts().CPlusPlus)
5778 FieldCollector->Add(cast<FieldDecl>(Anon));
5779 } else {
5780 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5781 if (SCSpec == DeclSpec::SCS_mutable) {
5782 // mutable can only appear on non-static class members, so it's always
5783 // an error here
5784 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5785 Invalid = true;
5786 SC = SC_None;
5789 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5790 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5791 Context.getTypeDeclType(Record), TInfo, SC);
5792 ProcessDeclAttributes(S, Anon, Dc);
5794 // Default-initialize the implicit variable. This initialization will be
5795 // trivial in almost all cases, except if a union member has an in-class
5796 // initializer:
5797 // union { int n = 0; };
5798 ActOnUninitializedDecl(Anon);
5800 Anon->setImplicit();
5802 // Mark this as an anonymous struct/union type.
5803 Record->setAnonymousStructOrUnion(true);
5805 // Add the anonymous struct/union object to the current
5806 // context. We'll be referencing this object when we refer to one of
5807 // its members.
5808 Owner->addDecl(Anon);
5810 // Inject the members of the anonymous struct/union into the owning
5811 // context and into the identifier resolver chain for name lookup
5812 // purposes.
5813 SmallVector<NamedDecl*, 2> Chain;
5814 Chain.push_back(Anon);
5816 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5817 Chain))
5818 Invalid = true;
5820 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5821 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5822 MangleNumberingContext *MCtx;
5823 Decl *ManglingContextDecl;
5824 std::tie(MCtx, ManglingContextDecl) =
5825 getCurrentMangleNumberContext(NewVD->getDeclContext());
5826 if (MCtx) {
5827 Context.setManglingNumber(
5828 NewVD, MCtx->getManglingNumber(
5829 NewVD, getMSManglingNumber(getLangOpts(), S)));
5830 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5835 if (Invalid)
5836 Anon->setInvalidDecl();
5838 return Anon;
5841 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5842 /// Microsoft C anonymous structure.
5843 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5844 /// Example:
5846 /// struct A { int a; };
5847 /// struct B { struct A; int b; };
5849 /// void foo() {
5850 /// B var;
5851 /// var.a = 3;
5852 /// }
5854 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5855 RecordDecl *Record) {
5856 assert(Record && "expected a record!");
5858 // Mock up a declarator.
5859 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5860 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5861 assert(TInfo && "couldn't build declarator info for anonymous struct");
5863 auto *ParentDecl = cast<RecordDecl>(CurContext);
5864 QualType RecTy = Context.getTypeDeclType(Record);
5866 // Create a declaration for this anonymous struct.
5867 NamedDecl *Anon =
5868 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5869 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5870 /*BitWidth=*/nullptr, /*Mutable=*/false,
5871 /*InitStyle=*/ICIS_NoInit);
5872 Anon->setImplicit();
5874 // Add the anonymous struct object to the current context.
5875 CurContext->addDecl(Anon);
5877 // Inject the members of the anonymous struct into the current
5878 // context and into the identifier resolver chain for name lookup
5879 // purposes.
5880 SmallVector<NamedDecl*, 2> Chain;
5881 Chain.push_back(Anon);
5883 RecordDecl *RecordDef = Record->getDefinition();
5884 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5885 diag::err_field_incomplete_or_sizeless) ||
5886 InjectAnonymousStructOrUnionMembers(
5887 *this, S, CurContext, RecordDef, AS_none,
5888 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5889 Anon->setInvalidDecl();
5890 ParentDecl->setInvalidDecl();
5893 return Anon;
5896 /// GetNameForDeclarator - Determine the full declaration name for the
5897 /// given Declarator.
5898 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5899 return GetNameFromUnqualifiedId(D.getName());
5902 /// Retrieves the declaration name from a parsed unqualified-id.
5903 DeclarationNameInfo
5904 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5905 DeclarationNameInfo NameInfo;
5906 NameInfo.setLoc(Name.StartLocation);
5908 switch (Name.getKind()) {
5910 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5911 case UnqualifiedIdKind::IK_Identifier:
5912 NameInfo.setName(Name.Identifier);
5913 return NameInfo;
5915 case UnqualifiedIdKind::IK_DeductionGuideName: {
5916 // C++ [temp.deduct.guide]p3:
5917 // The simple-template-id shall name a class template specialization.
5918 // The template-name shall be the same identifier as the template-name
5919 // of the simple-template-id.
5920 // These together intend to imply that the template-name shall name a
5921 // class template.
5922 // FIXME: template<typename T> struct X {};
5923 // template<typename T> using Y = X<T>;
5924 // Y(int) -> Y<int>;
5925 // satisfies these rules but does not name a class template.
5926 TemplateName TN = Name.TemplateName.get().get();
5927 auto *Template = TN.getAsTemplateDecl();
5928 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5929 Diag(Name.StartLocation,
5930 diag::err_deduction_guide_name_not_class_template)
5931 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5932 if (Template)
5933 Diag(Template->getLocation(), diag::note_template_decl_here);
5934 return DeclarationNameInfo();
5937 NameInfo.setName(
5938 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5939 return NameInfo;
5942 case UnqualifiedIdKind::IK_OperatorFunctionId:
5943 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5944 Name.OperatorFunctionId.Operator));
5945 NameInfo.setCXXOperatorNameRange(SourceRange(
5946 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5947 return NameInfo;
5949 case UnqualifiedIdKind::IK_LiteralOperatorId:
5950 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5951 Name.Identifier));
5952 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5953 return NameInfo;
5955 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5956 TypeSourceInfo *TInfo;
5957 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5958 if (Ty.isNull())
5959 return DeclarationNameInfo();
5960 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5961 Context.getCanonicalType(Ty)));
5962 NameInfo.setNamedTypeInfo(TInfo);
5963 return NameInfo;
5966 case UnqualifiedIdKind::IK_ConstructorName: {
5967 TypeSourceInfo *TInfo;
5968 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5969 if (Ty.isNull())
5970 return DeclarationNameInfo();
5971 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5972 Context.getCanonicalType(Ty)));
5973 NameInfo.setNamedTypeInfo(TInfo);
5974 return NameInfo;
5977 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5978 // In well-formed code, we can only have a constructor
5979 // template-id that refers to the current context, so go there
5980 // to find the actual type being constructed.
5981 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5982 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5983 return DeclarationNameInfo();
5985 // Determine the type of the class being constructed.
5986 QualType CurClassType = Context.getTypeDeclType(CurClass);
5988 // FIXME: Check two things: that the template-id names the same type as
5989 // CurClassType, and that the template-id does not occur when the name
5990 // was qualified.
5992 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5993 Context.getCanonicalType(CurClassType)));
5994 // FIXME: should we retrieve TypeSourceInfo?
5995 NameInfo.setNamedTypeInfo(nullptr);
5996 return NameInfo;
5999 case UnqualifiedIdKind::IK_DestructorName: {
6000 TypeSourceInfo *TInfo;
6001 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6002 if (Ty.isNull())
6003 return DeclarationNameInfo();
6004 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6005 Context.getCanonicalType(Ty)));
6006 NameInfo.setNamedTypeInfo(TInfo);
6007 return NameInfo;
6010 case UnqualifiedIdKind::IK_TemplateId: {
6011 TemplateName TName = Name.TemplateId->Template.get();
6012 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6013 return Context.getNameForTemplate(TName, TNameLoc);
6016 } // switch (Name.getKind())
6018 llvm_unreachable("Unknown name kind");
6021 static QualType getCoreType(QualType Ty) {
6022 do {
6023 if (Ty->isPointerType() || Ty->isReferenceType())
6024 Ty = Ty->getPointeeType();
6025 else if (Ty->isArrayType())
6026 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6027 else
6028 return Ty.withoutLocalFastQualifiers();
6029 } while (true);
6032 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6033 /// and Definition have "nearly" matching parameters. This heuristic is
6034 /// used to improve diagnostics in the case where an out-of-line function
6035 /// definition doesn't match any declaration within the class or namespace.
6036 /// Also sets Params to the list of indices to the parameters that differ
6037 /// between the declaration and the definition. If hasSimilarParameters
6038 /// returns true and Params is empty, then all of the parameters match.
6039 static bool hasSimilarParameters(ASTContext &Context,
6040 FunctionDecl *Declaration,
6041 FunctionDecl *Definition,
6042 SmallVectorImpl<unsigned> &Params) {
6043 Params.clear();
6044 if (Declaration->param_size() != Definition->param_size())
6045 return false;
6046 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6047 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6048 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6050 // The parameter types are identical
6051 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6052 continue;
6054 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6055 QualType DefParamBaseTy = getCoreType(DefParamTy);
6056 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6057 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6059 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6060 (DeclTyName && DeclTyName == DefTyName))
6061 Params.push_back(Idx);
6062 else // The two parameters aren't even close
6063 return false;
6066 return true;
6069 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6070 /// declarator needs to be rebuilt in the current instantiation.
6071 /// Any bits of declarator which appear before the name are valid for
6072 /// consideration here. That's specifically the type in the decl spec
6073 /// and the base type in any member-pointer chunks.
6074 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6075 DeclarationName Name) {
6076 // The types we specifically need to rebuild are:
6077 // - typenames, typeofs, and decltypes
6078 // - types which will become injected class names
6079 // Of course, we also need to rebuild any type referencing such a
6080 // type. It's safest to just say "dependent", but we call out a
6081 // few cases here.
6083 DeclSpec &DS = D.getMutableDeclSpec();
6084 switch (DS.getTypeSpecType()) {
6085 case DeclSpec::TST_typename:
6086 case DeclSpec::TST_typeofType:
6087 case DeclSpec::TST_typeof_unqualType:
6088 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6089 #include "clang/Basic/TransformTypeTraits.def"
6090 case DeclSpec::TST_atomic: {
6091 // Grab the type from the parser.
6092 TypeSourceInfo *TSI = nullptr;
6093 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6094 if (T.isNull() || !T->isInstantiationDependentType()) break;
6096 // Make sure there's a type source info. This isn't really much
6097 // of a waste; most dependent types should have type source info
6098 // attached already.
6099 if (!TSI)
6100 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6102 // Rebuild the type in the current instantiation.
6103 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6104 if (!TSI) return true;
6106 // Store the new type back in the decl spec.
6107 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6108 DS.UpdateTypeRep(LocType);
6109 break;
6112 case DeclSpec::TST_decltype:
6113 case DeclSpec::TST_typeof_unqualExpr:
6114 case DeclSpec::TST_typeofExpr: {
6115 Expr *E = DS.getRepAsExpr();
6116 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6117 if (Result.isInvalid()) return true;
6118 DS.UpdateExprRep(Result.get());
6119 break;
6122 default:
6123 // Nothing to do for these decl specs.
6124 break;
6127 // It doesn't matter what order we do this in.
6128 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6129 DeclaratorChunk &Chunk = D.getTypeObject(I);
6131 // The only type information in the declarator which can come
6132 // before the declaration name is the base type of a member
6133 // pointer.
6134 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6135 continue;
6137 // Rebuild the scope specifier in-place.
6138 CXXScopeSpec &SS = Chunk.Mem.Scope();
6139 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6140 return true;
6143 return false;
6146 /// Returns true if the declaration is declared in a system header or from a
6147 /// system macro.
6148 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6149 return SM.isInSystemHeader(D->getLocation()) ||
6150 SM.isInSystemMacro(D->getLocation());
6153 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6154 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6155 // of system decl.
6156 if (D->getPreviousDecl() || D->isImplicit())
6157 return;
6158 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6159 if (Status != ReservedIdentifierStatus::NotReserved &&
6160 !isFromSystemHeader(Context.getSourceManager(), D)) {
6161 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6162 << D << static_cast<int>(Status);
6166 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6167 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6169 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6170 // declaration only if the `bind_to_declaration` extension is set.
6171 SmallVector<FunctionDecl *, 4> Bases;
6172 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6173 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6174 implementation_extension_bind_to_declaration))
6175 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6176 S, D, MultiTemplateParamsArg(), Bases);
6178 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6180 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6181 Dcl && Dcl->getDeclContext()->isFileContext())
6182 Dcl->setTopLevelDeclInObjCContainer();
6184 if (!Bases.empty())
6185 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6187 return Dcl;
6190 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6191 /// If T is the name of a class, then each of the following shall have a
6192 /// name different from T:
6193 /// - every static data member of class T;
6194 /// - every member function of class T
6195 /// - every member of class T that is itself a type;
6196 /// \returns true if the declaration name violates these rules.
6197 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6198 DeclarationNameInfo NameInfo) {
6199 DeclarationName Name = NameInfo.getName();
6201 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6202 while (Record && Record->isAnonymousStructOrUnion())
6203 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6204 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6205 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6206 return true;
6209 return false;
6212 /// Diagnose a declaration whose declarator-id has the given
6213 /// nested-name-specifier.
6215 /// \param SS The nested-name-specifier of the declarator-id.
6217 /// \param DC The declaration context to which the nested-name-specifier
6218 /// resolves.
6220 /// \param Name The name of the entity being declared.
6222 /// \param Loc The location of the name of the entity being declared.
6224 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6225 /// we're declaring an explicit / partial specialization / instantiation.
6227 /// \returns true if we cannot safely recover from this error, false otherwise.
6228 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6229 DeclarationName Name,
6230 SourceLocation Loc, bool IsTemplateId) {
6231 DeclContext *Cur = CurContext;
6232 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6233 Cur = Cur->getParent();
6235 // If the user provided a superfluous scope specifier that refers back to the
6236 // class in which the entity is already declared, diagnose and ignore it.
6238 // class X {
6239 // void X::f();
6240 // };
6242 // Note, it was once ill-formed to give redundant qualification in all
6243 // contexts, but that rule was removed by DR482.
6244 if (Cur->Equals(DC)) {
6245 if (Cur->isRecord()) {
6246 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6247 : diag::err_member_extra_qualification)
6248 << Name << FixItHint::CreateRemoval(SS.getRange());
6249 SS.clear();
6250 } else {
6251 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6253 return false;
6256 // Check whether the qualifying scope encloses the scope of the original
6257 // declaration. For a template-id, we perform the checks in
6258 // CheckTemplateSpecializationScope.
6259 if (!Cur->Encloses(DC) && !IsTemplateId) {
6260 if (Cur->isRecord())
6261 Diag(Loc, diag::err_member_qualification)
6262 << Name << SS.getRange();
6263 else if (isa<TranslationUnitDecl>(DC))
6264 Diag(Loc, diag::err_invalid_declarator_global_scope)
6265 << Name << SS.getRange();
6266 else if (isa<FunctionDecl>(Cur))
6267 Diag(Loc, diag::err_invalid_declarator_in_function)
6268 << Name << SS.getRange();
6269 else if (isa<BlockDecl>(Cur))
6270 Diag(Loc, diag::err_invalid_declarator_in_block)
6271 << Name << SS.getRange();
6272 else if (isa<ExportDecl>(Cur)) {
6273 if (!isa<NamespaceDecl>(DC))
6274 Diag(Loc, diag::err_export_non_namespace_scope_name)
6275 << Name << SS.getRange();
6276 else
6277 // The cases that DC is not NamespaceDecl should be handled in
6278 // CheckRedeclarationExported.
6279 return false;
6280 } else
6281 Diag(Loc, diag::err_invalid_declarator_scope)
6282 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6284 return true;
6287 if (Cur->isRecord()) {
6288 // Cannot qualify members within a class.
6289 Diag(Loc, diag::err_member_qualification)
6290 << Name << SS.getRange();
6291 SS.clear();
6293 // C++ constructors and destructors with incorrect scopes can break
6294 // our AST invariants by having the wrong underlying types. If
6295 // that's the case, then drop this declaration entirely.
6296 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6297 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6298 !Context.hasSameType(Name.getCXXNameType(),
6299 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6300 return true;
6302 return false;
6305 // C++11 [dcl.meaning]p1:
6306 // [...] "The nested-name-specifier of the qualified declarator-id shall
6307 // not begin with a decltype-specifer"
6308 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6309 while (SpecLoc.getPrefix())
6310 SpecLoc = SpecLoc.getPrefix();
6311 if (isa_and_nonnull<DecltypeType>(
6312 SpecLoc.getNestedNameSpecifier()->getAsType()))
6313 Diag(Loc, diag::err_decltype_in_declarator)
6314 << SpecLoc.getTypeLoc().getSourceRange();
6316 return false;
6319 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6320 MultiTemplateParamsArg TemplateParamLists) {
6321 // TODO: consider using NameInfo for diagnostic.
6322 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6323 DeclarationName Name = NameInfo.getName();
6325 // All of these full declarators require an identifier. If it doesn't have
6326 // one, the ParsedFreeStandingDeclSpec action should be used.
6327 if (D.isDecompositionDeclarator()) {
6328 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6329 } else if (!Name) {
6330 if (!D.isInvalidType()) // Reject this if we think it is valid.
6331 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6332 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6333 return nullptr;
6334 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6335 return nullptr;
6337 // The scope passed in may not be a decl scope. Zip up the scope tree until
6338 // we find one that is.
6339 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6340 (S->getFlags() & Scope::TemplateParamScope) != 0)
6341 S = S->getParent();
6343 DeclContext *DC = CurContext;
6344 if (D.getCXXScopeSpec().isInvalid())
6345 D.setInvalidType();
6346 else if (D.getCXXScopeSpec().isSet()) {
6347 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6348 UPPC_DeclarationQualifier))
6349 return nullptr;
6351 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6352 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6353 if (!DC || isa<EnumDecl>(DC)) {
6354 // If we could not compute the declaration context, it's because the
6355 // declaration context is dependent but does not refer to a class,
6356 // class template, or class template partial specialization. Complain
6357 // and return early, to avoid the coming semantic disaster.
6358 Diag(D.getIdentifierLoc(),
6359 diag::err_template_qualified_declarator_no_match)
6360 << D.getCXXScopeSpec().getScopeRep()
6361 << D.getCXXScopeSpec().getRange();
6362 return nullptr;
6364 bool IsDependentContext = DC->isDependentContext();
6366 if (!IsDependentContext &&
6367 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6368 return nullptr;
6370 // If a class is incomplete, do not parse entities inside it.
6371 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6372 Diag(D.getIdentifierLoc(),
6373 diag::err_member_def_undefined_record)
6374 << Name << DC << D.getCXXScopeSpec().getRange();
6375 return nullptr;
6377 if (!D.getDeclSpec().isFriendSpecified()) {
6378 if (diagnoseQualifiedDeclaration(
6379 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6380 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6381 if (DC->isRecord())
6382 return nullptr;
6384 D.setInvalidType();
6388 // Check whether we need to rebuild the type of the given
6389 // declaration in the current instantiation.
6390 if (EnteringContext && IsDependentContext &&
6391 TemplateParamLists.size() != 0) {
6392 ContextRAII SavedContext(*this, DC);
6393 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6394 D.setInvalidType();
6398 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6399 QualType R = TInfo->getType();
6401 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6402 UPPC_DeclarationType))
6403 D.setInvalidType();
6405 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6406 forRedeclarationInCurContext());
6408 // See if this is a redefinition of a variable in the same scope.
6409 if (!D.getCXXScopeSpec().isSet()) {
6410 bool IsLinkageLookup = false;
6411 bool CreateBuiltins = false;
6413 // If the declaration we're planning to build will be a function
6414 // or object with linkage, then look for another declaration with
6415 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6417 // If the declaration we're planning to build will be declared with
6418 // external linkage in the translation unit, create any builtin with
6419 // the same name.
6420 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6421 /* Do nothing*/;
6422 else if (CurContext->isFunctionOrMethod() &&
6423 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6424 R->isFunctionType())) {
6425 IsLinkageLookup = true;
6426 CreateBuiltins =
6427 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6428 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6429 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6430 CreateBuiltins = true;
6432 if (IsLinkageLookup) {
6433 Previous.clear(LookupRedeclarationWithLinkage);
6434 Previous.setRedeclarationKind(ForExternalRedeclaration);
6437 LookupName(Previous, S, CreateBuiltins);
6438 } else { // Something like "int foo::x;"
6439 LookupQualifiedName(Previous, DC);
6441 // C++ [dcl.meaning]p1:
6442 // When the declarator-id is qualified, the declaration shall refer to a
6443 // previously declared member of the class or namespace to which the
6444 // qualifier refers (or, in the case of a namespace, of an element of the
6445 // inline namespace set of that namespace (7.3.1)) or to a specialization
6446 // thereof; [...]
6448 // Note that we already checked the context above, and that we do not have
6449 // enough information to make sure that Previous contains the declaration
6450 // we want to match. For example, given:
6452 // class X {
6453 // void f();
6454 // void f(float);
6455 // };
6457 // void X::f(int) { } // ill-formed
6459 // In this case, Previous will point to the overload set
6460 // containing the two f's declared in X, but neither of them
6461 // matches.
6463 RemoveUsingDecls(Previous);
6466 if (Previous.isSingleResult() &&
6467 Previous.getFoundDecl()->isTemplateParameter()) {
6468 // Maybe we will complain about the shadowed template parameter.
6469 if (!D.isInvalidType())
6470 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6471 Previous.getFoundDecl());
6473 // Just pretend that we didn't see the previous declaration.
6474 Previous.clear();
6477 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6478 // Forget that the previous declaration is the injected-class-name.
6479 Previous.clear();
6481 // In C++, the previous declaration we find might be a tag type
6482 // (class or enum). In this case, the new declaration will hide the
6483 // tag type. Note that this applies to functions, function templates, and
6484 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6485 if (Previous.isSingleTagDecl() &&
6486 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6487 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6488 Previous.clear();
6490 // Check that there are no default arguments other than in the parameters
6491 // of a function declaration (C++ only).
6492 if (getLangOpts().CPlusPlus)
6493 CheckExtraCXXDefaultArguments(D);
6495 NamedDecl *New;
6497 bool AddToScope = true;
6498 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6499 if (TemplateParamLists.size()) {
6500 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6501 return nullptr;
6504 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6505 } else if (R->isFunctionType()) {
6506 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6507 TemplateParamLists,
6508 AddToScope);
6509 } else {
6510 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6511 AddToScope);
6514 if (!New)
6515 return nullptr;
6517 // If this has an identifier and is not a function template specialization,
6518 // add it to the scope stack.
6519 if (New->getDeclName() && AddToScope)
6520 PushOnScopeChains(New, S);
6522 if (isInOpenMPDeclareTargetContext())
6523 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6525 return New;
6528 /// Helper method to turn variable array types into constant array
6529 /// types in certain situations which would otherwise be errors (for
6530 /// GCC compatibility).
6531 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6532 ASTContext &Context,
6533 bool &SizeIsNegative,
6534 llvm::APSInt &Oversized) {
6535 // This method tries to turn a variable array into a constant
6536 // array even when the size isn't an ICE. This is necessary
6537 // for compatibility with code that depends on gcc's buggy
6538 // constant expression folding, like struct {char x[(int)(char*)2];}
6539 SizeIsNegative = false;
6540 Oversized = 0;
6542 if (T->isDependentType())
6543 return QualType();
6545 QualifierCollector Qs;
6546 const Type *Ty = Qs.strip(T);
6548 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6549 QualType Pointee = PTy->getPointeeType();
6550 QualType FixedType =
6551 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6552 Oversized);
6553 if (FixedType.isNull()) return FixedType;
6554 FixedType = Context.getPointerType(FixedType);
6555 return Qs.apply(Context, FixedType);
6557 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6558 QualType Inner = PTy->getInnerType();
6559 QualType FixedType =
6560 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6561 Oversized);
6562 if (FixedType.isNull()) return FixedType;
6563 FixedType = Context.getParenType(FixedType);
6564 return Qs.apply(Context, FixedType);
6567 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6568 if (!VLATy)
6569 return QualType();
6571 QualType ElemTy = VLATy->getElementType();
6572 if (ElemTy->isVariablyModifiedType()) {
6573 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6574 SizeIsNegative, Oversized);
6575 if (ElemTy.isNull())
6576 return QualType();
6579 Expr::EvalResult Result;
6580 if (!VLATy->getSizeExpr() ||
6581 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6582 return QualType();
6584 llvm::APSInt Res = Result.Val.getInt();
6586 // Check whether the array size is negative.
6587 if (Res.isSigned() && Res.isNegative()) {
6588 SizeIsNegative = true;
6589 return QualType();
6592 // Check whether the array is too large to be addressed.
6593 unsigned ActiveSizeBits =
6594 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6595 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6596 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6597 : Res.getActiveBits();
6598 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6599 Oversized = Res;
6600 return QualType();
6603 QualType FoldedArrayType = Context.getConstantArrayType(
6604 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6605 return Qs.apply(Context, FoldedArrayType);
6608 static void
6609 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6610 SrcTL = SrcTL.getUnqualifiedLoc();
6611 DstTL = DstTL.getUnqualifiedLoc();
6612 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6613 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6614 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6615 DstPTL.getPointeeLoc());
6616 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6617 return;
6619 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6620 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6621 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6622 DstPTL.getInnerLoc());
6623 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6624 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6625 return;
6627 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6628 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6629 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6630 TypeLoc DstElemTL = DstATL.getElementLoc();
6631 if (VariableArrayTypeLoc SrcElemATL =
6632 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6633 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6634 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6635 } else {
6636 DstElemTL.initializeFullCopy(SrcElemTL);
6638 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6639 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6640 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6643 /// Helper method to turn variable array types into constant array
6644 /// types in certain situations which would otherwise be errors (for
6645 /// GCC compatibility).
6646 static TypeSourceInfo*
6647 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6648 ASTContext &Context,
6649 bool &SizeIsNegative,
6650 llvm::APSInt &Oversized) {
6651 QualType FixedTy
6652 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6653 SizeIsNegative, Oversized);
6654 if (FixedTy.isNull())
6655 return nullptr;
6656 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6657 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6658 FixedTInfo->getTypeLoc());
6659 return FixedTInfo;
6662 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6663 /// true if we were successful.
6664 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6665 QualType &T, SourceLocation Loc,
6666 unsigned FailedFoldDiagID) {
6667 bool SizeIsNegative;
6668 llvm::APSInt Oversized;
6669 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6670 TInfo, Context, SizeIsNegative, Oversized);
6671 if (FixedTInfo) {
6672 Diag(Loc, diag::ext_vla_folded_to_constant);
6673 TInfo = FixedTInfo;
6674 T = FixedTInfo->getType();
6675 return true;
6678 if (SizeIsNegative)
6679 Diag(Loc, diag::err_typecheck_negative_array_size);
6680 else if (Oversized.getBoolValue())
6681 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6682 else if (FailedFoldDiagID)
6683 Diag(Loc, FailedFoldDiagID);
6684 return false;
6687 /// Register the given locally-scoped extern "C" declaration so
6688 /// that it can be found later for redeclarations. We include any extern "C"
6689 /// declaration that is not visible in the translation unit here, not just
6690 /// function-scope declarations.
6691 void
6692 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6693 if (!getLangOpts().CPlusPlus &&
6694 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6695 // Don't need to track declarations in the TU in C.
6696 return;
6698 // Note that we have a locally-scoped external with this name.
6699 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6702 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6703 // FIXME: We can have multiple results via __attribute__((overloadable)).
6704 auto Result = Context.getExternCContextDecl()->lookup(Name);
6705 return Result.empty() ? nullptr : *Result.begin();
6708 /// Diagnose function specifiers on a declaration of an identifier that
6709 /// does not identify a function.
6710 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6711 // FIXME: We should probably indicate the identifier in question to avoid
6712 // confusion for constructs like "virtual int a(), b;"
6713 if (DS.isVirtualSpecified())
6714 Diag(DS.getVirtualSpecLoc(),
6715 diag::err_virtual_non_function);
6717 if (DS.hasExplicitSpecifier())
6718 Diag(DS.getExplicitSpecLoc(),
6719 diag::err_explicit_non_function);
6721 if (DS.isNoreturnSpecified())
6722 Diag(DS.getNoreturnSpecLoc(),
6723 diag::err_noreturn_non_function);
6726 NamedDecl*
6727 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6728 TypeSourceInfo *TInfo, LookupResult &Previous) {
6729 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6730 if (D.getCXXScopeSpec().isSet()) {
6731 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6732 << D.getCXXScopeSpec().getRange();
6733 D.setInvalidType();
6734 // Pretend we didn't see the scope specifier.
6735 DC = CurContext;
6736 Previous.clear();
6739 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6741 if (D.getDeclSpec().isInlineSpecified())
6742 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6743 << getLangOpts().CPlusPlus17;
6744 if (D.getDeclSpec().hasConstexprSpecifier())
6745 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6746 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6748 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6749 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6750 Diag(D.getName().StartLocation,
6751 diag::err_deduction_guide_invalid_specifier)
6752 << "typedef";
6753 else
6754 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6755 << D.getName().getSourceRange();
6756 return nullptr;
6759 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6760 if (!NewTD) return nullptr;
6762 // Handle attributes prior to checking for duplicates in MergeVarDecl
6763 ProcessDeclAttributes(S, NewTD, D);
6765 CheckTypedefForVariablyModifiedType(S, NewTD);
6767 bool Redeclaration = D.isRedeclaration();
6768 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6769 D.setRedeclaration(Redeclaration);
6770 return ND;
6773 void
6774 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6775 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6776 // then it shall have block scope.
6777 // Note that variably modified types must be fixed before merging the decl so
6778 // that redeclarations will match.
6779 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6780 QualType T = TInfo->getType();
6781 if (T->isVariablyModifiedType()) {
6782 setFunctionHasBranchProtectedScope();
6784 if (S->getFnParent() == nullptr) {
6785 bool SizeIsNegative;
6786 llvm::APSInt Oversized;
6787 TypeSourceInfo *FixedTInfo =
6788 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6789 SizeIsNegative,
6790 Oversized);
6791 if (FixedTInfo) {
6792 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6793 NewTD->setTypeSourceInfo(FixedTInfo);
6794 } else {
6795 if (SizeIsNegative)
6796 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6797 else if (T->isVariableArrayType())
6798 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6799 else if (Oversized.getBoolValue())
6800 Diag(NewTD->getLocation(), diag::err_array_too_large)
6801 << toString(Oversized, 10);
6802 else
6803 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6804 NewTD->setInvalidDecl();
6810 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6811 /// declares a typedef-name, either using the 'typedef' type specifier or via
6812 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6813 NamedDecl*
6814 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6815 LookupResult &Previous, bool &Redeclaration) {
6817 // Find the shadowed declaration before filtering for scope.
6818 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6820 // Merge the decl with the existing one if appropriate. If the decl is
6821 // in an outer scope, it isn't the same thing.
6822 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6823 /*AllowInlineNamespace*/false);
6824 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6825 if (!Previous.empty()) {
6826 Redeclaration = true;
6827 MergeTypedefNameDecl(S, NewTD, Previous);
6828 } else {
6829 inferGslPointerAttribute(NewTD);
6832 if (ShadowedDecl && !Redeclaration)
6833 CheckShadow(NewTD, ShadowedDecl, Previous);
6835 // If this is the C FILE type, notify the AST context.
6836 if (IdentifierInfo *II = NewTD->getIdentifier())
6837 if (!NewTD->isInvalidDecl() &&
6838 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6839 switch (II->getInterestingIdentifierID()) {
6840 case tok::InterestingIdentifierKind::FILE:
6841 Context.setFILEDecl(NewTD);
6842 break;
6843 case tok::InterestingIdentifierKind::jmp_buf:
6844 Context.setjmp_bufDecl(NewTD);
6845 break;
6846 case tok::InterestingIdentifierKind::sigjmp_buf:
6847 Context.setsigjmp_bufDecl(NewTD);
6848 break;
6849 case tok::InterestingIdentifierKind::ucontext_t:
6850 Context.setucontext_tDecl(NewTD);
6851 break;
6852 case tok::InterestingIdentifierKind::float_t:
6853 case tok::InterestingIdentifierKind::double_t:
6854 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6855 break;
6856 default:
6857 break;
6861 return NewTD;
6864 /// Determines whether the given declaration is an out-of-scope
6865 /// previous declaration.
6867 /// This routine should be invoked when name lookup has found a
6868 /// previous declaration (PrevDecl) that is not in the scope where a
6869 /// new declaration by the same name is being introduced. If the new
6870 /// declaration occurs in a local scope, previous declarations with
6871 /// linkage may still be considered previous declarations (C99
6872 /// 6.2.2p4-5, C++ [basic.link]p6).
6874 /// \param PrevDecl the previous declaration found by name
6875 /// lookup
6877 /// \param DC the context in which the new declaration is being
6878 /// declared.
6880 /// \returns true if PrevDecl is an out-of-scope previous declaration
6881 /// for a new delcaration with the same name.
6882 static bool
6883 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6884 ASTContext &Context) {
6885 if (!PrevDecl)
6886 return false;
6888 if (!PrevDecl->hasLinkage())
6889 return false;
6891 if (Context.getLangOpts().CPlusPlus) {
6892 // C++ [basic.link]p6:
6893 // If there is a visible declaration of an entity with linkage
6894 // having the same name and type, ignoring entities declared
6895 // outside the innermost enclosing namespace scope, the block
6896 // scope declaration declares that same entity and receives the
6897 // linkage of the previous declaration.
6898 DeclContext *OuterContext = DC->getRedeclContext();
6899 if (!OuterContext->isFunctionOrMethod())
6900 // This rule only applies to block-scope declarations.
6901 return false;
6903 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6904 if (PrevOuterContext->isRecord())
6905 // We found a member function: ignore it.
6906 return false;
6908 // Find the innermost enclosing namespace for the new and
6909 // previous declarations.
6910 OuterContext = OuterContext->getEnclosingNamespaceContext();
6911 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6913 // The previous declaration is in a different namespace, so it
6914 // isn't the same function.
6915 if (!OuterContext->Equals(PrevOuterContext))
6916 return false;
6919 return true;
6922 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6923 CXXScopeSpec &SS = D.getCXXScopeSpec();
6924 if (!SS.isSet()) return;
6925 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6928 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6929 QualType type = decl->getType();
6930 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6931 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6932 // Various kinds of declaration aren't allowed to be __autoreleasing.
6933 unsigned kind = -1U;
6934 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6935 if (var->hasAttr<BlocksAttr>())
6936 kind = 0; // __block
6937 else if (!var->hasLocalStorage())
6938 kind = 1; // global
6939 } else if (isa<ObjCIvarDecl>(decl)) {
6940 kind = 3; // ivar
6941 } else if (isa<FieldDecl>(decl)) {
6942 kind = 2; // field
6945 if (kind != -1U) {
6946 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6947 << kind;
6949 } else if (lifetime == Qualifiers::OCL_None) {
6950 // Try to infer lifetime.
6951 if (!type->isObjCLifetimeType())
6952 return false;
6954 lifetime = type->getObjCARCImplicitLifetime();
6955 type = Context.getLifetimeQualifiedType(type, lifetime);
6956 decl->setType(type);
6959 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6960 // Thread-local variables cannot have lifetime.
6961 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6962 var->getTLSKind()) {
6963 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6964 << var->getType();
6965 return true;
6969 return false;
6972 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6973 if (Decl->getType().hasAddressSpace())
6974 return;
6975 if (Decl->getType()->isDependentType())
6976 return;
6977 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6978 QualType Type = Var->getType();
6979 if (Type->isSamplerT() || Type->isVoidType())
6980 return;
6981 LangAS ImplAS = LangAS::opencl_private;
6982 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6983 // __opencl_c_program_scope_global_variables feature, the address space
6984 // for a variable at program scope or a static or extern variable inside
6985 // a function are inferred to be __global.
6986 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6987 Var->hasGlobalStorage())
6988 ImplAS = LangAS::opencl_global;
6989 // If the original type from a decayed type is an array type and that array
6990 // type has no address space yet, deduce it now.
6991 if (auto DT = dyn_cast<DecayedType>(Type)) {
6992 auto OrigTy = DT->getOriginalType();
6993 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6994 // Add the address space to the original array type and then propagate
6995 // that to the element type through `getAsArrayType`.
6996 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6997 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6998 // Re-generate the decayed type.
6999 Type = Context.getDecayedType(OrigTy);
7002 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7003 // Apply any qualifiers (including address space) from the array type to
7004 // the element type. This implements C99 6.7.3p8: "If the specification of
7005 // an array type includes any type qualifiers, the element type is so
7006 // qualified, not the array type."
7007 if (Type->isArrayType())
7008 Type = QualType(Context.getAsArrayType(Type), 0);
7009 Decl->setType(Type);
7013 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7014 // Ensure that an auto decl is deduced otherwise the checks below might cache
7015 // the wrong linkage.
7016 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7018 // 'weak' only applies to declarations with external linkage.
7019 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7020 if (!ND.isExternallyVisible()) {
7021 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7022 ND.dropAttr<WeakAttr>();
7025 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7026 if (ND.isExternallyVisible()) {
7027 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7028 ND.dropAttr<WeakRefAttr>();
7029 ND.dropAttr<AliasAttr>();
7033 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7034 if (VD->hasInit()) {
7035 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7036 assert(VD->isThisDeclarationADefinition() &&
7037 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7038 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7039 VD->dropAttr<AliasAttr>();
7044 // 'selectany' only applies to externally visible variable declarations.
7045 // It does not apply to functions.
7046 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7047 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7048 S.Diag(Attr->getLocation(),
7049 diag::err_attribute_selectany_non_extern_data);
7050 ND.dropAttr<SelectAnyAttr>();
7054 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7055 auto *VD = dyn_cast<VarDecl>(&ND);
7056 bool IsAnonymousNS = false;
7057 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7058 if (VD) {
7059 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7060 while (NS && !IsAnonymousNS) {
7061 IsAnonymousNS = NS->isAnonymousNamespace();
7062 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7065 // dll attributes require external linkage. Static locals may have external
7066 // linkage but still cannot be explicitly imported or exported.
7067 // In Microsoft mode, a variable defined in anonymous namespace must have
7068 // external linkage in order to be exported.
7069 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7070 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7071 (!AnonNSInMicrosoftMode &&
7072 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7073 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7074 << &ND << Attr;
7075 ND.setInvalidDecl();
7079 // Check the attributes on the function type, if any.
7080 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7081 // Don't declare this variable in the second operand of the for-statement;
7082 // GCC miscompiles that by ending its lifetime before evaluating the
7083 // third operand. See gcc.gnu.org/PR86769.
7084 AttributedTypeLoc ATL;
7085 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7086 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7087 TL = ATL.getModifiedLoc()) {
7088 // The [[lifetimebound]] attribute can be applied to the implicit object
7089 // parameter of a non-static member function (other than a ctor or dtor)
7090 // by applying it to the function type.
7091 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7092 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7093 if (!MD || MD->isStatic()) {
7094 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7095 << !MD << A->getRange();
7096 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7097 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7098 << isa<CXXDestructorDecl>(MD) << A->getRange();
7105 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7106 NamedDecl *NewDecl,
7107 bool IsSpecialization,
7108 bool IsDefinition) {
7109 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7110 return;
7112 bool IsTemplate = false;
7113 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7114 OldDecl = OldTD->getTemplatedDecl();
7115 IsTemplate = true;
7116 if (!IsSpecialization)
7117 IsDefinition = false;
7119 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7120 NewDecl = NewTD->getTemplatedDecl();
7121 IsTemplate = true;
7124 if (!OldDecl || !NewDecl)
7125 return;
7127 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7128 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7129 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7130 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7132 // dllimport and dllexport are inheritable attributes so we have to exclude
7133 // inherited attribute instances.
7134 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7135 (NewExportAttr && !NewExportAttr->isInherited());
7137 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7138 // the only exception being explicit specializations.
7139 // Implicitly generated declarations are also excluded for now because there
7140 // is no other way to switch these to use dllimport or dllexport.
7141 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7143 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7144 // Allow with a warning for free functions and global variables.
7145 bool JustWarn = false;
7146 if (!OldDecl->isCXXClassMember()) {
7147 auto *VD = dyn_cast<VarDecl>(OldDecl);
7148 if (VD && !VD->getDescribedVarTemplate())
7149 JustWarn = true;
7150 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7151 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7152 JustWarn = true;
7155 // We cannot change a declaration that's been used because IR has already
7156 // been emitted. Dllimported functions will still work though (modulo
7157 // address equality) as they can use the thunk.
7158 if (OldDecl->isUsed())
7159 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7160 JustWarn = false;
7162 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7163 : diag::err_attribute_dll_redeclaration;
7164 S.Diag(NewDecl->getLocation(), DiagID)
7165 << NewDecl
7166 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7167 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7168 if (!JustWarn) {
7169 NewDecl->setInvalidDecl();
7170 return;
7174 // A redeclaration is not allowed to drop a dllimport attribute, the only
7175 // exceptions being inline function definitions (except for function
7176 // templates), local extern declarations, qualified friend declarations or
7177 // special MSVC extension: in the last case, the declaration is treated as if
7178 // it were marked dllexport.
7179 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7180 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7181 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7182 // Ignore static data because out-of-line definitions are diagnosed
7183 // separately.
7184 IsStaticDataMember = VD->isStaticDataMember();
7185 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7186 VarDecl::DeclarationOnly;
7187 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7188 IsInline = FD->isInlined();
7189 IsQualifiedFriend = FD->getQualifier() &&
7190 FD->getFriendObjectKind() == Decl::FOK_Declared;
7193 if (OldImportAttr && !HasNewAttr &&
7194 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7195 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7196 if (IsMicrosoftABI && IsDefinition) {
7197 if (IsSpecialization) {
7198 S.Diag(
7199 NewDecl->getLocation(),
7200 diag::err_attribute_dllimport_function_specialization_definition);
7201 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7202 NewDecl->dropAttr<DLLImportAttr>();
7203 } else {
7204 S.Diag(NewDecl->getLocation(),
7205 diag::warn_redeclaration_without_import_attribute)
7206 << NewDecl;
7207 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7208 NewDecl->dropAttr<DLLImportAttr>();
7209 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7210 S.Context, NewImportAttr->getRange()));
7212 } else if (IsMicrosoftABI && IsSpecialization) {
7213 assert(!IsDefinition);
7214 // MSVC allows this. Keep the inherited attribute.
7215 } else {
7216 S.Diag(NewDecl->getLocation(),
7217 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7218 << NewDecl << OldImportAttr;
7219 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7220 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7221 OldDecl->dropAttr<DLLImportAttr>();
7222 NewDecl->dropAttr<DLLImportAttr>();
7224 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7225 // In MinGW, seeing a function declared inline drops the dllimport
7226 // attribute.
7227 OldDecl->dropAttr<DLLImportAttr>();
7228 NewDecl->dropAttr<DLLImportAttr>();
7229 S.Diag(NewDecl->getLocation(),
7230 diag::warn_dllimport_dropped_from_inline_function)
7231 << NewDecl << OldImportAttr;
7234 // A specialization of a class template member function is processed here
7235 // since it's a redeclaration. If the parent class is dllexport, the
7236 // specialization inherits that attribute. This doesn't happen automatically
7237 // since the parent class isn't instantiated until later.
7238 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7239 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7240 !NewImportAttr && !NewExportAttr) {
7241 if (const DLLExportAttr *ParentExportAttr =
7242 MD->getParent()->getAttr<DLLExportAttr>()) {
7243 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7244 NewAttr->setInherited(true);
7245 NewDecl->addAttr(NewAttr);
7251 /// Given that we are within the definition of the given function,
7252 /// will that definition behave like C99's 'inline', where the
7253 /// definition is discarded except for optimization purposes?
7254 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7255 // Try to avoid calling GetGVALinkageForFunction.
7257 // All cases of this require the 'inline' keyword.
7258 if (!FD->isInlined()) return false;
7260 // This is only possible in C++ with the gnu_inline attribute.
7261 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7262 return false;
7264 // Okay, go ahead and call the relatively-more-expensive function.
7265 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7268 /// Determine whether a variable is extern "C" prior to attaching
7269 /// an initializer. We can't just call isExternC() here, because that
7270 /// will also compute and cache whether the declaration is externally
7271 /// visible, which might change when we attach the initializer.
7273 /// This can only be used if the declaration is known to not be a
7274 /// redeclaration of an internal linkage declaration.
7276 /// For instance:
7278 /// auto x = []{};
7280 /// Attaching the initializer here makes this declaration not externally
7281 /// visible, because its type has internal linkage.
7283 /// FIXME: This is a hack.
7284 template<typename T>
7285 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7286 if (S.getLangOpts().CPlusPlus) {
7287 // In C++, the overloadable attribute negates the effects of extern "C".
7288 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7289 return false;
7291 // So do CUDA's host/device attributes.
7292 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7293 D->template hasAttr<CUDAHostAttr>()))
7294 return false;
7296 return D->isExternC();
7299 static bool shouldConsiderLinkage(const VarDecl *VD) {
7300 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7301 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7302 isa<OMPDeclareMapperDecl>(DC))
7303 return VD->hasExternalStorage();
7304 if (DC->isFileContext())
7305 return true;
7306 if (DC->isRecord())
7307 return false;
7308 if (DC->getDeclKind() == Decl::HLSLBuffer)
7309 return false;
7311 if (isa<RequiresExprBodyDecl>(DC))
7312 return false;
7313 llvm_unreachable("Unexpected context");
7316 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7317 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7318 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7319 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7320 return true;
7321 if (DC->isRecord())
7322 return false;
7323 llvm_unreachable("Unexpected context");
7326 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7327 ParsedAttr::Kind Kind) {
7328 // Check decl attributes on the DeclSpec.
7329 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7330 return true;
7332 // Walk the declarator structure, checking decl attributes that were in a type
7333 // position to the decl itself.
7334 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7335 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7336 return true;
7339 // Finally, check attributes on the decl itself.
7340 return PD.getAttributes().hasAttribute(Kind) ||
7341 PD.getDeclarationAttributes().hasAttribute(Kind);
7344 /// Adjust the \c DeclContext for a function or variable that might be a
7345 /// function-local external declaration.
7346 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7347 if (!DC->isFunctionOrMethod())
7348 return false;
7350 // If this is a local extern function or variable declared within a function
7351 // template, don't add it into the enclosing namespace scope until it is
7352 // instantiated; it might have a dependent type right now.
7353 if (DC->isDependentContext())
7354 return true;
7356 // C++11 [basic.link]p7:
7357 // When a block scope declaration of an entity with linkage is not found to
7358 // refer to some other declaration, then that entity is a member of the
7359 // innermost enclosing namespace.
7361 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7362 // semantically-enclosing namespace, not a lexically-enclosing one.
7363 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7364 DC = DC->getParent();
7365 return true;
7368 /// Returns true if given declaration has external C language linkage.
7369 static bool isDeclExternC(const Decl *D) {
7370 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7371 return FD->isExternC();
7372 if (const auto *VD = dyn_cast<VarDecl>(D))
7373 return VD->isExternC();
7375 llvm_unreachable("Unknown type of decl!");
7378 /// Returns true if there hasn't been any invalid type diagnosed.
7379 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7380 DeclContext *DC = NewVD->getDeclContext();
7381 QualType R = NewVD->getType();
7383 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7384 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7385 // argument.
7386 if (R->isImageType() || R->isPipeType()) {
7387 Se.Diag(NewVD->getLocation(),
7388 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7389 << R;
7390 NewVD->setInvalidDecl();
7391 return false;
7394 // OpenCL v1.2 s6.9.r:
7395 // The event type cannot be used to declare a program scope variable.
7396 // OpenCL v2.0 s6.9.q:
7397 // The clk_event_t and reserve_id_t types cannot be declared in program
7398 // scope.
7399 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7400 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7401 Se.Diag(NewVD->getLocation(),
7402 diag::err_invalid_type_for_program_scope_var)
7403 << R;
7404 NewVD->setInvalidDecl();
7405 return false;
7409 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7410 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7411 Se.getLangOpts())) {
7412 QualType NR = R.getCanonicalType();
7413 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7414 NR->isReferenceType()) {
7415 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7416 NR->isFunctionReferenceType()) {
7417 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7418 << NR->isReferenceType();
7419 NewVD->setInvalidDecl();
7420 return false;
7422 NR = NR->getPointeeType();
7426 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7427 Se.getLangOpts())) {
7428 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7429 // half array type (unless the cl_khr_fp16 extension is enabled).
7430 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7431 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7432 NewVD->setInvalidDecl();
7433 return false;
7437 // OpenCL v1.2 s6.9.r:
7438 // The event type cannot be used with the __local, __constant and __global
7439 // address space qualifiers.
7440 if (R->isEventT()) {
7441 if (R.getAddressSpace() != LangAS::opencl_private) {
7442 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7443 NewVD->setInvalidDecl();
7444 return false;
7448 if (R->isSamplerT()) {
7449 // OpenCL v1.2 s6.9.b p4:
7450 // The sampler type cannot be used with the __local and __global address
7451 // space qualifiers.
7452 if (R.getAddressSpace() == LangAS::opencl_local ||
7453 R.getAddressSpace() == LangAS::opencl_global) {
7454 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7455 NewVD->setInvalidDecl();
7458 // OpenCL v1.2 s6.12.14.1:
7459 // A global sampler must be declared with either the constant address
7460 // space qualifier or with the const qualifier.
7461 if (DC->isTranslationUnit() &&
7462 !(R.getAddressSpace() == LangAS::opencl_constant ||
7463 R.isConstQualified())) {
7464 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7465 NewVD->setInvalidDecl();
7467 if (NewVD->isInvalidDecl())
7468 return false;
7471 return true;
7474 template <typename AttrTy>
7475 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7476 const TypedefNameDecl *TND = TT->getDecl();
7477 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7478 AttrTy *Clone = Attribute->clone(S.Context);
7479 Clone->setInherited(true);
7480 D->addAttr(Clone);
7484 // This function emits warning and a corresponding note based on the
7485 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7486 // declarations of an annotated type must be const qualified.
7487 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7488 QualType VarType = VD->getType().getCanonicalType();
7490 // Ignore local declarations (for now) and those with const qualification.
7491 // TODO: Local variables should not be allowed if their type declaration has
7492 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7493 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7494 return;
7496 if (VarType->isArrayType()) {
7497 // Retrieve element type for array declarations.
7498 VarType = S.getASTContext().getBaseElementType(VarType);
7501 const RecordDecl *RD = VarType->getAsRecordDecl();
7503 // Check if the record declaration is present and if it has any attributes.
7504 if (RD == nullptr)
7505 return;
7507 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7508 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7509 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7510 return;
7514 NamedDecl *Sema::ActOnVariableDeclarator(
7515 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7516 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7517 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7518 QualType R = TInfo->getType();
7519 DeclarationName Name = GetNameForDeclarator(D).getName();
7521 IdentifierInfo *II = Name.getAsIdentifierInfo();
7522 bool IsPlaceholderVariable = false;
7524 if (D.isDecompositionDeclarator()) {
7525 // Take the name of the first declarator as our name for diagnostic
7526 // purposes.
7527 auto &Decomp = D.getDecompositionDeclarator();
7528 if (!Decomp.bindings().empty()) {
7529 II = Decomp.bindings()[0].Name;
7530 Name = II;
7532 } else if (!II) {
7533 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7534 return nullptr;
7538 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7539 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7541 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7542 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7543 IsPlaceholderVariable = true;
7544 if (!Previous.empty()) {
7545 NamedDecl *PrevDecl = *Previous.begin();
7546 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7547 DC->getRedeclContext());
7548 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7549 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7553 // dllimport globals without explicit storage class are treated as extern. We
7554 // have to change the storage class this early to get the right DeclContext.
7555 if (SC == SC_None && !DC->isRecord() &&
7556 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7557 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7558 SC = SC_Extern;
7560 DeclContext *OriginalDC = DC;
7561 bool IsLocalExternDecl = SC == SC_Extern &&
7562 adjustContextForLocalExternDecl(DC);
7564 if (SCSpec == DeclSpec::SCS_mutable) {
7565 // mutable can only appear on non-static class members, so it's always
7566 // an error here
7567 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7568 D.setInvalidType();
7569 SC = SC_None;
7572 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7573 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7574 D.getDeclSpec().getStorageClassSpecLoc())) {
7575 // In C++11, the 'register' storage class specifier is deprecated.
7576 // Suppress the warning in system macros, it's used in macros in some
7577 // popular C system headers, such as in glibc's htonl() macro.
7578 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7579 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7580 : diag::warn_deprecated_register)
7581 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7584 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7586 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7587 // C99 6.9p2: The storage-class specifiers auto and register shall not
7588 // appear in the declaration specifiers in an external declaration.
7589 // Global Register+Asm is a GNU extension we support.
7590 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7591 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7592 D.setInvalidType();
7596 // If this variable has a VLA type and an initializer, try to
7597 // fold to a constant-sized type. This is otherwise invalid.
7598 if (D.hasInitializer() && R->isVariableArrayType())
7599 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7600 /*DiagID=*/0);
7602 bool IsMemberSpecialization = false;
7603 bool IsVariableTemplateSpecialization = false;
7604 bool IsPartialSpecialization = false;
7605 bool IsVariableTemplate = false;
7606 VarDecl *NewVD = nullptr;
7607 VarTemplateDecl *NewTemplate = nullptr;
7608 TemplateParameterList *TemplateParams = nullptr;
7609 if (!getLangOpts().CPlusPlus) {
7610 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7611 II, R, TInfo, SC);
7613 if (R->getContainedDeducedType())
7614 ParsingInitForAutoVars.insert(NewVD);
7616 if (D.isInvalidType())
7617 NewVD->setInvalidDecl();
7619 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7620 NewVD->hasLocalStorage())
7621 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7622 NTCUC_AutoVar, NTCUK_Destruct);
7623 } else {
7624 bool Invalid = false;
7626 if (DC->isRecord() && !CurContext->isRecord()) {
7627 // This is an out-of-line definition of a static data member.
7628 switch (SC) {
7629 case SC_None:
7630 break;
7631 case SC_Static:
7632 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7633 diag::err_static_out_of_line)
7634 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7635 break;
7636 case SC_Auto:
7637 case SC_Register:
7638 case SC_Extern:
7639 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7640 // to names of variables declared in a block or to function parameters.
7641 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7642 // of class members
7644 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7645 diag::err_storage_class_for_static_member)
7646 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7647 break;
7648 case SC_PrivateExtern:
7649 llvm_unreachable("C storage class in c++!");
7653 if (SC == SC_Static && CurContext->isRecord()) {
7654 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7655 // Walk up the enclosing DeclContexts to check for any that are
7656 // incompatible with static data members.
7657 const DeclContext *FunctionOrMethod = nullptr;
7658 const CXXRecordDecl *AnonStruct = nullptr;
7659 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7660 if (Ctxt->isFunctionOrMethod()) {
7661 FunctionOrMethod = Ctxt;
7662 break;
7664 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7665 if (ParentDecl && !ParentDecl->getDeclName()) {
7666 AnonStruct = ParentDecl;
7667 break;
7670 if (FunctionOrMethod) {
7671 // C++ [class.static.data]p5: A local class shall not have static data
7672 // members.
7673 Diag(D.getIdentifierLoc(),
7674 diag::err_static_data_member_not_allowed_in_local_class)
7675 << Name << RD->getDeclName()
7676 << llvm::to_underlying(RD->getTagKind());
7677 } else if (AnonStruct) {
7678 // C++ [class.static.data]p4: Unnamed classes and classes contained
7679 // directly or indirectly within unnamed classes shall not contain
7680 // static data members.
7681 Diag(D.getIdentifierLoc(),
7682 diag::err_static_data_member_not_allowed_in_anon_struct)
7683 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7684 Invalid = true;
7685 } else if (RD->isUnion()) {
7686 // C++98 [class.union]p1: If a union contains a static data member,
7687 // the program is ill-formed. C++11 drops this restriction.
7688 Diag(D.getIdentifierLoc(),
7689 getLangOpts().CPlusPlus11
7690 ? diag::warn_cxx98_compat_static_data_member_in_union
7691 : diag::ext_static_data_member_in_union) << Name;
7696 // Match up the template parameter lists with the scope specifier, then
7697 // determine whether we have a template or a template specialization.
7698 bool InvalidScope = false;
7699 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7700 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7701 D.getCXXScopeSpec(),
7702 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7703 ? D.getName().TemplateId
7704 : nullptr,
7705 TemplateParamLists,
7706 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7707 Invalid |= InvalidScope;
7709 if (TemplateParams) {
7710 if (!TemplateParams->size() &&
7711 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7712 // There is an extraneous 'template<>' for this variable. Complain
7713 // about it, but allow the declaration of the variable.
7714 Diag(TemplateParams->getTemplateLoc(),
7715 diag::err_template_variable_noparams)
7716 << II
7717 << SourceRange(TemplateParams->getTemplateLoc(),
7718 TemplateParams->getRAngleLoc());
7719 TemplateParams = nullptr;
7720 } else {
7721 // Check that we can declare a template here.
7722 if (CheckTemplateDeclScope(S, TemplateParams))
7723 return nullptr;
7725 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7726 // This is an explicit specialization or a partial specialization.
7727 IsVariableTemplateSpecialization = true;
7728 IsPartialSpecialization = TemplateParams->size() > 0;
7729 } else { // if (TemplateParams->size() > 0)
7730 // This is a template declaration.
7731 IsVariableTemplate = true;
7733 // Only C++1y supports variable templates (N3651).
7734 Diag(D.getIdentifierLoc(),
7735 getLangOpts().CPlusPlus14
7736 ? diag::warn_cxx11_compat_variable_template
7737 : diag::ext_variable_template);
7740 } else {
7741 // Check that we can declare a member specialization here.
7742 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7743 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7744 return nullptr;
7745 assert((Invalid ||
7746 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7747 "should have a 'template<>' for this decl");
7750 if (IsVariableTemplateSpecialization) {
7751 SourceLocation TemplateKWLoc =
7752 TemplateParamLists.size() > 0
7753 ? TemplateParamLists[0]->getTemplateLoc()
7754 : SourceLocation();
7755 DeclResult Res = ActOnVarTemplateSpecialization(
7756 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7757 IsPartialSpecialization);
7758 if (Res.isInvalid())
7759 return nullptr;
7760 NewVD = cast<VarDecl>(Res.get());
7761 AddToScope = false;
7762 } else if (D.isDecompositionDeclarator()) {
7763 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7764 D.getIdentifierLoc(), R, TInfo, SC,
7765 Bindings);
7766 } else
7767 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7768 D.getIdentifierLoc(), II, R, TInfo, SC);
7770 // If this is supposed to be a variable template, create it as such.
7771 if (IsVariableTemplate) {
7772 NewTemplate =
7773 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7774 TemplateParams, NewVD);
7775 NewVD->setDescribedVarTemplate(NewTemplate);
7778 // If this decl has an auto type in need of deduction, make a note of the
7779 // Decl so we can diagnose uses of it in its own initializer.
7780 if (R->getContainedDeducedType())
7781 ParsingInitForAutoVars.insert(NewVD);
7783 if (D.isInvalidType() || Invalid) {
7784 NewVD->setInvalidDecl();
7785 if (NewTemplate)
7786 NewTemplate->setInvalidDecl();
7789 SetNestedNameSpecifier(*this, NewVD, D);
7791 // If we have any template parameter lists that don't directly belong to
7792 // the variable (matching the scope specifier), store them.
7793 // An explicit variable template specialization does not own any template
7794 // parameter lists.
7795 bool IsExplicitSpecialization =
7796 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7797 unsigned VDTemplateParamLists =
7798 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7799 if (TemplateParamLists.size() > VDTemplateParamLists)
7800 NewVD->setTemplateParameterListsInfo(
7801 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7804 if (D.getDeclSpec().isInlineSpecified()) {
7805 if (!getLangOpts().CPlusPlus) {
7806 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7807 << 0;
7808 } else if (CurContext->isFunctionOrMethod()) {
7809 // 'inline' is not allowed on block scope variable declaration.
7810 Diag(D.getDeclSpec().getInlineSpecLoc(),
7811 diag::err_inline_declaration_block_scope) << Name
7812 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7813 } else {
7814 Diag(D.getDeclSpec().getInlineSpecLoc(),
7815 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7816 : diag::ext_inline_variable);
7817 NewVD->setInlineSpecified();
7821 // Set the lexical context. If the declarator has a C++ scope specifier, the
7822 // lexical context will be different from the semantic context.
7823 NewVD->setLexicalDeclContext(CurContext);
7824 if (NewTemplate)
7825 NewTemplate->setLexicalDeclContext(CurContext);
7827 if (IsLocalExternDecl) {
7828 if (D.isDecompositionDeclarator())
7829 for (auto *B : Bindings)
7830 B->setLocalExternDecl();
7831 else
7832 NewVD->setLocalExternDecl();
7835 bool EmitTLSUnsupportedError = false;
7836 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7837 // C++11 [dcl.stc]p4:
7838 // When thread_local is applied to a variable of block scope the
7839 // storage-class-specifier static is implied if it does not appear
7840 // explicitly.
7841 // Core issue: 'static' is not implied if the variable is declared
7842 // 'extern'.
7843 if (NewVD->hasLocalStorage() &&
7844 (SCSpec != DeclSpec::SCS_unspecified ||
7845 TSCS != DeclSpec::TSCS_thread_local ||
7846 !DC->isFunctionOrMethod()))
7847 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7848 diag::err_thread_non_global)
7849 << DeclSpec::getSpecifierName(TSCS);
7850 else if (!Context.getTargetInfo().isTLSSupported()) {
7851 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7852 getLangOpts().SYCLIsDevice) {
7853 // Postpone error emission until we've collected attributes required to
7854 // figure out whether it's a host or device variable and whether the
7855 // error should be ignored.
7856 EmitTLSUnsupportedError = true;
7857 // We still need to mark the variable as TLS so it shows up in AST with
7858 // proper storage class for other tools to use even if we're not going
7859 // to emit any code for it.
7860 NewVD->setTSCSpec(TSCS);
7861 } else
7862 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7863 diag::err_thread_unsupported);
7864 } else
7865 NewVD->setTSCSpec(TSCS);
7868 switch (D.getDeclSpec().getConstexprSpecifier()) {
7869 case ConstexprSpecKind::Unspecified:
7870 break;
7872 case ConstexprSpecKind::Consteval:
7873 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7874 diag::err_constexpr_wrong_decl_kind)
7875 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7876 [[fallthrough]];
7878 case ConstexprSpecKind::Constexpr:
7879 NewVD->setConstexpr(true);
7880 // C++1z [dcl.spec.constexpr]p1:
7881 // A static data member declared with the constexpr specifier is
7882 // implicitly an inline variable.
7883 if (NewVD->isStaticDataMember() &&
7884 (getLangOpts().CPlusPlus17 ||
7885 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7886 NewVD->setImplicitlyInline();
7887 break;
7889 case ConstexprSpecKind::Constinit:
7890 if (!NewVD->hasGlobalStorage())
7891 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7892 diag::err_constinit_local_variable);
7893 else
7894 NewVD->addAttr(
7895 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7896 ConstInitAttr::Keyword_constinit));
7897 break;
7900 // C99 6.7.4p3
7901 // An inline definition of a function with external linkage shall
7902 // not contain a definition of a modifiable object with static or
7903 // thread storage duration...
7904 // We only apply this when the function is required to be defined
7905 // elsewhere, i.e. when the function is not 'extern inline'. Note
7906 // that a local variable with thread storage duration still has to
7907 // be marked 'static'. Also note that it's possible to get these
7908 // semantics in C++ using __attribute__((gnu_inline)).
7909 if (SC == SC_Static && S->getFnParent() != nullptr &&
7910 !NewVD->getType().isConstQualified()) {
7911 FunctionDecl *CurFD = getCurFunctionDecl();
7912 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7913 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7914 diag::warn_static_local_in_extern_inline);
7915 MaybeSuggestAddingStaticToDecl(CurFD);
7919 if (D.getDeclSpec().isModulePrivateSpecified()) {
7920 if (IsVariableTemplateSpecialization)
7921 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7922 << (IsPartialSpecialization ? 1 : 0)
7923 << FixItHint::CreateRemoval(
7924 D.getDeclSpec().getModulePrivateSpecLoc());
7925 else if (IsMemberSpecialization)
7926 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7927 << 2
7928 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7929 else if (NewVD->hasLocalStorage())
7930 Diag(NewVD->getLocation(), diag::err_module_private_local)
7931 << 0 << NewVD
7932 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7933 << FixItHint::CreateRemoval(
7934 D.getDeclSpec().getModulePrivateSpecLoc());
7935 else {
7936 NewVD->setModulePrivate();
7937 if (NewTemplate)
7938 NewTemplate->setModulePrivate();
7939 for (auto *B : Bindings)
7940 B->setModulePrivate();
7944 if (getLangOpts().OpenCL) {
7945 deduceOpenCLAddressSpace(NewVD);
7947 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7948 if (TSC != TSCS_unspecified) {
7949 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7950 diag::err_opencl_unknown_type_specifier)
7951 << getLangOpts().getOpenCLVersionString()
7952 << DeclSpec::getSpecifierName(TSC) << 1;
7953 NewVD->setInvalidDecl();
7957 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7958 // address space if the table has local storage (semantic checks elsewhere
7959 // will produce an error anyway).
7960 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7961 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7962 !NewVD->hasLocalStorage()) {
7963 QualType Type = Context.getAddrSpaceQualType(
7964 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7965 NewVD->setType(Type);
7969 // Handle attributes prior to checking for duplicates in MergeVarDecl
7970 ProcessDeclAttributes(S, NewVD, D);
7972 // FIXME: This is probably the wrong location to be doing this and we should
7973 // probably be doing this for more attributes (especially for function
7974 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7975 // the code to copy attributes would be generated by TableGen.
7976 if (R->isFunctionPointerType())
7977 if (const auto *TT = R->getAs<TypedefType>())
7978 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7980 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7981 getLangOpts().SYCLIsDevice) {
7982 if (EmitTLSUnsupportedError &&
7983 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7984 (getLangOpts().OpenMPIsTargetDevice &&
7985 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7986 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7987 diag::err_thread_unsupported);
7989 if (EmitTLSUnsupportedError &&
7990 (LangOpts.SYCLIsDevice ||
7991 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7992 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7993 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7994 // storage [duration]."
7995 if (SC == SC_None && S->getFnParent() != nullptr &&
7996 (NewVD->hasAttr<CUDASharedAttr>() ||
7997 NewVD->hasAttr<CUDAConstantAttr>())) {
7998 NewVD->setStorageClass(SC_Static);
8002 // Ensure that dllimport globals without explicit storage class are treated as
8003 // extern. The storage class is set above using parsed attributes. Now we can
8004 // check the VarDecl itself.
8005 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8006 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8007 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8009 // In auto-retain/release, infer strong retension for variables of
8010 // retainable type.
8011 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8012 NewVD->setInvalidDecl();
8014 // Handle GNU asm-label extension (encoded as an attribute).
8015 if (Expr *E = (Expr*)D.getAsmLabel()) {
8016 // The parser guarantees this is a string.
8017 StringLiteral *SE = cast<StringLiteral>(E);
8018 StringRef Label = SE->getString();
8019 if (S->getFnParent() != nullptr) {
8020 switch (SC) {
8021 case SC_None:
8022 case SC_Auto:
8023 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8024 break;
8025 case SC_Register:
8026 // Local Named register
8027 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8028 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8029 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8030 break;
8031 case SC_Static:
8032 case SC_Extern:
8033 case SC_PrivateExtern:
8034 break;
8036 } else if (SC == SC_Register) {
8037 // Global Named register
8038 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8039 const auto &TI = Context.getTargetInfo();
8040 bool HasSizeMismatch;
8042 if (!TI.isValidGCCRegisterName(Label))
8043 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8044 else if (!TI.validateGlobalRegisterVariable(Label,
8045 Context.getTypeSize(R),
8046 HasSizeMismatch))
8047 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8048 else if (HasSizeMismatch)
8049 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8052 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8053 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8054 NewVD->setInvalidDecl(true);
8058 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8059 /*IsLiteralLabel=*/true,
8060 SE->getStrTokenLoc(0)));
8061 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8062 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8063 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8064 if (I != ExtnameUndeclaredIdentifiers.end()) {
8065 if (isDeclExternC(NewVD)) {
8066 NewVD->addAttr(I->second);
8067 ExtnameUndeclaredIdentifiers.erase(I);
8068 } else
8069 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8070 << /*Variable*/1 << NewVD;
8074 // Find the shadowed declaration before filtering for scope.
8075 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8076 ? getShadowedDeclaration(NewVD, Previous)
8077 : nullptr;
8079 // Don't consider existing declarations that are in a different
8080 // scope and are out-of-semantic-context declarations (if the new
8081 // declaration has linkage).
8082 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8083 D.getCXXScopeSpec().isNotEmpty() ||
8084 IsMemberSpecialization ||
8085 IsVariableTemplateSpecialization);
8087 // Check whether the previous declaration is in the same block scope. This
8088 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8089 if (getLangOpts().CPlusPlus &&
8090 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8091 NewVD->setPreviousDeclInSameBlockScope(
8092 Previous.isSingleResult() && !Previous.isShadowed() &&
8093 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8095 if (!getLangOpts().CPlusPlus) {
8096 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8097 } else {
8098 // If this is an explicit specialization of a static data member, check it.
8099 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8100 CheckMemberSpecialization(NewVD, Previous))
8101 NewVD->setInvalidDecl();
8103 // Merge the decl with the existing one if appropriate.
8104 if (!Previous.empty()) {
8105 if (Previous.isSingleResult() &&
8106 isa<FieldDecl>(Previous.getFoundDecl()) &&
8107 D.getCXXScopeSpec().isSet()) {
8108 // The user tried to define a non-static data member
8109 // out-of-line (C++ [dcl.meaning]p1).
8110 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8111 << D.getCXXScopeSpec().getRange();
8112 Previous.clear();
8113 NewVD->setInvalidDecl();
8115 } else if (D.getCXXScopeSpec().isSet()) {
8116 // No previous declaration in the qualifying scope.
8117 Diag(D.getIdentifierLoc(), diag::err_no_member)
8118 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8119 << D.getCXXScopeSpec().getRange();
8120 NewVD->setInvalidDecl();
8123 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable)
8124 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8126 // CheckVariableDeclaration will set NewVD as invalid if something is in
8127 // error like WebAssembly tables being declared as arrays with a non-zero
8128 // size, but then parsing continues and emits further errors on that line.
8129 // To avoid that we check here if it happened and return nullptr.
8130 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8131 return nullptr;
8133 if (NewTemplate) {
8134 VarTemplateDecl *PrevVarTemplate =
8135 NewVD->getPreviousDecl()
8136 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8137 : nullptr;
8139 // Check the template parameter list of this declaration, possibly
8140 // merging in the template parameter list from the previous variable
8141 // template declaration.
8142 if (CheckTemplateParameterList(
8143 TemplateParams,
8144 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8145 : nullptr,
8146 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8147 DC->isDependentContext())
8148 ? TPC_ClassTemplateMember
8149 : TPC_VarTemplate))
8150 NewVD->setInvalidDecl();
8152 // If we are providing an explicit specialization of a static variable
8153 // template, make a note of that.
8154 if (PrevVarTemplate &&
8155 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8156 PrevVarTemplate->setMemberSpecialization();
8160 // Diagnose shadowed variables iff this isn't a redeclaration.
8161 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8162 CheckShadow(NewVD, ShadowedDecl, Previous);
8164 ProcessPragmaWeak(S, NewVD);
8166 // If this is the first declaration of an extern C variable, update
8167 // the map of such variables.
8168 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8169 isIncompleteDeclExternC(*this, NewVD))
8170 RegisterLocallyScopedExternCDecl(NewVD, S);
8172 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8173 MangleNumberingContext *MCtx;
8174 Decl *ManglingContextDecl;
8175 std::tie(MCtx, ManglingContextDecl) =
8176 getCurrentMangleNumberContext(NewVD->getDeclContext());
8177 if (MCtx) {
8178 Context.setManglingNumber(
8179 NewVD, MCtx->getManglingNumber(
8180 NewVD, getMSManglingNumber(getLangOpts(), S)));
8181 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8185 // Special handling of variable named 'main'.
8186 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8187 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8188 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8190 // C++ [basic.start.main]p3
8191 // A program that declares a variable main at global scope is ill-formed.
8192 if (getLangOpts().CPlusPlus)
8193 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8195 // In C, and external-linkage variable named main results in undefined
8196 // behavior.
8197 else if (NewVD->hasExternalFormalLinkage())
8198 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8201 if (D.isRedeclaration() && !Previous.empty()) {
8202 NamedDecl *Prev = Previous.getRepresentativeDecl();
8203 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8204 D.isFunctionDefinition());
8207 if (NewTemplate) {
8208 if (NewVD->isInvalidDecl())
8209 NewTemplate->setInvalidDecl();
8210 ActOnDocumentableDecl(NewTemplate);
8211 return NewTemplate;
8214 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8215 CompleteMemberSpecialization(NewVD, Previous);
8217 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8219 return NewVD;
8222 /// Enum describing the %select options in diag::warn_decl_shadow.
8223 enum ShadowedDeclKind {
8224 SDK_Local,
8225 SDK_Global,
8226 SDK_StaticMember,
8227 SDK_Field,
8228 SDK_Typedef,
8229 SDK_Using,
8230 SDK_StructuredBinding
8233 /// Determine what kind of declaration we're shadowing.
8234 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8235 const DeclContext *OldDC) {
8236 if (isa<TypeAliasDecl>(ShadowedDecl))
8237 return SDK_Using;
8238 else if (isa<TypedefDecl>(ShadowedDecl))
8239 return SDK_Typedef;
8240 else if (isa<BindingDecl>(ShadowedDecl))
8241 return SDK_StructuredBinding;
8242 else if (isa<RecordDecl>(OldDC))
8243 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8245 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8248 /// Return the location of the capture if the given lambda captures the given
8249 /// variable \p VD, or an invalid source location otherwise.
8250 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8251 const VarDecl *VD) {
8252 for (const Capture &Capture : LSI->Captures) {
8253 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8254 return Capture.getLocation();
8256 return SourceLocation();
8259 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8260 const LookupResult &R) {
8261 // Only diagnose if we're shadowing an unambiguous field or variable.
8262 if (R.getResultKind() != LookupResult::Found)
8263 return false;
8265 // Return false if warning is ignored.
8266 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8269 /// Return the declaration shadowed by the given variable \p D, or null
8270 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8271 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8272 const LookupResult &R) {
8273 if (!shouldWarnIfShadowedDecl(Diags, R))
8274 return nullptr;
8276 // Don't diagnose declarations at file scope.
8277 if (D->hasGlobalStorage() && !D->isStaticLocal())
8278 return nullptr;
8280 NamedDecl *ShadowedDecl = R.getFoundDecl();
8281 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8282 : nullptr;
8285 /// Return the declaration shadowed by the given typedef \p D, or null
8286 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8287 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8288 const LookupResult &R) {
8289 // Don't warn if typedef declaration is part of a class
8290 if (D->getDeclContext()->isRecord())
8291 return nullptr;
8293 if (!shouldWarnIfShadowedDecl(Diags, R))
8294 return nullptr;
8296 NamedDecl *ShadowedDecl = R.getFoundDecl();
8297 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8300 /// Return the declaration shadowed by the given variable \p D, or null
8301 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8302 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8303 const LookupResult &R) {
8304 if (!shouldWarnIfShadowedDecl(Diags, R))
8305 return nullptr;
8307 NamedDecl *ShadowedDecl = R.getFoundDecl();
8308 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8309 : nullptr;
8312 /// Diagnose variable or built-in function shadowing. Implements
8313 /// -Wshadow.
8315 /// This method is called whenever a VarDecl is added to a "useful"
8316 /// scope.
8318 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8319 /// \param R the lookup of the name
8321 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8322 const LookupResult &R) {
8323 DeclContext *NewDC = D->getDeclContext();
8325 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8326 // Fields are not shadowed by variables in C++ static methods.
8327 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8328 if (MD->isStatic())
8329 return;
8331 // Fields shadowed by constructor parameters are a special case. Usually
8332 // the constructor initializes the field with the parameter.
8333 if (isa<CXXConstructorDecl>(NewDC))
8334 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8335 // Remember that this was shadowed so we can either warn about its
8336 // modification or its existence depending on warning settings.
8337 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8338 return;
8342 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8343 if (shadowedVar->isExternC()) {
8344 // For shadowing external vars, make sure that we point to the global
8345 // declaration, not a locally scoped extern declaration.
8346 for (auto *I : shadowedVar->redecls())
8347 if (I->isFileVarDecl()) {
8348 ShadowedDecl = I;
8349 break;
8353 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8355 unsigned WarningDiag = diag::warn_decl_shadow;
8356 SourceLocation CaptureLoc;
8357 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8358 isa<CXXMethodDecl>(NewDC)) {
8359 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8360 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8361 if (RD->getLambdaCaptureDefault() == LCD_None) {
8362 // Try to avoid warnings for lambdas with an explicit capture list.
8363 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8364 // Warn only when the lambda captures the shadowed decl explicitly.
8365 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8366 if (CaptureLoc.isInvalid())
8367 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8368 } else {
8369 // Remember that this was shadowed so we can avoid the warning if the
8370 // shadowed decl isn't captured and the warning settings allow it.
8371 cast<LambdaScopeInfo>(getCurFunction())
8372 ->ShadowingDecls.push_back(
8373 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8374 return;
8378 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8379 // A variable can't shadow a local variable in an enclosing scope, if
8380 // they are separated by a non-capturing declaration context.
8381 for (DeclContext *ParentDC = NewDC;
8382 ParentDC && !ParentDC->Equals(OldDC);
8383 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8384 // Only block literals, captured statements, and lambda expressions
8385 // can capture; other scopes don't.
8386 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8387 !isLambdaCallOperator(ParentDC)) {
8388 return;
8395 // Never warn about shadowing a placeholder variable.
8396 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8397 return;
8399 // Only warn about certain kinds of shadowing for class members.
8400 if (NewDC && NewDC->isRecord()) {
8401 // In particular, don't warn about shadowing non-class members.
8402 if (!OldDC->isRecord())
8403 return;
8405 // TODO: should we warn about static data members shadowing
8406 // static data members from base classes?
8408 // TODO: don't diagnose for inaccessible shadowed members.
8409 // This is hard to do perfectly because we might friend the
8410 // shadowing context, but that's just a false negative.
8414 DeclarationName Name = R.getLookupName();
8416 // Emit warning and note.
8417 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8418 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8419 if (!CaptureLoc.isInvalid())
8420 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8421 << Name << /*explicitly*/ 1;
8422 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8425 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8426 /// when these variables are captured by the lambda.
8427 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8428 for (const auto &Shadow : LSI->ShadowingDecls) {
8429 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8430 // Try to avoid the warning when the shadowed decl isn't captured.
8431 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8432 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8433 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8434 ? diag::warn_decl_shadow_uncaptured_local
8435 : diag::warn_decl_shadow)
8436 << Shadow.VD->getDeclName()
8437 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8438 if (!CaptureLoc.isInvalid())
8439 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8440 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8441 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8445 /// Check -Wshadow without the advantage of a previous lookup.
8446 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8447 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8448 return;
8450 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8451 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8452 LookupName(R, S);
8453 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8454 CheckShadow(D, ShadowedDecl, R);
8457 /// Check if 'E', which is an expression that is about to be modified, refers
8458 /// to a constructor parameter that shadows a field.
8459 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8460 // Quickly ignore expressions that can't be shadowing ctor parameters.
8461 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8462 return;
8463 E = E->IgnoreParenImpCasts();
8464 auto *DRE = dyn_cast<DeclRefExpr>(E);
8465 if (!DRE)
8466 return;
8467 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8468 auto I = ShadowingDecls.find(D);
8469 if (I == ShadowingDecls.end())
8470 return;
8471 const NamedDecl *ShadowedDecl = I->second;
8472 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8473 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8474 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8475 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8477 // Avoid issuing multiple warnings about the same decl.
8478 ShadowingDecls.erase(I);
8481 /// Check for conflict between this global or extern "C" declaration and
8482 /// previous global or extern "C" declarations. This is only used in C++.
8483 template<typename T>
8484 static bool checkGlobalOrExternCConflict(
8485 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8486 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8487 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8489 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8490 // The common case: this global doesn't conflict with any extern "C"
8491 // declaration.
8492 return false;
8495 if (Prev) {
8496 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8497 // Both the old and new declarations have C language linkage. This is a
8498 // redeclaration.
8499 Previous.clear();
8500 Previous.addDecl(Prev);
8501 return true;
8504 // This is a global, non-extern "C" declaration, and there is a previous
8505 // non-global extern "C" declaration. Diagnose if this is a variable
8506 // declaration.
8507 if (!isa<VarDecl>(ND))
8508 return false;
8509 } else {
8510 // The declaration is extern "C". Check for any declaration in the
8511 // translation unit which might conflict.
8512 if (IsGlobal) {
8513 // We have already performed the lookup into the translation unit.
8514 IsGlobal = false;
8515 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8516 I != E; ++I) {
8517 if (isa<VarDecl>(*I)) {
8518 Prev = *I;
8519 break;
8522 } else {
8523 DeclContext::lookup_result R =
8524 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8525 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8526 I != E; ++I) {
8527 if (isa<VarDecl>(*I)) {
8528 Prev = *I;
8529 break;
8531 // FIXME: If we have any other entity with this name in global scope,
8532 // the declaration is ill-formed, but that is a defect: it breaks the
8533 // 'stat' hack, for instance. Only variables can have mangled name
8534 // clashes with extern "C" declarations, so only they deserve a
8535 // diagnostic.
8539 if (!Prev)
8540 return false;
8543 // Use the first declaration's location to ensure we point at something which
8544 // is lexically inside an extern "C" linkage-spec.
8545 assert(Prev && "should have found a previous declaration to diagnose");
8546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8547 Prev = FD->getFirstDecl();
8548 else
8549 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8551 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8552 << IsGlobal << ND;
8553 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8554 << IsGlobal;
8555 return false;
8558 /// Apply special rules for handling extern "C" declarations. Returns \c true
8559 /// if we have found that this is a redeclaration of some prior entity.
8561 /// Per C++ [dcl.link]p6:
8562 /// Two declarations [for a function or variable] with C language linkage
8563 /// with the same name that appear in different scopes refer to the same
8564 /// [entity]. An entity with C language linkage shall not be declared with
8565 /// the same name as an entity in global scope.
8566 template<typename T>
8567 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8568 LookupResult &Previous) {
8569 if (!S.getLangOpts().CPlusPlus) {
8570 // In C, when declaring a global variable, look for a corresponding 'extern'
8571 // variable declared in function scope. We don't need this in C++, because
8572 // we find local extern decls in the surrounding file-scope DeclContext.
8573 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8574 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8575 Previous.clear();
8576 Previous.addDecl(Prev);
8577 return true;
8580 return false;
8583 // A declaration in the translation unit can conflict with an extern "C"
8584 // declaration.
8585 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8586 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8588 // An extern "C" declaration can conflict with a declaration in the
8589 // translation unit or can be a redeclaration of an extern "C" declaration
8590 // in another scope.
8591 if (isIncompleteDeclExternC(S,ND))
8592 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8594 // Neither global nor extern "C": nothing to do.
8595 return false;
8598 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8599 // If the decl is already known invalid, don't check it.
8600 if (NewVD->isInvalidDecl())
8601 return;
8603 QualType T = NewVD->getType();
8605 // Defer checking an 'auto' type until its initializer is attached.
8606 if (T->isUndeducedType())
8607 return;
8609 if (NewVD->hasAttrs())
8610 CheckAlignasUnderalignment(NewVD);
8612 if (T->isObjCObjectType()) {
8613 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8614 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8615 T = Context.getObjCObjectPointerType(T);
8616 NewVD->setType(T);
8619 // Emit an error if an address space was applied to decl with local storage.
8620 // This includes arrays of objects with address space qualifiers, but not
8621 // automatic variables that point to other address spaces.
8622 // ISO/IEC TR 18037 S5.1.2
8623 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8624 T.getAddressSpace() != LangAS::Default) {
8625 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8626 NewVD->setInvalidDecl();
8627 return;
8630 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8631 // scope.
8632 if (getLangOpts().OpenCLVersion == 120 &&
8633 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8634 getLangOpts()) &&
8635 NewVD->isStaticLocal()) {
8636 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8637 NewVD->setInvalidDecl();
8638 return;
8641 if (getLangOpts().OpenCL) {
8642 if (!diagnoseOpenCLTypes(*this, NewVD))
8643 return;
8645 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8646 if (NewVD->hasAttr<BlocksAttr>()) {
8647 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8648 return;
8651 if (T->isBlockPointerType()) {
8652 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8653 // can't use 'extern' storage class.
8654 if (!T.isConstQualified()) {
8655 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8656 << 0 /*const*/;
8657 NewVD->setInvalidDecl();
8658 return;
8660 if (NewVD->hasExternalStorage()) {
8661 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8662 NewVD->setInvalidDecl();
8663 return;
8667 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8668 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8669 NewVD->hasExternalStorage()) {
8670 if (!T->isSamplerT() && !T->isDependentType() &&
8671 !(T.getAddressSpace() == LangAS::opencl_constant ||
8672 (T.getAddressSpace() == LangAS::opencl_global &&
8673 getOpenCLOptions().areProgramScopeVariablesSupported(
8674 getLangOpts())))) {
8675 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8676 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8677 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8678 << Scope << "global or constant";
8679 else
8680 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8681 << Scope << "constant";
8682 NewVD->setInvalidDecl();
8683 return;
8685 } else {
8686 if (T.getAddressSpace() == LangAS::opencl_global) {
8687 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8688 << 1 /*is any function*/ << "global";
8689 NewVD->setInvalidDecl();
8690 return;
8692 if (T.getAddressSpace() == LangAS::opencl_constant ||
8693 T.getAddressSpace() == LangAS::opencl_local) {
8694 FunctionDecl *FD = getCurFunctionDecl();
8695 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8696 // in functions.
8697 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8698 if (T.getAddressSpace() == LangAS::opencl_constant)
8699 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8700 << 0 /*non-kernel only*/ << "constant";
8701 else
8702 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8703 << 0 /*non-kernel only*/ << "local";
8704 NewVD->setInvalidDecl();
8705 return;
8707 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8708 // in the outermost scope of a kernel function.
8709 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8710 if (!getCurScope()->isFunctionScope()) {
8711 if (T.getAddressSpace() == LangAS::opencl_constant)
8712 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8713 << "constant";
8714 else
8715 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8716 << "local";
8717 NewVD->setInvalidDecl();
8718 return;
8721 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8722 // If we are parsing a template we didn't deduce an addr
8723 // space yet.
8724 T.getAddressSpace() != LangAS::Default) {
8725 // Do not allow other address spaces on automatic variable.
8726 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8727 NewVD->setInvalidDecl();
8728 return;
8733 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8734 && !NewVD->hasAttr<BlocksAttr>()) {
8735 if (getLangOpts().getGC() != LangOptions::NonGC)
8736 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8737 else {
8738 assert(!getLangOpts().ObjCAutoRefCount);
8739 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8743 // WebAssembly tables must be static with a zero length and can't be
8744 // declared within functions.
8745 if (T->isWebAssemblyTableType()) {
8746 if (getCurScope()->getParent()) { // Parent is null at top-level
8747 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8748 NewVD->setInvalidDecl();
8749 return;
8751 if (NewVD->getStorageClass() != SC_Static) {
8752 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8753 NewVD->setInvalidDecl();
8754 return;
8756 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8757 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8758 Diag(NewVD->getLocation(),
8759 diag::err_typecheck_wasm_table_must_have_zero_length);
8760 NewVD->setInvalidDecl();
8761 return;
8765 bool isVM = T->isVariablyModifiedType();
8766 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8767 NewVD->hasAttr<BlocksAttr>())
8768 setFunctionHasBranchProtectedScope();
8770 if ((isVM && NewVD->hasLinkage()) ||
8771 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8772 bool SizeIsNegative;
8773 llvm::APSInt Oversized;
8774 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8775 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8776 QualType FixedT;
8777 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8778 FixedT = FixedTInfo->getType();
8779 else if (FixedTInfo) {
8780 // Type and type-as-written are canonically different. We need to fix up
8781 // both types separately.
8782 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8783 Oversized);
8785 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8786 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8787 // FIXME: This won't give the correct result for
8788 // int a[10][n];
8789 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8791 if (NewVD->isFileVarDecl())
8792 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8793 << SizeRange;
8794 else if (NewVD->isStaticLocal())
8795 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8796 << SizeRange;
8797 else
8798 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8799 << SizeRange;
8800 NewVD->setInvalidDecl();
8801 return;
8804 if (!FixedTInfo) {
8805 if (NewVD->isFileVarDecl())
8806 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8807 else
8808 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8809 NewVD->setInvalidDecl();
8810 return;
8813 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8814 NewVD->setType(FixedT);
8815 NewVD->setTypeSourceInfo(FixedTInfo);
8818 if (T->isVoidType()) {
8819 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8820 // of objects and functions.
8821 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8822 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8823 << T;
8824 NewVD->setInvalidDecl();
8825 return;
8829 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8830 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8831 NewVD->setInvalidDecl();
8832 return;
8835 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8836 !T.isWebAssemblyReferenceType()) {
8837 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8838 NewVD->setInvalidDecl();
8839 return;
8842 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8843 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8844 NewVD->setInvalidDecl();
8845 return;
8848 if (NewVD->isConstexpr() && !T->isDependentType() &&
8849 RequireLiteralType(NewVD->getLocation(), T,
8850 diag::err_constexpr_var_non_literal)) {
8851 NewVD->setInvalidDecl();
8852 return;
8855 // PPC MMA non-pointer types are not allowed as non-local variable types.
8856 if (Context.getTargetInfo().getTriple().isPPC64() &&
8857 !NewVD->isLocalVarDecl() &&
8858 CheckPPCMMAType(T, NewVD->getLocation())) {
8859 NewVD->setInvalidDecl();
8860 return;
8863 // Check that SVE types are only used in functions with SVE available.
8864 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8865 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8866 llvm::StringMap<bool> CallerFeatureMap;
8867 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8868 if (!Builtin::evaluateRequiredTargetFeatures(
8869 "sve", CallerFeatureMap)) {
8870 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8871 NewVD->setInvalidDecl();
8872 return;
8876 if (T->isRVVType())
8877 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext));
8880 /// Perform semantic checking on a newly-created variable
8881 /// declaration.
8883 /// This routine performs all of the type-checking required for a
8884 /// variable declaration once it has been built. It is used both to
8885 /// check variables after they have been parsed and their declarators
8886 /// have been translated into a declaration, and to check variables
8887 /// that have been instantiated from a template.
8889 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8891 /// Returns true if the variable declaration is a redeclaration.
8892 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8893 CheckVariableDeclarationType(NewVD);
8895 // If the decl is already known invalid, don't check it.
8896 if (NewVD->isInvalidDecl())
8897 return false;
8899 // If we did not find anything by this name, look for a non-visible
8900 // extern "C" declaration with the same name.
8901 if (Previous.empty() &&
8902 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8903 Previous.setShadowed();
8905 if (!Previous.empty()) {
8906 MergeVarDecl(NewVD, Previous);
8907 return true;
8909 return false;
8912 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8913 /// and if so, check that it's a valid override and remember it.
8914 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8915 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8917 // Look for methods in base classes that this method might override.
8918 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8919 /*DetectVirtual=*/false);
8920 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8921 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8922 DeclarationName Name = MD->getDeclName();
8924 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8925 // We really want to find the base class destructor here.
8926 QualType T = Context.getTypeDeclType(BaseRecord);
8927 CanQualType CT = Context.getCanonicalType(T);
8928 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8931 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8932 CXXMethodDecl *BaseMD =
8933 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8934 if (!BaseMD || !BaseMD->isVirtual() ||
8935 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8936 /*ConsiderCudaAttrs=*/true))
8937 continue;
8938 if (!CheckExplicitObjectOverride(MD, BaseMD))
8939 continue;
8940 if (Overridden.insert(BaseMD).second) {
8941 MD->addOverriddenMethod(BaseMD);
8942 CheckOverridingFunctionReturnType(MD, BaseMD);
8943 CheckOverridingFunctionAttributes(MD, BaseMD);
8944 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8945 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8948 // A method can only override one function from each base class. We
8949 // don't track indirectly overridden methods from bases of bases.
8950 return true;
8953 return false;
8956 DC->lookupInBases(VisitBase, Paths);
8957 return !Overridden.empty();
8960 namespace {
8961 // Struct for holding all of the extra arguments needed by
8962 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8963 struct ActOnFDArgs {
8964 Scope *S;
8965 Declarator &D;
8966 MultiTemplateParamsArg TemplateParamLists;
8967 bool AddToScope;
8969 } // end anonymous namespace
8971 namespace {
8973 // Callback to only accept typo corrections that have a non-zero edit distance.
8974 // Also only accept corrections that have the same parent decl.
8975 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8976 public:
8977 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8978 CXXRecordDecl *Parent)
8979 : Context(Context), OriginalFD(TypoFD),
8980 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8982 bool ValidateCandidate(const TypoCorrection &candidate) override {
8983 if (candidate.getEditDistance() == 0)
8984 return false;
8986 SmallVector<unsigned, 1> MismatchedParams;
8987 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8988 CDeclEnd = candidate.end();
8989 CDecl != CDeclEnd; ++CDecl) {
8990 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8992 if (FD && !FD->hasBody() &&
8993 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8994 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8995 CXXRecordDecl *Parent = MD->getParent();
8996 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8997 return true;
8998 } else if (!ExpectedParent) {
8999 return true;
9004 return false;
9007 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9008 return std::make_unique<DifferentNameValidatorCCC>(*this);
9011 private:
9012 ASTContext &Context;
9013 FunctionDecl *OriginalFD;
9014 CXXRecordDecl *ExpectedParent;
9017 } // end anonymous namespace
9019 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9020 TypoCorrectedFunctionDefinitions.insert(F);
9023 /// Generate diagnostics for an invalid function redeclaration.
9025 /// This routine handles generating the diagnostic messages for an invalid
9026 /// function redeclaration, including finding possible similar declarations
9027 /// or performing typo correction if there are no previous declarations with
9028 /// the same name.
9030 /// Returns a NamedDecl iff typo correction was performed and substituting in
9031 /// the new declaration name does not cause new errors.
9032 static NamedDecl *DiagnoseInvalidRedeclaration(
9033 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9034 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9035 DeclarationName Name = NewFD->getDeclName();
9036 DeclContext *NewDC = NewFD->getDeclContext();
9037 SmallVector<unsigned, 1> MismatchedParams;
9038 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9039 TypoCorrection Correction;
9040 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9041 unsigned DiagMsg =
9042 IsLocalFriend ? diag::err_no_matching_local_friend :
9043 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9044 diag::err_member_decl_does_not_match;
9045 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9046 IsLocalFriend ? Sema::LookupLocalFriendName
9047 : Sema::LookupOrdinaryName,
9048 Sema::ForVisibleRedeclaration);
9050 NewFD->setInvalidDecl();
9051 if (IsLocalFriend)
9052 SemaRef.LookupName(Prev, S);
9053 else
9054 SemaRef.LookupQualifiedName(Prev, NewDC);
9055 assert(!Prev.isAmbiguous() &&
9056 "Cannot have an ambiguity in previous-declaration lookup");
9057 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9058 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9059 MD ? MD->getParent() : nullptr);
9060 if (!Prev.empty()) {
9061 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9062 Func != FuncEnd; ++Func) {
9063 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9064 if (FD &&
9065 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9066 // Add 1 to the index so that 0 can mean the mismatch didn't
9067 // involve a parameter
9068 unsigned ParamNum =
9069 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9070 NearMatches.push_back(std::make_pair(FD, ParamNum));
9073 // If the qualified name lookup yielded nothing, try typo correction
9074 } else if ((Correction = SemaRef.CorrectTypo(
9075 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9076 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9077 IsLocalFriend ? nullptr : NewDC))) {
9078 // Set up everything for the call to ActOnFunctionDeclarator
9079 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9080 ExtraArgs.D.getIdentifierLoc());
9081 Previous.clear();
9082 Previous.setLookupName(Correction.getCorrection());
9083 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9084 CDeclEnd = Correction.end();
9085 CDecl != CDeclEnd; ++CDecl) {
9086 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9087 if (FD && !FD->hasBody() &&
9088 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9089 Previous.addDecl(FD);
9092 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9094 NamedDecl *Result;
9095 // Retry building the function declaration with the new previous
9096 // declarations, and with errors suppressed.
9098 // Trap errors.
9099 Sema::SFINAETrap Trap(SemaRef);
9101 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9102 // pieces need to verify the typo-corrected C++ declaration and hopefully
9103 // eliminate the need for the parameter pack ExtraArgs.
9104 Result = SemaRef.ActOnFunctionDeclarator(
9105 ExtraArgs.S, ExtraArgs.D,
9106 Correction.getCorrectionDecl()->getDeclContext(),
9107 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9108 ExtraArgs.AddToScope);
9110 if (Trap.hasErrorOccurred())
9111 Result = nullptr;
9114 if (Result) {
9115 // Determine which correction we picked.
9116 Decl *Canonical = Result->getCanonicalDecl();
9117 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9118 I != E; ++I)
9119 if ((*I)->getCanonicalDecl() == Canonical)
9120 Correction.setCorrectionDecl(*I);
9122 // Let Sema know about the correction.
9123 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9124 SemaRef.diagnoseTypo(
9125 Correction,
9126 SemaRef.PDiag(IsLocalFriend
9127 ? diag::err_no_matching_local_friend_suggest
9128 : diag::err_member_decl_does_not_match_suggest)
9129 << Name << NewDC << IsDefinition);
9130 return Result;
9133 // Pretend the typo correction never occurred
9134 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9135 ExtraArgs.D.getIdentifierLoc());
9136 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9137 Previous.clear();
9138 Previous.setLookupName(Name);
9141 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9142 << Name << NewDC << IsDefinition << NewFD->getLocation();
9144 bool NewFDisConst = false;
9145 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9146 NewFDisConst = NewMD->isConst();
9148 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9149 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9150 NearMatch != NearMatchEnd; ++NearMatch) {
9151 FunctionDecl *FD = NearMatch->first;
9152 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9153 bool FDisConst = MD && MD->isConst();
9154 bool IsMember = MD || !IsLocalFriend;
9156 // FIXME: These notes are poorly worded for the local friend case.
9157 if (unsigned Idx = NearMatch->second) {
9158 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9159 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9160 if (Loc.isInvalid()) Loc = FD->getLocation();
9161 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9162 : diag::note_local_decl_close_param_match)
9163 << Idx << FDParam->getType()
9164 << NewFD->getParamDecl(Idx - 1)->getType();
9165 } else if (FDisConst != NewFDisConst) {
9166 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9167 << NewFDisConst << FD->getSourceRange().getEnd()
9168 << (NewFDisConst
9169 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9170 .getConstQualifierLoc())
9171 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9172 .getRParenLoc()
9173 .getLocWithOffset(1),
9174 " const"));
9175 } else
9176 SemaRef.Diag(FD->getLocation(),
9177 IsMember ? diag::note_member_def_close_match
9178 : diag::note_local_decl_close_match);
9180 return nullptr;
9183 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9184 switch (D.getDeclSpec().getStorageClassSpec()) {
9185 default: llvm_unreachable("Unknown storage class!");
9186 case DeclSpec::SCS_auto:
9187 case DeclSpec::SCS_register:
9188 case DeclSpec::SCS_mutable:
9189 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9190 diag::err_typecheck_sclass_func);
9191 D.getMutableDeclSpec().ClearStorageClassSpecs();
9192 D.setInvalidType();
9193 break;
9194 case DeclSpec::SCS_unspecified: break;
9195 case DeclSpec::SCS_extern:
9196 if (D.getDeclSpec().isExternInLinkageSpec())
9197 return SC_None;
9198 return SC_Extern;
9199 case DeclSpec::SCS_static: {
9200 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9201 // C99 6.7.1p5:
9202 // The declaration of an identifier for a function that has
9203 // block scope shall have no explicit storage-class specifier
9204 // other than extern
9205 // See also (C++ [dcl.stc]p4).
9206 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9207 diag::err_static_block_func);
9208 break;
9209 } else
9210 return SC_Static;
9212 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9215 // No explicit storage class has already been returned
9216 return SC_None;
9219 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9220 DeclContext *DC, QualType &R,
9221 TypeSourceInfo *TInfo,
9222 StorageClass SC,
9223 bool &IsVirtualOkay) {
9224 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9225 DeclarationName Name = NameInfo.getName();
9227 FunctionDecl *NewFD = nullptr;
9228 bool isInline = D.getDeclSpec().isInlineSpecified();
9230 if (!SemaRef.getLangOpts().CPlusPlus) {
9231 // Determine whether the function was written with a prototype. This is
9232 // true when:
9233 // - there is a prototype in the declarator, or
9234 // - the type R of the function is some kind of typedef or other non-
9235 // attributed reference to a type name (which eventually refers to a
9236 // function type). Note, we can't always look at the adjusted type to
9237 // check this case because attributes may cause a non-function
9238 // declarator to still have a function type. e.g.,
9239 // typedef void func(int a);
9240 // __attribute__((noreturn)) func other_func; // This has a prototype
9241 bool HasPrototype =
9242 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9243 (D.getDeclSpec().isTypeRep() &&
9244 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9245 ->isFunctionProtoType()) ||
9246 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9247 assert(
9248 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9249 "Strict prototypes are required");
9251 NewFD = FunctionDecl::Create(
9252 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9253 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9254 ConstexprSpecKind::Unspecified,
9255 /*TrailingRequiresClause=*/nullptr);
9256 if (D.isInvalidType())
9257 NewFD->setInvalidDecl();
9259 return NewFD;
9262 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9264 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9265 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9266 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9267 diag::err_constexpr_wrong_decl_kind)
9268 << static_cast<int>(ConstexprKind);
9269 ConstexprKind = ConstexprSpecKind::Unspecified;
9270 D.getMutableDeclSpec().ClearConstexprSpec();
9272 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9274 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9276 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9277 // This is a C++ constructor declaration.
9278 assert(DC->isRecord() &&
9279 "Constructors can only be declared in a member context");
9281 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9282 return CXXConstructorDecl::Create(
9283 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9284 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9285 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9286 InheritedConstructor(), TrailingRequiresClause);
9288 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9289 // This is a C++ destructor declaration.
9290 if (DC->isRecord()) {
9291 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9292 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9293 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9294 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9295 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9296 /*isImplicitlyDeclared=*/false, ConstexprKind,
9297 TrailingRequiresClause);
9298 // User defined destructors start as not selected if the class definition is still
9299 // not done.
9300 if (Record->isBeingDefined())
9301 NewDD->setIneligibleOrNotSelected(true);
9303 // If the destructor needs an implicit exception specification, set it
9304 // now. FIXME: It'd be nice to be able to create the right type to start
9305 // with, but the type needs to reference the destructor declaration.
9306 if (SemaRef.getLangOpts().CPlusPlus11)
9307 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9309 IsVirtualOkay = true;
9310 return NewDD;
9312 } else {
9313 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9314 D.setInvalidType();
9316 // Create a FunctionDecl to satisfy the function definition parsing
9317 // code path.
9318 return FunctionDecl::Create(
9319 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9320 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9321 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9324 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9325 if (!DC->isRecord()) {
9326 SemaRef.Diag(D.getIdentifierLoc(),
9327 diag::err_conv_function_not_member);
9328 return nullptr;
9331 SemaRef.CheckConversionDeclarator(D, R, SC);
9332 if (D.isInvalidType())
9333 return nullptr;
9335 IsVirtualOkay = true;
9336 return CXXConversionDecl::Create(
9337 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9338 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9339 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9340 TrailingRequiresClause);
9342 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9343 if (TrailingRequiresClause)
9344 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9345 diag::err_trailing_requires_clause_on_deduction_guide)
9346 << TrailingRequiresClause->getSourceRange();
9347 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9348 return nullptr;
9349 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9350 ExplicitSpecifier, NameInfo, R, TInfo,
9351 D.getEndLoc());
9352 } else if (DC->isRecord()) {
9353 // If the name of the function is the same as the name of the record,
9354 // then this must be an invalid constructor that has a return type.
9355 // (The parser checks for a return type and makes the declarator a
9356 // constructor if it has no return type).
9357 if (Name.getAsIdentifierInfo() &&
9358 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9359 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9360 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9361 << SourceRange(D.getIdentifierLoc());
9362 return nullptr;
9365 // This is a C++ method declaration.
9366 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9367 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9368 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9369 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9370 IsVirtualOkay = !Ret->isStatic();
9371 return Ret;
9372 } else {
9373 bool isFriend =
9374 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9375 if (!isFriend && SemaRef.CurContext->isRecord())
9376 return nullptr;
9378 // Determine whether the function was written with a
9379 // prototype. This true when:
9380 // - we're in C++ (where every function has a prototype),
9381 return FunctionDecl::Create(
9382 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9383 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9384 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9388 enum OpenCLParamType {
9389 ValidKernelParam,
9390 PtrPtrKernelParam,
9391 PtrKernelParam,
9392 InvalidAddrSpacePtrKernelParam,
9393 InvalidKernelParam,
9394 RecordKernelParam
9397 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9398 // Size dependent types are just typedefs to normal integer types
9399 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9400 // integers other than by their names.
9401 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9403 // Remove typedefs one by one until we reach a typedef
9404 // for a size dependent type.
9405 QualType DesugaredTy = Ty;
9406 do {
9407 ArrayRef<StringRef> Names(SizeTypeNames);
9408 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9409 if (Names.end() != Match)
9410 return true;
9412 Ty = DesugaredTy;
9413 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9414 } while (DesugaredTy != Ty);
9416 return false;
9419 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9420 if (PT->isDependentType())
9421 return InvalidKernelParam;
9423 if (PT->isPointerType() || PT->isReferenceType()) {
9424 QualType PointeeType = PT->getPointeeType();
9425 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9426 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9427 PointeeType.getAddressSpace() == LangAS::Default)
9428 return InvalidAddrSpacePtrKernelParam;
9430 if (PointeeType->isPointerType()) {
9431 // This is a pointer to pointer parameter.
9432 // Recursively check inner type.
9433 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9434 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9435 ParamKind == InvalidKernelParam)
9436 return ParamKind;
9438 // OpenCL v3.0 s6.11.a:
9439 // A restriction to pass pointers to pointers only applies to OpenCL C
9440 // v1.2 or below.
9441 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9442 return ValidKernelParam;
9444 return PtrPtrKernelParam;
9447 // C++ for OpenCL v1.0 s2.4:
9448 // Moreover the types used in parameters of the kernel functions must be:
9449 // Standard layout types for pointer parameters. The same applies to
9450 // reference if an implementation supports them in kernel parameters.
9451 if (S.getLangOpts().OpenCLCPlusPlus &&
9452 !S.getOpenCLOptions().isAvailableOption(
9453 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9454 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9455 bool IsStandardLayoutType = true;
9456 if (CXXRec) {
9457 // If template type is not ODR-used its definition is only available
9458 // in the template definition not its instantiation.
9459 // FIXME: This logic doesn't work for types that depend on template
9460 // parameter (PR58590).
9461 if (!CXXRec->hasDefinition())
9462 CXXRec = CXXRec->getTemplateInstantiationPattern();
9463 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9464 IsStandardLayoutType = false;
9466 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9467 !IsStandardLayoutType)
9468 return InvalidKernelParam;
9471 // OpenCL v1.2 s6.9.p:
9472 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9473 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9474 return ValidKernelParam;
9476 return PtrKernelParam;
9479 // OpenCL v1.2 s6.9.k:
9480 // Arguments to kernel functions in a program cannot be declared with the
9481 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9482 // uintptr_t or a struct and/or union that contain fields declared to be one
9483 // of these built-in scalar types.
9484 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9485 return InvalidKernelParam;
9487 if (PT->isImageType())
9488 return PtrKernelParam;
9490 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9491 return InvalidKernelParam;
9493 // OpenCL extension spec v1.2 s9.5:
9494 // This extension adds support for half scalar and vector types as built-in
9495 // types that can be used for arithmetic operations, conversions etc.
9496 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9497 PT->isHalfType())
9498 return InvalidKernelParam;
9500 // Look into an array argument to check if it has a forbidden type.
9501 if (PT->isArrayType()) {
9502 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9503 // Call ourself to check an underlying type of an array. Since the
9504 // getPointeeOrArrayElementType returns an innermost type which is not an
9505 // array, this recursive call only happens once.
9506 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9509 // C++ for OpenCL v1.0 s2.4:
9510 // Moreover the types used in parameters of the kernel functions must be:
9511 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9512 // types) for parameters passed by value;
9513 if (S.getLangOpts().OpenCLCPlusPlus &&
9514 !S.getOpenCLOptions().isAvailableOption(
9515 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9516 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9517 return InvalidKernelParam;
9519 if (PT->isRecordType())
9520 return RecordKernelParam;
9522 return ValidKernelParam;
9525 static void checkIsValidOpenCLKernelParameter(
9526 Sema &S,
9527 Declarator &D,
9528 ParmVarDecl *Param,
9529 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9530 QualType PT = Param->getType();
9532 // Cache the valid types we encounter to avoid rechecking structs that are
9533 // used again
9534 if (ValidTypes.count(PT.getTypePtr()))
9535 return;
9537 switch (getOpenCLKernelParameterType(S, PT)) {
9538 case PtrPtrKernelParam:
9539 // OpenCL v3.0 s6.11.a:
9540 // A kernel function argument cannot be declared as a pointer to a pointer
9541 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9542 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9543 D.setInvalidType();
9544 return;
9546 case InvalidAddrSpacePtrKernelParam:
9547 // OpenCL v1.0 s6.5:
9548 // __kernel function arguments declared to be a pointer of a type can point
9549 // to one of the following address spaces only : __global, __local or
9550 // __constant.
9551 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9552 D.setInvalidType();
9553 return;
9555 // OpenCL v1.2 s6.9.k:
9556 // Arguments to kernel functions in a program cannot be declared with the
9557 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9558 // uintptr_t or a struct and/or union that contain fields declared to be
9559 // one of these built-in scalar types.
9561 case InvalidKernelParam:
9562 // OpenCL v1.2 s6.8 n:
9563 // A kernel function argument cannot be declared
9564 // of event_t type.
9565 // Do not diagnose half type since it is diagnosed as invalid argument
9566 // type for any function elsewhere.
9567 if (!PT->isHalfType()) {
9568 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9570 // Explain what typedefs are involved.
9571 const TypedefType *Typedef = nullptr;
9572 while ((Typedef = PT->getAs<TypedefType>())) {
9573 SourceLocation Loc = Typedef->getDecl()->getLocation();
9574 // SourceLocation may be invalid for a built-in type.
9575 if (Loc.isValid())
9576 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9577 PT = Typedef->desugar();
9581 D.setInvalidType();
9582 return;
9584 case PtrKernelParam:
9585 case ValidKernelParam:
9586 ValidTypes.insert(PT.getTypePtr());
9587 return;
9589 case RecordKernelParam:
9590 break;
9593 // Track nested structs we will inspect
9594 SmallVector<const Decl *, 4> VisitStack;
9596 // Track where we are in the nested structs. Items will migrate from
9597 // VisitStack to HistoryStack as we do the DFS for bad field.
9598 SmallVector<const FieldDecl *, 4> HistoryStack;
9599 HistoryStack.push_back(nullptr);
9601 // At this point we already handled everything except of a RecordType or
9602 // an ArrayType of a RecordType.
9603 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9604 const RecordType *RecTy =
9605 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9606 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9608 VisitStack.push_back(RecTy->getDecl());
9609 assert(VisitStack.back() && "First decl null?");
9611 do {
9612 const Decl *Next = VisitStack.pop_back_val();
9613 if (!Next) {
9614 assert(!HistoryStack.empty());
9615 // Found a marker, we have gone up a level
9616 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9617 ValidTypes.insert(Hist->getType().getTypePtr());
9619 continue;
9622 // Adds everything except the original parameter declaration (which is not a
9623 // field itself) to the history stack.
9624 const RecordDecl *RD;
9625 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9626 HistoryStack.push_back(Field);
9628 QualType FieldTy = Field->getType();
9629 // Other field types (known to be valid or invalid) are handled while we
9630 // walk around RecordDecl::fields().
9631 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9632 "Unexpected type.");
9633 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9635 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9636 } else {
9637 RD = cast<RecordDecl>(Next);
9640 // Add a null marker so we know when we've gone back up a level
9641 VisitStack.push_back(nullptr);
9643 for (const auto *FD : RD->fields()) {
9644 QualType QT = FD->getType();
9646 if (ValidTypes.count(QT.getTypePtr()))
9647 continue;
9649 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9650 if (ParamType == ValidKernelParam)
9651 continue;
9653 if (ParamType == RecordKernelParam) {
9654 VisitStack.push_back(FD);
9655 continue;
9658 // OpenCL v1.2 s6.9.p:
9659 // Arguments to kernel functions that are declared to be a struct or union
9660 // do not allow OpenCL objects to be passed as elements of the struct or
9661 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9662 // of SVM.
9663 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9664 ParamType == InvalidAddrSpacePtrKernelParam) {
9665 S.Diag(Param->getLocation(),
9666 diag::err_record_with_pointers_kernel_param)
9667 << PT->isUnionType()
9668 << PT;
9669 } else {
9670 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9673 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9674 << OrigRecDecl->getDeclName();
9676 // We have an error, now let's go back up through history and show where
9677 // the offending field came from
9678 for (ArrayRef<const FieldDecl *>::const_iterator
9679 I = HistoryStack.begin() + 1,
9680 E = HistoryStack.end();
9681 I != E; ++I) {
9682 const FieldDecl *OuterField = *I;
9683 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9684 << OuterField->getType();
9687 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9688 << QT->isPointerType()
9689 << QT;
9690 D.setInvalidType();
9691 return;
9693 } while (!VisitStack.empty());
9696 /// Find the DeclContext in which a tag is implicitly declared if we see an
9697 /// elaborated type specifier in the specified context, and lookup finds
9698 /// nothing.
9699 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9700 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9701 DC = DC->getParent();
9702 return DC;
9705 /// Find the Scope in which a tag is implicitly declared if we see an
9706 /// elaborated type specifier in the specified context, and lookup finds
9707 /// nothing.
9708 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9709 while (S->isClassScope() ||
9710 (LangOpts.CPlusPlus &&
9711 S->isFunctionPrototypeScope()) ||
9712 ((S->getFlags() & Scope::DeclScope) == 0) ||
9713 (S->getEntity() && S->getEntity()->isTransparentContext()))
9714 S = S->getParent();
9715 return S;
9718 /// Determine whether a declaration matches a known function in namespace std.
9719 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9720 unsigned BuiltinID) {
9721 switch (BuiltinID) {
9722 case Builtin::BI__GetExceptionInfo:
9723 // No type checking whatsoever.
9724 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9726 case Builtin::BIaddressof:
9727 case Builtin::BI__addressof:
9728 case Builtin::BIforward:
9729 case Builtin::BIforward_like:
9730 case Builtin::BImove:
9731 case Builtin::BImove_if_noexcept:
9732 case Builtin::BIas_const: {
9733 // Ensure that we don't treat the algorithm
9734 // OutputIt std::move(InputIt, InputIt, OutputIt)
9735 // as the builtin std::move.
9736 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9737 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9740 default:
9741 return false;
9745 NamedDecl*
9746 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9747 TypeSourceInfo *TInfo, LookupResult &Previous,
9748 MultiTemplateParamsArg TemplateParamListsRef,
9749 bool &AddToScope) {
9750 QualType R = TInfo->getType();
9752 assert(R->isFunctionType());
9753 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9754 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9756 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9757 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9758 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9759 if (!TemplateParamLists.empty() &&
9760 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9761 TemplateParamLists.back() = Invented;
9762 else
9763 TemplateParamLists.push_back(Invented);
9766 // TODO: consider using NameInfo for diagnostic.
9767 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9768 DeclarationName Name = NameInfo.getName();
9769 StorageClass SC = getFunctionStorageClass(*this, D);
9771 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9772 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9773 diag::err_invalid_thread)
9774 << DeclSpec::getSpecifierName(TSCS);
9776 if (D.isFirstDeclarationOfMember())
9777 adjustMemberFunctionCC(
9778 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9779 D.isCtorOrDtor(), D.getIdentifierLoc());
9781 bool isFriend = false;
9782 FunctionTemplateDecl *FunctionTemplate = nullptr;
9783 bool isMemberSpecialization = false;
9784 bool isFunctionTemplateSpecialization = false;
9786 bool HasExplicitTemplateArgs = false;
9787 TemplateArgumentListInfo TemplateArgs;
9789 bool isVirtualOkay = false;
9791 DeclContext *OriginalDC = DC;
9792 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9794 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9795 isVirtualOkay);
9796 if (!NewFD) return nullptr;
9798 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9799 NewFD->setTopLevelDeclInObjCContainer();
9801 // Set the lexical context. If this is a function-scope declaration, or has a
9802 // C++ scope specifier, or is the object of a friend declaration, the lexical
9803 // context will be different from the semantic context.
9804 NewFD->setLexicalDeclContext(CurContext);
9806 if (IsLocalExternDecl)
9807 NewFD->setLocalExternDecl();
9809 if (getLangOpts().CPlusPlus) {
9810 // The rules for implicit inlines changed in C++20 for methods and friends
9811 // with an in-class definition (when such a definition is not attached to
9812 // the global module). User-specified 'inline' overrides this (set when
9813 // the function decl is created above).
9814 // FIXME: We need a better way to separate C++ standard and clang modules.
9815 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9816 !NewFD->getOwningModule() ||
9817 NewFD->getOwningModule()->isGlobalModule() ||
9818 NewFD->getOwningModule()->isHeaderLikeModule();
9819 bool isInline = D.getDeclSpec().isInlineSpecified();
9820 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9821 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9822 isFriend = D.getDeclSpec().isFriendSpecified();
9823 if (isFriend && !isInline && D.isFunctionDefinition()) {
9824 // Pre-C++20 [class.friend]p5
9825 // A function can be defined in a friend declaration of a
9826 // class . . . . Such a function is implicitly inline.
9827 // Post C++20 [class.friend]p7
9828 // Such a function is implicitly an inline function if it is attached
9829 // to the global module.
9830 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9833 // If this is a method defined in an __interface, and is not a constructor
9834 // or an overloaded operator, then set the pure flag (isVirtual will already
9835 // return true).
9836 if (const CXXRecordDecl *Parent =
9837 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9838 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9839 NewFD->setPure(true);
9841 // C++ [class.union]p2
9842 // A union can have member functions, but not virtual functions.
9843 if (isVirtual && Parent->isUnion()) {
9844 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9845 NewFD->setInvalidDecl();
9847 if ((Parent->isClass() || Parent->isStruct()) &&
9848 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9849 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9850 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9851 if (auto *Def = Parent->getDefinition())
9852 Def->setInitMethod(true);
9856 SetNestedNameSpecifier(*this, NewFD, D);
9857 isMemberSpecialization = false;
9858 isFunctionTemplateSpecialization = false;
9859 if (D.isInvalidType())
9860 NewFD->setInvalidDecl();
9862 // Match up the template parameter lists with the scope specifier, then
9863 // determine whether we have a template or a template specialization.
9864 bool Invalid = false;
9865 TemplateParameterList *TemplateParams =
9866 MatchTemplateParametersToScopeSpecifier(
9867 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9868 D.getCXXScopeSpec(),
9869 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9870 ? D.getName().TemplateId
9871 : nullptr,
9872 TemplateParamLists, isFriend, isMemberSpecialization,
9873 Invalid);
9874 if (TemplateParams) {
9875 // Check that we can declare a template here.
9876 if (CheckTemplateDeclScope(S, TemplateParams))
9877 NewFD->setInvalidDecl();
9879 if (TemplateParams->size() > 0) {
9880 // This is a function template
9882 // A destructor cannot be a template.
9883 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9884 Diag(NewFD->getLocation(), diag::err_destructor_template);
9885 NewFD->setInvalidDecl();
9888 // If we're adding a template to a dependent context, we may need to
9889 // rebuilding some of the types used within the template parameter list,
9890 // now that we know what the current instantiation is.
9891 if (DC->isDependentContext()) {
9892 ContextRAII SavedContext(*this, DC);
9893 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9894 Invalid = true;
9897 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9898 NewFD->getLocation(),
9899 Name, TemplateParams,
9900 NewFD);
9901 FunctionTemplate->setLexicalDeclContext(CurContext);
9902 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9904 // For source fidelity, store the other template param lists.
9905 if (TemplateParamLists.size() > 1) {
9906 NewFD->setTemplateParameterListsInfo(Context,
9907 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9908 .drop_back(1));
9910 } else {
9911 // This is a function template specialization.
9912 isFunctionTemplateSpecialization = true;
9913 // For source fidelity, store all the template param lists.
9914 if (TemplateParamLists.size() > 0)
9915 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9917 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9918 if (isFriend) {
9919 // We want to remove the "template<>", found here.
9920 SourceRange RemoveRange = TemplateParams->getSourceRange();
9922 // If we remove the template<> and the name is not a
9923 // template-id, we're actually silently creating a problem:
9924 // the friend declaration will refer to an untemplated decl,
9925 // and clearly the user wants a template specialization. So
9926 // we need to insert '<>' after the name.
9927 SourceLocation InsertLoc;
9928 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9929 InsertLoc = D.getName().getSourceRange().getEnd();
9930 InsertLoc = getLocForEndOfToken(InsertLoc);
9933 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9934 << Name << RemoveRange
9935 << FixItHint::CreateRemoval(RemoveRange)
9936 << FixItHint::CreateInsertion(InsertLoc, "<>");
9937 Invalid = true;
9940 } else {
9941 // Check that we can declare a template here.
9942 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9943 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9944 NewFD->setInvalidDecl();
9946 // All template param lists were matched against the scope specifier:
9947 // this is NOT (an explicit specialization of) a template.
9948 if (TemplateParamLists.size() > 0)
9949 // For source fidelity, store all the template param lists.
9950 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9953 if (Invalid) {
9954 NewFD->setInvalidDecl();
9955 if (FunctionTemplate)
9956 FunctionTemplate->setInvalidDecl();
9959 // C++ [dcl.fct.spec]p5:
9960 // The virtual specifier shall only be used in declarations of
9961 // nonstatic class member functions that appear within a
9962 // member-specification of a class declaration; see 10.3.
9964 if (isVirtual && !NewFD->isInvalidDecl()) {
9965 if (!isVirtualOkay) {
9966 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9967 diag::err_virtual_non_function);
9968 } else if (!CurContext->isRecord()) {
9969 // 'virtual' was specified outside of the class.
9970 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9971 diag::err_virtual_out_of_class)
9972 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9973 } else if (NewFD->getDescribedFunctionTemplate()) {
9974 // C++ [temp.mem]p3:
9975 // A member function template shall not be virtual.
9976 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9977 diag::err_virtual_member_function_template)
9978 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9979 } else {
9980 // Okay: Add virtual to the method.
9981 NewFD->setVirtualAsWritten(true);
9984 if (getLangOpts().CPlusPlus14 &&
9985 NewFD->getReturnType()->isUndeducedType())
9986 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9989 if (getLangOpts().CPlusPlus14 &&
9990 (NewFD->isDependentContext() ||
9991 (isFriend && CurContext->isDependentContext())) &&
9992 NewFD->getReturnType()->isUndeducedType()) {
9993 // If the function template is referenced directly (for instance, as a
9994 // member of the current instantiation), pretend it has a dependent type.
9995 // This is not really justified by the standard, but is the only sane
9996 // thing to do.
9997 // FIXME: For a friend function, we have not marked the function as being
9998 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9999 const FunctionProtoType *FPT =
10000 NewFD->getType()->castAs<FunctionProtoType>();
10001 QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
10002 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
10003 FPT->getExtProtoInfo()));
10006 // C++ [dcl.fct.spec]p3:
10007 // The inline specifier shall not appear on a block scope function
10008 // declaration.
10009 if (isInline && !NewFD->isInvalidDecl()) {
10010 if (CurContext->isFunctionOrMethod()) {
10011 // 'inline' is not allowed on block scope function declaration.
10012 Diag(D.getDeclSpec().getInlineSpecLoc(),
10013 diag::err_inline_declaration_block_scope) << Name
10014 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10018 // C++ [dcl.fct.spec]p6:
10019 // The explicit specifier shall be used only in the declaration of a
10020 // constructor or conversion function within its class definition;
10021 // see 12.3.1 and 12.3.2.
10022 if (hasExplicit && !NewFD->isInvalidDecl() &&
10023 !isa<CXXDeductionGuideDecl>(NewFD)) {
10024 if (!CurContext->isRecord()) {
10025 // 'explicit' was specified outside of the class.
10026 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10027 diag::err_explicit_out_of_class)
10028 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10029 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10030 !isa<CXXConversionDecl>(NewFD)) {
10031 // 'explicit' was specified on a function that wasn't a constructor
10032 // or conversion function.
10033 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10034 diag::err_explicit_non_ctor_or_conv_function)
10035 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10039 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10040 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10041 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10042 // are implicitly inline.
10043 NewFD->setImplicitlyInline();
10045 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10046 // be either constructors or to return a literal type. Therefore,
10047 // destructors cannot be declared constexpr.
10048 if (isa<CXXDestructorDecl>(NewFD) &&
10049 (!getLangOpts().CPlusPlus20 ||
10050 ConstexprKind == ConstexprSpecKind::Consteval)) {
10051 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10052 << static_cast<int>(ConstexprKind);
10053 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10054 ? ConstexprSpecKind::Unspecified
10055 : ConstexprSpecKind::Constexpr);
10057 // C++20 [dcl.constexpr]p2: An allocation function, or a
10058 // deallocation function shall not be declared with the consteval
10059 // specifier.
10060 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10061 (NewFD->getOverloadedOperator() == OO_New ||
10062 NewFD->getOverloadedOperator() == OO_Array_New ||
10063 NewFD->getOverloadedOperator() == OO_Delete ||
10064 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10065 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10066 diag::err_invalid_consteval_decl_kind)
10067 << NewFD;
10068 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10072 // If __module_private__ was specified, mark the function accordingly.
10073 if (D.getDeclSpec().isModulePrivateSpecified()) {
10074 if (isFunctionTemplateSpecialization) {
10075 SourceLocation ModulePrivateLoc
10076 = D.getDeclSpec().getModulePrivateSpecLoc();
10077 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10078 << 0
10079 << FixItHint::CreateRemoval(ModulePrivateLoc);
10080 } else {
10081 NewFD->setModulePrivate();
10082 if (FunctionTemplate)
10083 FunctionTemplate->setModulePrivate();
10087 if (isFriend) {
10088 if (FunctionTemplate) {
10089 FunctionTemplate->setObjectOfFriendDecl();
10090 FunctionTemplate->setAccess(AS_public);
10092 NewFD->setObjectOfFriendDecl();
10093 NewFD->setAccess(AS_public);
10096 // If a function is defined as defaulted or deleted, mark it as such now.
10097 // We'll do the relevant checks on defaulted / deleted functions later.
10098 switch (D.getFunctionDefinitionKind()) {
10099 case FunctionDefinitionKind::Declaration:
10100 case FunctionDefinitionKind::Definition:
10101 break;
10103 case FunctionDefinitionKind::Defaulted:
10104 NewFD->setDefaulted();
10105 break;
10107 case FunctionDefinitionKind::Deleted:
10108 NewFD->setDeletedAsWritten();
10109 break;
10112 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10113 D.isFunctionDefinition() && !isInline) {
10114 // Pre C++20 [class.mfct]p2:
10115 // A member function may be defined (8.4) in its class definition, in
10116 // which case it is an inline member function (7.1.2)
10117 // Post C++20 [class.mfct]p1:
10118 // If a member function is attached to the global module and is defined
10119 // in its class definition, it is inline.
10120 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10123 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10124 !CurContext->isRecord()) {
10125 // C++ [class.static]p1:
10126 // A data or function member of a class may be declared static
10127 // in a class definition, in which case it is a static member of
10128 // the class.
10130 // Complain about the 'static' specifier if it's on an out-of-line
10131 // member function definition.
10133 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10134 // member function template declaration and class member template
10135 // declaration (MSVC versions before 2015), warn about this.
10136 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10137 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10138 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10139 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10140 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10141 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10144 // C++11 [except.spec]p15:
10145 // A deallocation function with no exception-specification is treated
10146 // as if it were specified with noexcept(true).
10147 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10148 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10149 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10150 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10151 NewFD->setType(Context.getFunctionType(
10152 FPT->getReturnType(), FPT->getParamTypes(),
10153 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10155 // C++20 [dcl.inline]/7
10156 // If an inline function or variable that is attached to a named module
10157 // is declared in a definition domain, it shall be defined in that
10158 // domain.
10159 // So, if the current declaration does not have a definition, we must
10160 // check at the end of the TU (or when the PMF starts) to see that we
10161 // have a definition at that point.
10162 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10163 NewFD->hasOwningModule() &&
10164 NewFD->getOwningModule()->isModulePurview()) {
10165 PendingInlineFuncDecls.insert(NewFD);
10169 // Filter out previous declarations that don't match the scope.
10170 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10171 D.getCXXScopeSpec().isNotEmpty() ||
10172 isMemberSpecialization ||
10173 isFunctionTemplateSpecialization);
10175 // Handle GNU asm-label extension (encoded as an attribute).
10176 if (Expr *E = (Expr*) D.getAsmLabel()) {
10177 // The parser guarantees this is a string.
10178 StringLiteral *SE = cast<StringLiteral>(E);
10179 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10180 /*IsLiteralLabel=*/true,
10181 SE->getStrTokenLoc(0)));
10182 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10183 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10184 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10185 if (I != ExtnameUndeclaredIdentifiers.end()) {
10186 if (isDeclExternC(NewFD)) {
10187 NewFD->addAttr(I->second);
10188 ExtnameUndeclaredIdentifiers.erase(I);
10189 } else
10190 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10191 << /*Variable*/0 << NewFD;
10195 // Copy the parameter declarations from the declarator D to the function
10196 // declaration NewFD, if they are available. First scavenge them into Params.
10197 SmallVector<ParmVarDecl*, 16> Params;
10198 unsigned FTIIdx;
10199 if (D.isFunctionDeclarator(FTIIdx)) {
10200 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10202 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10203 // function that takes no arguments, not a function that takes a
10204 // single void argument.
10205 // We let through "const void" here because Sema::GetTypeForDeclarator
10206 // already checks for that case.
10207 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10208 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10209 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10210 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10211 Param->setDeclContext(NewFD);
10212 Params.push_back(Param);
10214 if (Param->isInvalidDecl())
10215 NewFD->setInvalidDecl();
10219 if (!getLangOpts().CPlusPlus) {
10220 // In C, find all the tag declarations from the prototype and move them
10221 // into the function DeclContext. Remove them from the surrounding tag
10222 // injection context of the function, which is typically but not always
10223 // the TU.
10224 DeclContext *PrototypeTagContext =
10225 getTagInjectionContext(NewFD->getLexicalDeclContext());
10226 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10227 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10229 // We don't want to reparent enumerators. Look at their parent enum
10230 // instead.
10231 if (!TD) {
10232 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10233 TD = cast<EnumDecl>(ECD->getDeclContext());
10235 if (!TD)
10236 continue;
10237 DeclContext *TagDC = TD->getLexicalDeclContext();
10238 if (!TagDC->containsDecl(TD))
10239 continue;
10240 TagDC->removeDecl(TD);
10241 TD->setDeclContext(NewFD);
10242 NewFD->addDecl(TD);
10244 // Preserve the lexical DeclContext if it is not the surrounding tag
10245 // injection context of the FD. In this example, the semantic context of
10246 // E will be f and the lexical context will be S, while both the
10247 // semantic and lexical contexts of S will be f:
10248 // void f(struct S { enum E { a } f; } s);
10249 if (TagDC != PrototypeTagContext)
10250 TD->setLexicalDeclContext(TagDC);
10253 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10254 // When we're declaring a function with a typedef, typeof, etc as in the
10255 // following example, we'll need to synthesize (unnamed)
10256 // parameters for use in the declaration.
10258 // @code
10259 // typedef void fn(int);
10260 // fn f;
10261 // @endcode
10263 // Synthesize a parameter for each argument type.
10264 for (const auto &AI : FT->param_types()) {
10265 ParmVarDecl *Param =
10266 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10267 Param->setScopeInfo(0, Params.size());
10268 Params.push_back(Param);
10270 } else {
10271 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10272 "Should not need args for typedef of non-prototype fn");
10275 // Finally, we know we have the right number of parameters, install them.
10276 NewFD->setParams(Params);
10278 if (D.getDeclSpec().isNoreturnSpecified())
10279 NewFD->addAttr(
10280 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10282 // Functions returning a variably modified type violate C99 6.7.5.2p2
10283 // because all functions have linkage.
10284 if (!NewFD->isInvalidDecl() &&
10285 NewFD->getReturnType()->isVariablyModifiedType()) {
10286 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10287 NewFD->setInvalidDecl();
10290 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10291 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10292 !NewFD->hasAttr<SectionAttr>())
10293 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10294 Context, PragmaClangTextSection.SectionName,
10295 PragmaClangTextSection.PragmaLocation));
10297 // Apply an implicit SectionAttr if #pragma code_seg is active.
10298 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10299 !NewFD->hasAttr<SectionAttr>()) {
10300 NewFD->addAttr(SectionAttr::CreateImplicit(
10301 Context, CodeSegStack.CurrentValue->getString(),
10302 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10303 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10304 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10305 ASTContext::PSF_Read,
10306 NewFD))
10307 NewFD->dropAttr<SectionAttr>();
10310 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10311 // active.
10312 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10313 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10314 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10315 Context, PragmaClangTextSection.PragmaLocation));
10317 // Apply an implicit CodeSegAttr from class declspec or
10318 // apply an implicit SectionAttr from #pragma code_seg if active.
10319 if (!NewFD->hasAttr<CodeSegAttr>()) {
10320 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10321 D.isFunctionDefinition())) {
10322 NewFD->addAttr(SAttr);
10326 // Handle attributes.
10327 ProcessDeclAttributes(S, NewFD, D);
10328 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10329 if (NewTVA && !NewTVA->isDefaultVersion() &&
10330 !Context.getTargetInfo().hasFeature("fmv")) {
10331 // Don't add to scope fmv functions declarations if fmv disabled
10332 AddToScope = false;
10333 return NewFD;
10336 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10337 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10338 // type.
10340 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10341 // type declaration will generate a compilation error.
10342 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10343 if (AddressSpace != LangAS::Default) {
10344 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10345 NewFD->setInvalidDecl();
10349 if (!getLangOpts().CPlusPlus) {
10350 // Perform semantic checking on the function declaration.
10351 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10352 CheckMain(NewFD, D.getDeclSpec());
10354 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10355 CheckMSVCRTEntryPoint(NewFD);
10357 if (!NewFD->isInvalidDecl())
10358 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10359 isMemberSpecialization,
10360 D.isFunctionDefinition()));
10361 else if (!Previous.empty())
10362 // Recover gracefully from an invalid redeclaration.
10363 D.setRedeclaration(true);
10364 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10365 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10366 "previous declaration set still overloaded");
10368 // Diagnose no-prototype function declarations with calling conventions that
10369 // don't support variadic calls. Only do this in C and do it after merging
10370 // possibly prototyped redeclarations.
10371 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10372 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10373 CallingConv CC = FT->getExtInfo().getCC();
10374 if (!supportsVariadicCall(CC)) {
10375 // Windows system headers sometimes accidentally use stdcall without
10376 // (void) parameters, so we relax this to a warning.
10377 int DiagID =
10378 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10379 Diag(NewFD->getLocation(), DiagID)
10380 << FunctionType::getNameForCallConv(CC);
10384 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10385 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10386 checkNonTrivialCUnion(NewFD->getReturnType(),
10387 NewFD->getReturnTypeSourceRange().getBegin(),
10388 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10389 } else {
10390 // C++11 [replacement.functions]p3:
10391 // The program's definitions shall not be specified as inline.
10393 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10395 // Suppress the diagnostic if the function is __attribute__((used)), since
10396 // that forces an external definition to be emitted.
10397 if (D.getDeclSpec().isInlineSpecified() &&
10398 NewFD->isReplaceableGlobalAllocationFunction() &&
10399 !NewFD->hasAttr<UsedAttr>())
10400 Diag(D.getDeclSpec().getInlineSpecLoc(),
10401 diag::ext_operator_new_delete_declared_inline)
10402 << NewFD->getDeclName();
10404 // If the declarator is a template-id, translate the parser's template
10405 // argument list into our AST format.
10406 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10407 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10408 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10409 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10410 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10411 TemplateId->NumArgs);
10412 translateTemplateArguments(TemplateArgsPtr,
10413 TemplateArgs);
10415 HasExplicitTemplateArgs = true;
10417 if (NewFD->isInvalidDecl()) {
10418 HasExplicitTemplateArgs = false;
10419 } else if (FunctionTemplate) {
10420 // Function template with explicit template arguments.
10421 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10422 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10424 HasExplicitTemplateArgs = false;
10425 } else if (isFriend) {
10426 // "friend void foo<>(int);" is an implicit specialization decl.
10427 isFunctionTemplateSpecialization = true;
10428 } else {
10429 assert(isFunctionTemplateSpecialization &&
10430 "should have a 'template<>' for this decl");
10432 } else if (isFriend && isFunctionTemplateSpecialization) {
10433 // This combination is only possible in a recovery case; the user
10434 // wrote something like:
10435 // template <> friend void foo(int);
10436 // which we're recovering from as if the user had written:
10437 // friend void foo<>(int);
10438 // Go ahead and fake up a template id.
10439 HasExplicitTemplateArgs = true;
10440 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10441 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10444 // We do not add HD attributes to specializations here because
10445 // they may have different constexpr-ness compared to their
10446 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10447 // may end up with different effective targets. Instead, a
10448 // specialization inherits its target attributes from its template
10449 // in the CheckFunctionTemplateSpecialization() call below.
10450 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10451 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10453 // Handle explict specializations of function templates
10454 // and friend function declarations with an explicit
10455 // template argument list.
10456 if (isFunctionTemplateSpecialization) {
10457 bool isDependentSpecialization = false;
10458 if (isFriend) {
10459 // For friend function specializations, this is a dependent
10460 // specialization if its semantic context is dependent, its
10461 // type is dependent, or if its template-id is dependent.
10462 isDependentSpecialization =
10463 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10464 (HasExplicitTemplateArgs &&
10465 TemplateSpecializationType::
10466 anyInstantiationDependentTemplateArguments(
10467 TemplateArgs.arguments()));
10468 assert((!isDependentSpecialization ||
10469 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10470 "dependent friend function specialization without template "
10471 "args");
10472 } else {
10473 // For class-scope explicit specializations of function templates,
10474 // if the lexical context is dependent, then the specialization
10475 // is dependent.
10476 isDependentSpecialization =
10477 CurContext->isRecord() && CurContext->isDependentContext();
10480 TemplateArgumentListInfo *ExplicitTemplateArgs =
10481 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10482 if (isDependentSpecialization) {
10483 // If it's a dependent specialization, it may not be possible
10484 // to determine the primary template (for explicit specializations)
10485 // or befriended declaration (for friends) until the enclosing
10486 // template is instantiated. In such cases, we store the declarations
10487 // found by name lookup and defer resolution until instantiation.
10488 if (CheckDependentFunctionTemplateSpecialization(
10489 NewFD, ExplicitTemplateArgs, Previous))
10490 NewFD->setInvalidDecl();
10491 } else if (!NewFD->isInvalidDecl()) {
10492 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10493 Previous))
10494 NewFD->setInvalidDecl();
10497 // C++ [dcl.stc]p1:
10498 // A storage-class-specifier shall not be specified in an explicit
10499 // specialization (14.7.3)
10500 // FIXME: We should be checking this for dependent specializations.
10501 FunctionTemplateSpecializationInfo *Info =
10502 NewFD->getTemplateSpecializationInfo();
10503 if (Info && SC != SC_None) {
10504 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10505 Diag(NewFD->getLocation(),
10506 diag::err_explicit_specialization_inconsistent_storage_class)
10507 << SC
10508 << FixItHint::CreateRemoval(
10509 D.getDeclSpec().getStorageClassSpecLoc());
10511 else
10512 Diag(NewFD->getLocation(),
10513 diag::ext_explicit_specialization_storage_class)
10514 << FixItHint::CreateRemoval(
10515 D.getDeclSpec().getStorageClassSpecLoc());
10517 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10518 if (CheckMemberSpecialization(NewFD, Previous))
10519 NewFD->setInvalidDecl();
10522 // Perform semantic checking on the function declaration.
10523 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10524 CheckMain(NewFD, D.getDeclSpec());
10526 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10527 CheckMSVCRTEntryPoint(NewFD);
10529 if (!NewFD->isInvalidDecl())
10530 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10531 isMemberSpecialization,
10532 D.isFunctionDefinition()));
10533 else if (!Previous.empty())
10534 // Recover gracefully from an invalid redeclaration.
10535 D.setRedeclaration(true);
10537 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10538 !D.isRedeclaration() ||
10539 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10540 "previous declaration set still overloaded");
10542 NamedDecl *PrincipalDecl = (FunctionTemplate
10543 ? cast<NamedDecl>(FunctionTemplate)
10544 : NewFD);
10546 if (isFriend && NewFD->getPreviousDecl()) {
10547 AccessSpecifier Access = AS_public;
10548 if (!NewFD->isInvalidDecl())
10549 Access = NewFD->getPreviousDecl()->getAccess();
10551 NewFD->setAccess(Access);
10552 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10555 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10556 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10557 PrincipalDecl->setNonMemberOperator();
10559 // If we have a function template, check the template parameter
10560 // list. This will check and merge default template arguments.
10561 if (FunctionTemplate) {
10562 FunctionTemplateDecl *PrevTemplate =
10563 FunctionTemplate->getPreviousDecl();
10564 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10565 PrevTemplate ? PrevTemplate->getTemplateParameters()
10566 : nullptr,
10567 D.getDeclSpec().isFriendSpecified()
10568 ? (D.isFunctionDefinition()
10569 ? TPC_FriendFunctionTemplateDefinition
10570 : TPC_FriendFunctionTemplate)
10571 : (D.getCXXScopeSpec().isSet() &&
10572 DC && DC->isRecord() &&
10573 DC->isDependentContext())
10574 ? TPC_ClassTemplateMember
10575 : TPC_FunctionTemplate);
10578 if (NewFD->isInvalidDecl()) {
10579 // Ignore all the rest of this.
10580 } else if (!D.isRedeclaration()) {
10581 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10582 AddToScope };
10583 // Fake up an access specifier if it's supposed to be a class member.
10584 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10585 NewFD->setAccess(AS_public);
10587 // Qualified decls generally require a previous declaration.
10588 if (D.getCXXScopeSpec().isSet()) {
10589 // ...with the major exception of templated-scope or
10590 // dependent-scope friend declarations.
10592 // TODO: we currently also suppress this check in dependent
10593 // contexts because (1) the parameter depth will be off when
10594 // matching friend templates and (2) we might actually be
10595 // selecting a friend based on a dependent factor. But there
10596 // are situations where these conditions don't apply and we
10597 // can actually do this check immediately.
10599 // Unless the scope is dependent, it's always an error if qualified
10600 // redeclaration lookup found nothing at all. Diagnose that now;
10601 // nothing will diagnose that error later.
10602 if (isFriend &&
10603 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10604 (!Previous.empty() && CurContext->isDependentContext()))) {
10605 // ignore these
10606 } else if (NewFD->isCPUDispatchMultiVersion() ||
10607 NewFD->isCPUSpecificMultiVersion()) {
10608 // ignore this, we allow the redeclaration behavior here to create new
10609 // versions of the function.
10610 } else {
10611 // The user tried to provide an out-of-line definition for a
10612 // function that is a member of a class or namespace, but there
10613 // was no such member function declared (C++ [class.mfct]p2,
10614 // C++ [namespace.memdef]p2). For example:
10616 // class X {
10617 // void f() const;
10618 // };
10620 // void X::f() { } // ill-formed
10622 // Complain about this problem, and attempt to suggest close
10623 // matches (e.g., those that differ only in cv-qualifiers and
10624 // whether the parameter types are references).
10626 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10627 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10628 AddToScope = ExtraArgs.AddToScope;
10629 return Result;
10633 // Unqualified local friend declarations are required to resolve
10634 // to something.
10635 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10636 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10637 *this, Previous, NewFD, ExtraArgs, true, S)) {
10638 AddToScope = ExtraArgs.AddToScope;
10639 return Result;
10642 } else if (!D.isFunctionDefinition() &&
10643 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10644 !isFriend && !isFunctionTemplateSpecialization &&
10645 !isMemberSpecialization) {
10646 // An out-of-line member function declaration must also be a
10647 // definition (C++ [class.mfct]p2).
10648 // Note that this is not the case for explicit specializations of
10649 // function templates or member functions of class templates, per
10650 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10651 // extension for compatibility with old SWIG code which likes to
10652 // generate them.
10653 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10654 << D.getCXXScopeSpec().getRange();
10658 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10659 // Any top level function could potentially be specified as an entry.
10660 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10661 ActOnHLSLTopLevelFunction(NewFD);
10663 if (NewFD->hasAttr<HLSLShaderAttr>())
10664 CheckHLSLEntryPoint(NewFD);
10667 // If this is the first declaration of a library builtin function, add
10668 // attributes as appropriate.
10669 if (!D.isRedeclaration()) {
10670 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10671 if (unsigned BuiltinID = II->getBuiltinID()) {
10672 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10673 if (!InStdNamespace &&
10674 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10675 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10676 // Validate the type matches unless this builtin is specified as
10677 // matching regardless of its declared type.
10678 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10679 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10680 } else {
10681 ASTContext::GetBuiltinTypeError Error;
10682 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10683 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10685 if (!Error && !BuiltinType.isNull() &&
10686 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10687 NewFD->getType(), BuiltinType))
10688 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10691 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10692 isStdBuiltin(Context, NewFD, BuiltinID)) {
10693 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10699 ProcessPragmaWeak(S, NewFD);
10700 checkAttributesAfterMerging(*this, *NewFD);
10702 AddKnownFunctionAttributes(NewFD);
10704 if (NewFD->hasAttr<OverloadableAttr>() &&
10705 !NewFD->getType()->getAs<FunctionProtoType>()) {
10706 Diag(NewFD->getLocation(),
10707 diag::err_attribute_overloadable_no_prototype)
10708 << NewFD;
10709 NewFD->dropAttr<OverloadableAttr>();
10712 // If there's a #pragma GCC visibility in scope, and this isn't a class
10713 // member, set the visibility of this function.
10714 if (!DC->isRecord() && NewFD->isExternallyVisible())
10715 AddPushedVisibilityAttribute(NewFD);
10717 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10718 // marking the function.
10719 AddCFAuditedAttribute(NewFD);
10721 // If this is a function definition, check if we have to apply any
10722 // attributes (i.e. optnone and no_builtin) due to a pragma.
10723 if (D.isFunctionDefinition()) {
10724 AddRangeBasedOptnone(NewFD);
10725 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10726 AddSectionMSAllocText(NewFD);
10727 ModifyFnAttributesMSPragmaOptimize(NewFD);
10730 // If this is the first declaration of an extern C variable, update
10731 // the map of such variables.
10732 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10733 isIncompleteDeclExternC(*this, NewFD))
10734 RegisterLocallyScopedExternCDecl(NewFD, S);
10736 // Set this FunctionDecl's range up to the right paren.
10737 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10739 if (D.isRedeclaration() && !Previous.empty()) {
10740 NamedDecl *Prev = Previous.getRepresentativeDecl();
10741 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10742 isMemberSpecialization ||
10743 isFunctionTemplateSpecialization,
10744 D.isFunctionDefinition());
10747 if (getLangOpts().CUDA) {
10748 IdentifierInfo *II = NewFD->getIdentifier();
10749 if (II && II->isStr(getCudaConfigureFuncName()) &&
10750 !NewFD->isInvalidDecl() &&
10751 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10752 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10753 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10754 << getCudaConfigureFuncName();
10755 Context.setcudaConfigureCallDecl(NewFD);
10758 // Variadic functions, other than a *declaration* of printf, are not allowed
10759 // in device-side CUDA code, unless someone passed
10760 // -fcuda-allow-variadic-functions.
10761 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10762 (NewFD->hasAttr<CUDADeviceAttr>() ||
10763 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10764 !(II && II->isStr("printf") && NewFD->isExternC() &&
10765 !D.isFunctionDefinition())) {
10766 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10770 MarkUnusedFileScopedDecl(NewFD);
10774 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10775 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10776 if (SC == SC_Static) {
10777 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10778 D.setInvalidType();
10781 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10782 if (!NewFD->getReturnType()->isVoidType()) {
10783 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10784 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10785 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10786 : FixItHint());
10787 D.setInvalidType();
10790 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10791 for (auto *Param : NewFD->parameters())
10792 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10794 if (getLangOpts().OpenCLCPlusPlus) {
10795 if (DC->isRecord()) {
10796 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10797 D.setInvalidType();
10799 if (FunctionTemplate) {
10800 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10801 D.setInvalidType();
10806 if (getLangOpts().CPlusPlus) {
10807 // Precalculate whether this is a friend function template with a constraint
10808 // that depends on an enclosing template, per [temp.friend]p9.
10809 if (isFriend && FunctionTemplate &&
10810 FriendConstraintsDependOnEnclosingTemplate(NewFD))
10811 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10813 if (FunctionTemplate) {
10814 if (NewFD->isInvalidDecl())
10815 FunctionTemplate->setInvalidDecl();
10816 return FunctionTemplate;
10819 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10820 CompleteMemberSpecialization(NewFD, Previous);
10823 for (const ParmVarDecl *Param : NewFD->parameters()) {
10824 QualType PT = Param->getType();
10826 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10827 // types.
10828 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10829 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10830 QualType ElemTy = PipeTy->getElementType();
10831 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10832 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10833 D.setInvalidType();
10837 // WebAssembly tables can't be used as function parameters.
10838 if (Context.getTargetInfo().getTriple().isWasm()) {
10839 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10840 Diag(Param->getTypeSpecStartLoc(),
10841 diag::err_wasm_table_as_function_parameter);
10842 D.setInvalidType();
10847 // Diagnose availability attributes. Availability cannot be used on functions
10848 // that are run during load/unload.
10849 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10850 if (NewFD->hasAttr<ConstructorAttr>()) {
10851 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10852 << 1;
10853 NewFD->dropAttr<AvailabilityAttr>();
10855 if (NewFD->hasAttr<DestructorAttr>()) {
10856 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10857 << 2;
10858 NewFD->dropAttr<AvailabilityAttr>();
10862 // Diagnose no_builtin attribute on function declaration that are not a
10863 // definition.
10864 // FIXME: We should really be doing this in
10865 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10866 // the FunctionDecl and at this point of the code
10867 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10868 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10869 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10870 switch (D.getFunctionDefinitionKind()) {
10871 case FunctionDefinitionKind::Defaulted:
10872 case FunctionDefinitionKind::Deleted:
10873 Diag(NBA->getLocation(),
10874 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10875 << NBA->getSpelling();
10876 break;
10877 case FunctionDefinitionKind::Declaration:
10878 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10879 << NBA->getSpelling();
10880 break;
10881 case FunctionDefinitionKind::Definition:
10882 break;
10885 return NewFD;
10888 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10889 /// when __declspec(code_seg) "is applied to a class, all member functions of
10890 /// the class and nested classes -- this includes compiler-generated special
10891 /// member functions -- are put in the specified segment."
10892 /// The actual behavior is a little more complicated. The Microsoft compiler
10893 /// won't check outer classes if there is an active value from #pragma code_seg.
10894 /// The CodeSeg is always applied from the direct parent but only from outer
10895 /// classes when the #pragma code_seg stack is empty. See:
10896 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10897 /// available since MS has removed the page.
10898 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10899 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10900 if (!Method)
10901 return nullptr;
10902 const CXXRecordDecl *Parent = Method->getParent();
10903 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10904 Attr *NewAttr = SAttr->clone(S.getASTContext());
10905 NewAttr->setImplicit(true);
10906 return NewAttr;
10909 // The Microsoft compiler won't check outer classes for the CodeSeg
10910 // when the #pragma code_seg stack is active.
10911 if (S.CodeSegStack.CurrentValue)
10912 return nullptr;
10914 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10915 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10916 Attr *NewAttr = SAttr->clone(S.getASTContext());
10917 NewAttr->setImplicit(true);
10918 return NewAttr;
10921 return nullptr;
10924 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10925 /// containing class. Otherwise it will return implicit SectionAttr if the
10926 /// function is a definition and there is an active value on CodeSegStack
10927 /// (from the current #pragma code-seg value).
10929 /// \param FD Function being declared.
10930 /// \param IsDefinition Whether it is a definition or just a declaration.
10931 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10932 /// nullptr if no attribute should be added.
10933 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10934 bool IsDefinition) {
10935 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10936 return A;
10937 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10938 CodeSegStack.CurrentValue)
10939 return SectionAttr::CreateImplicit(
10940 getASTContext(), CodeSegStack.CurrentValue->getString(),
10941 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10942 return nullptr;
10945 /// Determines if we can perform a correct type check for \p D as a
10946 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10947 /// best-effort check.
10949 /// \param NewD The new declaration.
10950 /// \param OldD The old declaration.
10951 /// \param NewT The portion of the type of the new declaration to check.
10952 /// \param OldT The portion of the type of the old declaration to check.
10953 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10954 QualType NewT, QualType OldT) {
10955 if (!NewD->getLexicalDeclContext()->isDependentContext())
10956 return true;
10958 // For dependently-typed local extern declarations and friends, we can't
10959 // perform a correct type check in general until instantiation:
10961 // int f();
10962 // template<typename T> void g() { T f(); }
10964 // (valid if g() is only instantiated with T = int).
10965 if (NewT->isDependentType() &&
10966 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10967 return false;
10969 // Similarly, if the previous declaration was a dependent local extern
10970 // declaration, we don't really know its type yet.
10971 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10972 return false;
10974 return true;
10977 /// Checks if the new declaration declared in dependent context must be
10978 /// put in the same redeclaration chain as the specified declaration.
10980 /// \param D Declaration that is checked.
10981 /// \param PrevDecl Previous declaration found with proper lookup method for the
10982 /// same declaration name.
10983 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10984 /// belongs to.
10986 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10987 if (!D->getLexicalDeclContext()->isDependentContext())
10988 return true;
10990 // Don't chain dependent friend function definitions until instantiation, to
10991 // permit cases like
10993 // void func();
10994 // template<typename T> class C1 { friend void func() {} };
10995 // template<typename T> class C2 { friend void func() {} };
10997 // ... which is valid if only one of C1 and C2 is ever instantiated.
10999 // FIXME: This need only apply to function definitions. For now, we proxy
11000 // this by checking for a file-scope function. We do not want this to apply
11001 // to friend declarations nominating member functions, because that gets in
11002 // the way of access checks.
11003 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11004 return false;
11006 auto *VD = dyn_cast<ValueDecl>(D);
11007 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11008 return !VD || !PrevVD ||
11009 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11010 PrevVD->getType());
11013 /// Check the target or target_version attribute of the function for
11014 /// MultiVersion validity.
11016 /// Returns true if there was an error, false otherwise.
11017 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11018 const auto *TA = FD->getAttr<TargetAttr>();
11019 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11020 assert(
11021 (TA || TVA) &&
11022 "MultiVersion candidate requires a target or target_version attribute");
11023 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11024 enum ErrType { Feature = 0, Architecture = 1 };
11026 if (TA) {
11027 ParsedTargetAttr ParseInfo =
11028 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11029 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11030 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11031 << Architecture << ParseInfo.CPU;
11032 return true;
11034 for (const auto &Feat : ParseInfo.Features) {
11035 auto BareFeat = StringRef{Feat}.substr(1);
11036 if (Feat[0] == '-') {
11037 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11038 << Feature << ("no-" + BareFeat).str();
11039 return true;
11042 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11043 !TargetInfo.isValidFeatureName(BareFeat)) {
11044 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11045 << Feature << BareFeat;
11046 return true;
11051 if (TVA) {
11052 llvm::SmallVector<StringRef, 8> Feats;
11053 TVA->getFeatures(Feats);
11054 for (const auto &Feat : Feats) {
11055 if (!TargetInfo.validateCpuSupports(Feat)) {
11056 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11057 << Feature << Feat;
11058 return true;
11062 return false;
11065 // Provide a white-list of attributes that are allowed to be combined with
11066 // multiversion functions.
11067 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11068 MultiVersionKind MVKind) {
11069 // Note: this list/diagnosis must match the list in
11070 // checkMultiversionAttributesAllSame.
11071 switch (Kind) {
11072 default:
11073 return false;
11074 case attr::Used:
11075 return MVKind == MultiVersionKind::Target;
11076 case attr::NonNull:
11077 case attr::NoThrow:
11078 return true;
11082 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11083 const FunctionDecl *FD,
11084 const FunctionDecl *CausedFD,
11085 MultiVersionKind MVKind) {
11086 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11087 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11088 << static_cast<unsigned>(MVKind) << A;
11089 if (CausedFD)
11090 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11091 return true;
11094 for (const Attr *A : FD->attrs()) {
11095 switch (A->getKind()) {
11096 case attr::CPUDispatch:
11097 case attr::CPUSpecific:
11098 if (MVKind != MultiVersionKind::CPUDispatch &&
11099 MVKind != MultiVersionKind::CPUSpecific)
11100 return Diagnose(S, A);
11101 break;
11102 case attr::Target:
11103 if (MVKind != MultiVersionKind::Target)
11104 return Diagnose(S, A);
11105 break;
11106 case attr::TargetVersion:
11107 if (MVKind != MultiVersionKind::TargetVersion)
11108 return Diagnose(S, A);
11109 break;
11110 case attr::TargetClones:
11111 if (MVKind != MultiVersionKind::TargetClones)
11112 return Diagnose(S, A);
11113 break;
11114 default:
11115 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11116 return Diagnose(S, A);
11117 break;
11120 return false;
11123 bool Sema::areMultiversionVariantFunctionsCompatible(
11124 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11125 const PartialDiagnostic &NoProtoDiagID,
11126 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11127 const PartialDiagnosticAt &NoSupportDiagIDAt,
11128 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11129 bool ConstexprSupported, bool CLinkageMayDiffer) {
11130 enum DoesntSupport {
11131 FuncTemplates = 0,
11132 VirtFuncs = 1,
11133 DeducedReturn = 2,
11134 Constructors = 3,
11135 Destructors = 4,
11136 DeletedFuncs = 5,
11137 DefaultedFuncs = 6,
11138 ConstexprFuncs = 7,
11139 ConstevalFuncs = 8,
11140 Lambda = 9,
11142 enum Different {
11143 CallingConv = 0,
11144 ReturnType = 1,
11145 ConstexprSpec = 2,
11146 InlineSpec = 3,
11147 Linkage = 4,
11148 LanguageLinkage = 5,
11151 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11152 !OldFD->getType()->getAs<FunctionProtoType>()) {
11153 Diag(OldFD->getLocation(), NoProtoDiagID);
11154 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11155 return true;
11158 if (NoProtoDiagID.getDiagID() != 0 &&
11159 !NewFD->getType()->getAs<FunctionProtoType>())
11160 return Diag(NewFD->getLocation(), NoProtoDiagID);
11162 if (!TemplatesSupported &&
11163 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11164 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11165 << FuncTemplates;
11167 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11168 if (NewCXXFD->isVirtual())
11169 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11170 << VirtFuncs;
11172 if (isa<CXXConstructorDecl>(NewCXXFD))
11173 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11174 << Constructors;
11176 if (isa<CXXDestructorDecl>(NewCXXFD))
11177 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11178 << Destructors;
11181 if (NewFD->isDeleted())
11182 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11183 << DeletedFuncs;
11185 if (NewFD->isDefaulted())
11186 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11187 << DefaultedFuncs;
11189 if (!ConstexprSupported && NewFD->isConstexpr())
11190 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11191 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11193 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11194 const auto *NewType = cast<FunctionType>(NewQType);
11195 QualType NewReturnType = NewType->getReturnType();
11197 if (NewReturnType->isUndeducedType())
11198 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11199 << DeducedReturn;
11201 // Ensure the return type is identical.
11202 if (OldFD) {
11203 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11204 const auto *OldType = cast<FunctionType>(OldQType);
11205 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11206 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11208 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11209 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11211 QualType OldReturnType = OldType->getReturnType();
11213 if (OldReturnType != NewReturnType)
11214 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11216 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11217 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11219 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11220 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11222 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11223 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11225 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11226 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11228 if (CheckEquivalentExceptionSpec(
11229 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11230 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11231 return true;
11233 return false;
11236 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11237 const FunctionDecl *NewFD,
11238 bool CausesMV,
11239 MultiVersionKind MVKind) {
11240 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11241 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11242 if (OldFD)
11243 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11244 return true;
11247 bool IsCPUSpecificCPUDispatchMVKind =
11248 MVKind == MultiVersionKind::CPUDispatch ||
11249 MVKind == MultiVersionKind::CPUSpecific;
11251 if (CausesMV && OldFD &&
11252 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11253 return true;
11255 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11256 return true;
11258 // Only allow transition to MultiVersion if it hasn't been used.
11259 if (OldFD && CausesMV && OldFD->isUsed(false))
11260 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11262 return S.areMultiversionVariantFunctionsCompatible(
11263 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11264 PartialDiagnosticAt(NewFD->getLocation(),
11265 S.PDiag(diag::note_multiversioning_caused_here)),
11266 PartialDiagnosticAt(NewFD->getLocation(),
11267 S.PDiag(diag::err_multiversion_doesnt_support)
11268 << static_cast<unsigned>(MVKind)),
11269 PartialDiagnosticAt(NewFD->getLocation(),
11270 S.PDiag(diag::err_multiversion_diff)),
11271 /*TemplatesSupported=*/false,
11272 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11273 /*CLinkageMayDiffer=*/false);
11276 /// Check the validity of a multiversion function declaration that is the
11277 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11279 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11281 /// Returns true if there was an error, false otherwise.
11282 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11283 MultiVersionKind MVKind = FD->getMultiVersionKind();
11284 assert(MVKind != MultiVersionKind::None &&
11285 "Function lacks multiversion attribute");
11286 const auto *TA = FD->getAttr<TargetAttr>();
11287 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11288 // Target and target_version only causes MV if it is default, otherwise this
11289 // is a normal function.
11290 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11291 return false;
11293 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11294 FD->setInvalidDecl();
11295 return true;
11298 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11299 FD->setInvalidDecl();
11300 return true;
11303 FD->setIsMultiVersion();
11304 return false;
11307 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11308 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11309 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11310 return true;
11313 return false;
11316 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11317 FunctionDecl *NewFD,
11318 bool &Redeclaration,
11319 NamedDecl *&OldDecl,
11320 LookupResult &Previous) {
11321 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11322 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11323 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11324 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11325 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11326 // to change, this is a simple redeclaration.
11327 if ((NewTA && !NewTA->isDefaultVersion() &&
11328 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11329 (NewTVA && !NewTVA->isDefaultVersion() &&
11330 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11331 return false;
11333 // Otherwise, this decl causes MultiVersioning.
11334 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11335 NewTVA ? MultiVersionKind::TargetVersion
11336 : MultiVersionKind::Target)) {
11337 NewFD->setInvalidDecl();
11338 return true;
11341 if (CheckMultiVersionValue(S, NewFD)) {
11342 NewFD->setInvalidDecl();
11343 return true;
11346 // If this is 'default', permit the forward declaration.
11347 if (!OldFD->isMultiVersion() &&
11348 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11349 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11350 Redeclaration = true;
11351 OldDecl = OldFD;
11352 OldFD->setIsMultiVersion();
11353 NewFD->setIsMultiVersion();
11354 return false;
11357 if (CheckMultiVersionValue(S, OldFD)) {
11358 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11359 NewFD->setInvalidDecl();
11360 return true;
11363 if (NewTA) {
11364 ParsedTargetAttr OldParsed =
11365 S.getASTContext().getTargetInfo().parseTargetAttr(
11366 OldTA->getFeaturesStr());
11367 llvm::sort(OldParsed.Features);
11368 ParsedTargetAttr NewParsed =
11369 S.getASTContext().getTargetInfo().parseTargetAttr(
11370 NewTA->getFeaturesStr());
11371 // Sort order doesn't matter, it just needs to be consistent.
11372 llvm::sort(NewParsed.Features);
11373 if (OldParsed == NewParsed) {
11374 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11375 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11376 NewFD->setInvalidDecl();
11377 return true;
11381 if (NewTVA) {
11382 llvm::SmallVector<StringRef, 8> Feats;
11383 OldTVA->getFeatures(Feats);
11384 llvm::sort(Feats);
11385 llvm::SmallVector<StringRef, 8> NewFeats;
11386 NewTVA->getFeatures(NewFeats);
11387 llvm::sort(NewFeats);
11389 if (Feats == NewFeats) {
11390 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11391 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11392 NewFD->setInvalidDecl();
11393 return true;
11397 for (const auto *FD : OldFD->redecls()) {
11398 const auto *CurTA = FD->getAttr<TargetAttr>();
11399 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11400 // We allow forward declarations before ANY multiversioning attributes, but
11401 // nothing after the fact.
11402 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11403 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11404 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11405 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11406 << (NewTA ? 0 : 2);
11407 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11408 NewFD->setInvalidDecl();
11409 return true;
11413 OldFD->setIsMultiVersion();
11414 NewFD->setIsMultiVersion();
11415 Redeclaration = false;
11416 OldDecl = nullptr;
11417 Previous.clear();
11418 return false;
11421 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11422 MultiVersionKind New) {
11423 if (Old == New || Old == MultiVersionKind::None ||
11424 New == MultiVersionKind::None)
11425 return true;
11427 return (Old == MultiVersionKind::CPUDispatch &&
11428 New == MultiVersionKind::CPUSpecific) ||
11429 (Old == MultiVersionKind::CPUSpecific &&
11430 New == MultiVersionKind::CPUDispatch);
11433 /// Check the validity of a new function declaration being added to an existing
11434 /// multiversioned declaration collection.
11435 static bool CheckMultiVersionAdditionalDecl(
11436 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11437 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11438 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11439 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11440 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11441 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11442 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11443 // Disallow mixing of multiversioning types.
11444 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11445 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11446 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11447 NewFD->setInvalidDecl();
11448 return true;
11451 ParsedTargetAttr NewParsed;
11452 if (NewTA) {
11453 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11454 NewTA->getFeaturesStr());
11455 llvm::sort(NewParsed.Features);
11457 llvm::SmallVector<StringRef, 8> NewFeats;
11458 if (NewTVA) {
11459 NewTVA->getFeatures(NewFeats);
11460 llvm::sort(NewFeats);
11463 bool UseMemberUsingDeclRules =
11464 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11466 bool MayNeedOverloadableChecks =
11467 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11469 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11470 // of a previous member of the MultiVersion set.
11471 for (NamedDecl *ND : Previous) {
11472 FunctionDecl *CurFD = ND->getAsFunction();
11473 if (!CurFD || CurFD->isInvalidDecl())
11474 continue;
11475 if (MayNeedOverloadableChecks &&
11476 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11477 continue;
11479 if (NewMVKind == MultiVersionKind::None &&
11480 OldMVKind == MultiVersionKind::TargetVersion) {
11481 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11482 S.Context, "default", NewFD->getSourceRange()));
11483 NewFD->setIsMultiVersion();
11484 NewMVKind = MultiVersionKind::TargetVersion;
11485 if (!NewTVA) {
11486 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11487 NewTVA->getFeatures(NewFeats);
11488 llvm::sort(NewFeats);
11492 switch (NewMVKind) {
11493 case MultiVersionKind::None:
11494 assert(OldMVKind == MultiVersionKind::TargetClones &&
11495 "Only target_clones can be omitted in subsequent declarations");
11496 break;
11497 case MultiVersionKind::Target: {
11498 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11499 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11500 NewFD->setIsMultiVersion();
11501 Redeclaration = true;
11502 OldDecl = ND;
11503 return false;
11506 ParsedTargetAttr CurParsed =
11507 S.getASTContext().getTargetInfo().parseTargetAttr(
11508 CurTA->getFeaturesStr());
11509 llvm::sort(CurParsed.Features);
11510 if (CurParsed == NewParsed) {
11511 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11512 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11513 NewFD->setInvalidDecl();
11514 return true;
11516 break;
11518 case MultiVersionKind::TargetVersion: {
11519 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11520 if (CurTVA->getName() == NewTVA->getName()) {
11521 NewFD->setIsMultiVersion();
11522 Redeclaration = true;
11523 OldDecl = ND;
11524 return false;
11526 llvm::SmallVector<StringRef, 8> CurFeats;
11527 if (CurTVA) {
11528 CurTVA->getFeatures(CurFeats);
11529 llvm::sort(CurFeats);
11531 if (CurFeats == NewFeats) {
11532 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11533 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11534 NewFD->setInvalidDecl();
11535 return true;
11537 break;
11539 case MultiVersionKind::TargetClones: {
11540 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11541 Redeclaration = true;
11542 OldDecl = CurFD;
11543 NewFD->setIsMultiVersion();
11545 if (CurClones && NewClones &&
11546 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11547 !std::equal(CurClones->featuresStrs_begin(),
11548 CurClones->featuresStrs_end(),
11549 NewClones->featuresStrs_begin()))) {
11550 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11551 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11552 NewFD->setInvalidDecl();
11553 return true;
11556 return false;
11558 case MultiVersionKind::CPUSpecific:
11559 case MultiVersionKind::CPUDispatch: {
11560 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11561 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11562 // Handle CPUDispatch/CPUSpecific versions.
11563 // Only 1 CPUDispatch function is allowed, this will make it go through
11564 // the redeclaration errors.
11565 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11566 CurFD->hasAttr<CPUDispatchAttr>()) {
11567 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11568 std::equal(
11569 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11570 NewCPUDisp->cpus_begin(),
11571 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11572 return Cur->getName() == New->getName();
11573 })) {
11574 NewFD->setIsMultiVersion();
11575 Redeclaration = true;
11576 OldDecl = ND;
11577 return false;
11580 // If the declarations don't match, this is an error condition.
11581 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11582 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11583 NewFD->setInvalidDecl();
11584 return true;
11586 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11587 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11588 std::equal(
11589 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11590 NewCPUSpec->cpus_begin(),
11591 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11592 return Cur->getName() == New->getName();
11593 })) {
11594 NewFD->setIsMultiVersion();
11595 Redeclaration = true;
11596 OldDecl = ND;
11597 return false;
11600 // Only 1 version of CPUSpecific is allowed for each CPU.
11601 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11602 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11603 if (CurII == NewII) {
11604 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11605 << NewII;
11606 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11607 NewFD->setInvalidDecl();
11608 return true;
11613 break;
11618 // Else, this is simply a non-redecl case. Checking the 'value' is only
11619 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11620 // handled in the attribute adding step.
11621 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11622 NewMVKind == MultiVersionKind::Target) &&
11623 CheckMultiVersionValue(S, NewFD)) {
11624 NewFD->setInvalidDecl();
11625 return true;
11628 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11629 !OldFD->isMultiVersion(), NewMVKind)) {
11630 NewFD->setInvalidDecl();
11631 return true;
11634 // Permit forward declarations in the case where these two are compatible.
11635 if (!OldFD->isMultiVersion()) {
11636 OldFD->setIsMultiVersion();
11637 NewFD->setIsMultiVersion();
11638 Redeclaration = true;
11639 OldDecl = OldFD;
11640 return false;
11643 NewFD->setIsMultiVersion();
11644 Redeclaration = false;
11645 OldDecl = nullptr;
11646 Previous.clear();
11647 return false;
11650 /// Check the validity of a mulitversion function declaration.
11651 /// Also sets the multiversion'ness' of the function itself.
11653 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11655 /// Returns true if there was an error, false otherwise.
11656 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11657 bool &Redeclaration, NamedDecl *&OldDecl,
11658 LookupResult &Previous) {
11659 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11660 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11661 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11662 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11663 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11664 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11666 // Main isn't allowed to become a multiversion function, however it IS
11667 // permitted to have 'main' be marked with the 'target' optimization hint,
11668 // for 'target_version' only default is allowed.
11669 if (NewFD->isMain()) {
11670 if (MVKind != MultiVersionKind::None &&
11671 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11672 !(MVKind == MultiVersionKind::TargetVersion &&
11673 NewTVA->isDefaultVersion())) {
11674 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11675 NewFD->setInvalidDecl();
11676 return true;
11678 return false;
11681 // Target attribute on AArch64 is not used for multiversioning
11682 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11683 return false;
11685 if (!OldDecl || !OldDecl->getAsFunction() ||
11686 OldDecl->getDeclContext()->getRedeclContext() !=
11687 NewFD->getDeclContext()->getRedeclContext()) {
11688 // If there's no previous declaration, AND this isn't attempting to cause
11689 // multiversioning, this isn't an error condition.
11690 if (MVKind == MultiVersionKind::None)
11691 return false;
11692 return CheckMultiVersionFirstFunction(S, NewFD);
11695 FunctionDecl *OldFD = OldDecl->getAsFunction();
11697 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11698 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11699 return false;
11700 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11701 // Multiversion declaration doesn't have prototype.
11702 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11703 NewFD->setInvalidDecl();
11704 } else {
11705 // No "target_version" attribute is equivalent to "default" attribute.
11706 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11707 S.Context, "default", NewFD->getSourceRange()));
11708 NewFD->setIsMultiVersion();
11709 OldFD->setIsMultiVersion();
11710 OldDecl = OldFD;
11711 Redeclaration = true;
11713 return true;
11716 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11717 // for target_clones and target_version.
11718 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11719 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11720 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11721 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11722 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11723 NewFD->setInvalidDecl();
11724 return true;
11727 if (!OldFD->isMultiVersion()) {
11728 switch (MVKind) {
11729 case MultiVersionKind::Target:
11730 case MultiVersionKind::TargetVersion:
11731 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11732 OldDecl, Previous);
11733 case MultiVersionKind::TargetClones:
11734 if (OldFD->isUsed(false)) {
11735 NewFD->setInvalidDecl();
11736 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11738 OldFD->setIsMultiVersion();
11739 break;
11741 case MultiVersionKind::CPUDispatch:
11742 case MultiVersionKind::CPUSpecific:
11743 case MultiVersionKind::None:
11744 break;
11748 // At this point, we have a multiversion function decl (in OldFD) AND an
11749 // appropriate attribute in the current function decl. Resolve that these are
11750 // still compatible with previous declarations.
11751 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11752 NewCPUSpec, NewClones, Redeclaration,
11753 OldDecl, Previous);
11756 /// Perform semantic checking of a new function declaration.
11758 /// Performs semantic analysis of the new function declaration
11759 /// NewFD. This routine performs all semantic checking that does not
11760 /// require the actual declarator involved in the declaration, and is
11761 /// used both for the declaration of functions as they are parsed
11762 /// (called via ActOnDeclarator) and for the declaration of functions
11763 /// that have been instantiated via C++ template instantiation (called
11764 /// via InstantiateDecl).
11766 /// \param IsMemberSpecialization whether this new function declaration is
11767 /// a member specialization (that replaces any definition provided by the
11768 /// previous declaration).
11770 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11772 /// \returns true if the function declaration is a redeclaration.
11773 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11774 LookupResult &Previous,
11775 bool IsMemberSpecialization,
11776 bool DeclIsDefn) {
11777 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11778 "Variably modified return types are not handled here");
11780 // Determine whether the type of this function should be merged with
11781 // a previous visible declaration. This never happens for functions in C++,
11782 // and always happens in C if the previous declaration was visible.
11783 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11784 !Previous.isShadowed();
11786 bool Redeclaration = false;
11787 NamedDecl *OldDecl = nullptr;
11788 bool MayNeedOverloadableChecks = false;
11790 // Merge or overload the declaration with an existing declaration of
11791 // the same name, if appropriate.
11792 if (!Previous.empty()) {
11793 // Determine whether NewFD is an overload of PrevDecl or
11794 // a declaration that requires merging. If it's an overload,
11795 // there's no more work to do here; we'll just add the new
11796 // function to the scope.
11797 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11798 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11799 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11800 Redeclaration = true;
11801 OldDecl = Candidate;
11803 } else {
11804 MayNeedOverloadableChecks = true;
11805 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11806 /*NewIsUsingDecl*/ false)) {
11807 case Ovl_Match:
11808 Redeclaration = true;
11809 break;
11811 case Ovl_NonFunction:
11812 Redeclaration = true;
11813 break;
11815 case Ovl_Overload:
11816 Redeclaration = false;
11817 break;
11822 // Check for a previous extern "C" declaration with this name.
11823 if (!Redeclaration &&
11824 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11825 if (!Previous.empty()) {
11826 // This is an extern "C" declaration with the same name as a previous
11827 // declaration, and thus redeclares that entity...
11828 Redeclaration = true;
11829 OldDecl = Previous.getFoundDecl();
11830 MergeTypeWithPrevious = false;
11832 // ... except in the presence of __attribute__((overloadable)).
11833 if (OldDecl->hasAttr<OverloadableAttr>() ||
11834 NewFD->hasAttr<OverloadableAttr>()) {
11835 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11836 MayNeedOverloadableChecks = true;
11837 Redeclaration = false;
11838 OldDecl = nullptr;
11844 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11845 return Redeclaration;
11847 // PPC MMA non-pointer types are not allowed as function return types.
11848 if (Context.getTargetInfo().getTriple().isPPC64() &&
11849 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11850 NewFD->setInvalidDecl();
11853 // C++11 [dcl.constexpr]p8:
11854 // A constexpr specifier for a non-static member function that is not
11855 // a constructor declares that member function to be const.
11857 // This needs to be delayed until we know whether this is an out-of-line
11858 // definition of a static member function.
11860 // This rule is not present in C++1y, so we produce a backwards
11861 // compatibility warning whenever it happens in C++11.
11862 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11863 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11864 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11865 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11866 CXXMethodDecl *OldMD = nullptr;
11867 if (OldDecl)
11868 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11869 if (!OldMD || !OldMD->isStatic()) {
11870 const FunctionProtoType *FPT =
11871 MD->getType()->castAs<FunctionProtoType>();
11872 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11873 EPI.TypeQuals.addConst();
11874 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11875 FPT->getParamTypes(), EPI));
11877 // Warn that we did this, if we're not performing template instantiation.
11878 // In that case, we'll have warned already when the template was defined.
11879 if (!inTemplateInstantiation()) {
11880 SourceLocation AddConstLoc;
11881 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11882 .IgnoreParens().getAs<FunctionTypeLoc>())
11883 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11885 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11886 << FixItHint::CreateInsertion(AddConstLoc, " const");
11891 if (Redeclaration) {
11892 // NewFD and OldDecl represent declarations that need to be
11893 // merged.
11894 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11895 DeclIsDefn)) {
11896 NewFD->setInvalidDecl();
11897 return Redeclaration;
11900 Previous.clear();
11901 Previous.addDecl(OldDecl);
11903 if (FunctionTemplateDecl *OldTemplateDecl =
11904 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11905 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11906 FunctionTemplateDecl *NewTemplateDecl
11907 = NewFD->getDescribedFunctionTemplate();
11908 assert(NewTemplateDecl && "Template/non-template mismatch");
11910 // The call to MergeFunctionDecl above may have created some state in
11911 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11912 // can add it as a redeclaration.
11913 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11915 NewFD->setPreviousDeclaration(OldFD);
11916 if (NewFD->isCXXClassMember()) {
11917 NewFD->setAccess(OldTemplateDecl->getAccess());
11918 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11921 // If this is an explicit specialization of a member that is a function
11922 // template, mark it as a member specialization.
11923 if (IsMemberSpecialization &&
11924 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11925 NewTemplateDecl->setMemberSpecialization();
11926 assert(OldTemplateDecl->isMemberSpecialization());
11927 // Explicit specializations of a member template do not inherit deleted
11928 // status from the parent member template that they are specializing.
11929 if (OldFD->isDeleted()) {
11930 // FIXME: This assert will not hold in the presence of modules.
11931 assert(OldFD->getCanonicalDecl() == OldFD);
11932 // FIXME: We need an update record for this AST mutation.
11933 OldFD->setDeletedAsWritten(false);
11937 } else {
11938 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11939 auto *OldFD = cast<FunctionDecl>(OldDecl);
11940 // This needs to happen first so that 'inline' propagates.
11941 NewFD->setPreviousDeclaration(OldFD);
11942 if (NewFD->isCXXClassMember())
11943 NewFD->setAccess(OldFD->getAccess());
11946 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11947 !NewFD->getAttr<OverloadableAttr>()) {
11948 assert((Previous.empty() ||
11949 llvm::any_of(Previous,
11950 [](const NamedDecl *ND) {
11951 return ND->hasAttr<OverloadableAttr>();
11952 })) &&
11953 "Non-redecls shouldn't happen without overloadable present");
11955 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11956 const auto *FD = dyn_cast<FunctionDecl>(ND);
11957 return FD && !FD->hasAttr<OverloadableAttr>();
11960 if (OtherUnmarkedIter != Previous.end()) {
11961 Diag(NewFD->getLocation(),
11962 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11963 Diag((*OtherUnmarkedIter)->getLocation(),
11964 diag::note_attribute_overloadable_prev_overload)
11965 << false;
11967 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11971 if (LangOpts.OpenMP)
11972 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11974 // Semantic checking for this function declaration (in isolation).
11976 if (getLangOpts().CPlusPlus) {
11977 // C++-specific checks.
11978 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11979 CheckConstructor(Constructor);
11980 } else if (CXXDestructorDecl *Destructor =
11981 dyn_cast<CXXDestructorDecl>(NewFD)) {
11982 // We check here for invalid destructor names.
11983 // If we have a friend destructor declaration that is dependent, we can't
11984 // diagnose right away because cases like this are still valid:
11985 // template <class T> struct A { friend T::X::~Y(); };
11986 // struct B { struct Y { ~Y(); }; using X = Y; };
11987 // template struct A<B>;
11988 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11989 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
11990 CXXRecordDecl *Record = Destructor->getParent();
11991 QualType ClassType = Context.getTypeDeclType(Record);
11993 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11994 Context.getCanonicalType(ClassType));
11995 if (NewFD->getDeclName() != Name) {
11996 Diag(NewFD->getLocation(), diag::err_destructor_name);
11997 NewFD->setInvalidDecl();
11998 return Redeclaration;
12001 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12002 if (auto *TD = Guide->getDescribedFunctionTemplate())
12003 CheckDeductionGuideTemplate(TD);
12005 // A deduction guide is not on the list of entities that can be
12006 // explicitly specialized.
12007 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12008 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12009 << /*explicit specialization*/ 1;
12012 // Find any virtual functions that this function overrides.
12013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12014 if (!Method->isFunctionTemplateSpecialization() &&
12015 !Method->getDescribedFunctionTemplate() &&
12016 Method->isCanonicalDecl()) {
12017 AddOverriddenMethods(Method->getParent(), Method);
12019 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12020 // C++2a [class.virtual]p6
12021 // A virtual method shall not have a requires-clause.
12022 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12023 diag::err_constrained_virtual_method);
12025 if (Method->isStatic())
12026 checkThisInStaticMemberFunctionType(Method);
12029 // C++20: dcl.decl.general p4:
12030 // The optional requires-clause ([temp.pre]) in an init-declarator or
12031 // member-declarator shall be present only if the declarator declares a
12032 // templated function ([dcl.fct]).
12033 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
12034 // [temp.pre]/8:
12035 // An entity is templated if it is
12036 // - a template,
12037 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12038 // templated entity,
12039 // - a member of a templated entity,
12040 // - an enumerator for an enumeration that is a templated entity, or
12041 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12042 // appearing in the declaration of a templated entity. [Note 6: A local
12043 // class, a local or block variable, or a friend function defined in a
12044 // templated entity is a templated entity. — end note]
12046 // A templated function is a function template or a function that is
12047 // templated. A templated class is a class template or a class that is
12048 // templated. A templated variable is a variable template or a variable
12049 // that is templated.
12051 if (!NewFD->getDescribedFunctionTemplate() && // -a template
12052 // defined... in a templated entity
12053 !(DeclIsDefn && NewFD->isTemplated()) &&
12054 // a member of a templated entity
12055 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
12056 // Don't complain about instantiations, they've already had these
12057 // rules + others enforced.
12058 !NewFD->isTemplateInstantiation()) {
12059 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
12063 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12064 ActOnConversionDeclarator(Conversion);
12066 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12067 if (NewFD->isOverloadedOperator() &&
12068 CheckOverloadedOperatorDeclaration(NewFD)) {
12069 NewFD->setInvalidDecl();
12070 return Redeclaration;
12073 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12074 if (NewFD->getLiteralIdentifier() &&
12075 CheckLiteralOperatorDeclaration(NewFD)) {
12076 NewFD->setInvalidDecl();
12077 return Redeclaration;
12080 // In C++, check default arguments now that we have merged decls. Unless
12081 // the lexical context is the class, because in this case this is done
12082 // during delayed parsing anyway.
12083 if (!CurContext->isRecord())
12084 CheckCXXDefaultArguments(NewFD);
12086 // If this function is declared as being extern "C", then check to see if
12087 // the function returns a UDT (class, struct, or union type) that is not C
12088 // compatible, and if it does, warn the user.
12089 // But, issue any diagnostic on the first declaration only.
12090 if (Previous.empty() && NewFD->isExternC()) {
12091 QualType R = NewFD->getReturnType();
12092 if (R->isIncompleteType() && !R->isVoidType())
12093 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12094 << NewFD << R;
12095 else if (!R.isPODType(Context) && !R->isVoidType() &&
12096 !R->isObjCObjectPointerType())
12097 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12100 // C++1z [dcl.fct]p6:
12101 // [...] whether the function has a non-throwing exception-specification
12102 // [is] part of the function type
12104 // This results in an ABI break between C++14 and C++17 for functions whose
12105 // declared type includes an exception-specification in a parameter or
12106 // return type. (Exception specifications on the function itself are OK in
12107 // most cases, and exception specifications are not permitted in most other
12108 // contexts where they could make it into a mangling.)
12109 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12110 auto HasNoexcept = [&](QualType T) -> bool {
12111 // Strip off declarator chunks that could be between us and a function
12112 // type. We don't need to look far, exception specifications are very
12113 // restricted prior to C++17.
12114 if (auto *RT = T->getAs<ReferenceType>())
12115 T = RT->getPointeeType();
12116 else if (T->isAnyPointerType())
12117 T = T->getPointeeType();
12118 else if (auto *MPT = T->getAs<MemberPointerType>())
12119 T = MPT->getPointeeType();
12120 if (auto *FPT = T->getAs<FunctionProtoType>())
12121 if (FPT->isNothrow())
12122 return true;
12123 return false;
12126 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12127 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12128 for (QualType T : FPT->param_types())
12129 AnyNoexcept |= HasNoexcept(T);
12130 if (AnyNoexcept)
12131 Diag(NewFD->getLocation(),
12132 diag::warn_cxx17_compat_exception_spec_in_signature)
12133 << NewFD;
12136 if (!Redeclaration && LangOpts.CUDA)
12137 checkCUDATargetOverload(NewFD, Previous);
12140 // Check if the function definition uses any AArch64 SME features without
12141 // having the '+sme' feature enabled.
12142 if (DeclIsDefn) {
12143 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12144 bool UsesZA = NewFD->hasAttr<ArmNewZAAttr>();
12145 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12146 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12147 UsesSM |=
12148 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12149 UsesZA |= EPI.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask;
12152 if (UsesSM || UsesZA) {
12153 llvm::StringMap<bool> FeatureMap;
12154 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12155 if (!FeatureMap.contains("sme")) {
12156 if (UsesSM)
12157 Diag(NewFD->getLocation(),
12158 diag::err_sme_definition_using_sm_in_non_sme_target);
12159 else
12160 Diag(NewFD->getLocation(),
12161 diag::err_sme_definition_using_za_in_non_sme_target);
12166 return Redeclaration;
12169 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12170 // C++11 [basic.start.main]p3:
12171 // A program that [...] declares main to be inline, static or
12172 // constexpr is ill-formed.
12173 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12174 // appear in a declaration of main.
12175 // static main is not an error under C99, but we should warn about it.
12176 // We accept _Noreturn main as an extension.
12177 if (FD->getStorageClass() == SC_Static)
12178 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12179 ? diag::err_static_main : diag::warn_static_main)
12180 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12181 if (FD->isInlineSpecified())
12182 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12183 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12184 if (DS.isNoreturnSpecified()) {
12185 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12186 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12187 Diag(NoreturnLoc, diag::ext_noreturn_main);
12188 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12189 << FixItHint::CreateRemoval(NoreturnRange);
12191 if (FD->isConstexpr()) {
12192 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12193 << FD->isConsteval()
12194 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12195 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12198 if (getLangOpts().OpenCL) {
12199 Diag(FD->getLocation(), diag::err_opencl_no_main)
12200 << FD->hasAttr<OpenCLKernelAttr>();
12201 FD->setInvalidDecl();
12202 return;
12205 // Functions named main in hlsl are default entries, but don't have specific
12206 // signatures they are required to conform to.
12207 if (getLangOpts().HLSL)
12208 return;
12210 QualType T = FD->getType();
12211 assert(T->isFunctionType() && "function decl is not of function type");
12212 const FunctionType* FT = T->castAs<FunctionType>();
12214 // Set default calling convention for main()
12215 if (FT->getCallConv() != CC_C) {
12216 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12217 FD->setType(QualType(FT, 0));
12218 T = Context.getCanonicalType(FD->getType());
12221 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12222 // In C with GNU extensions we allow main() to have non-integer return
12223 // type, but we should warn about the extension, and we disable the
12224 // implicit-return-zero rule.
12226 // GCC in C mode accepts qualified 'int'.
12227 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12228 FD->setHasImplicitReturnZero(true);
12229 else {
12230 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12231 SourceRange RTRange = FD->getReturnTypeSourceRange();
12232 if (RTRange.isValid())
12233 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12234 << FixItHint::CreateReplacement(RTRange, "int");
12236 } else {
12237 // In C and C++, main magically returns 0 if you fall off the end;
12238 // set the flag which tells us that.
12239 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12241 // All the standards say that main() should return 'int'.
12242 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12243 FD->setHasImplicitReturnZero(true);
12244 else {
12245 // Otherwise, this is just a flat-out error.
12246 SourceRange RTRange = FD->getReturnTypeSourceRange();
12247 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12248 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12249 : FixItHint());
12250 FD->setInvalidDecl(true);
12254 // Treat protoless main() as nullary.
12255 if (isa<FunctionNoProtoType>(FT)) return;
12257 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12258 unsigned nparams = FTP->getNumParams();
12259 assert(FD->getNumParams() == nparams);
12261 bool HasExtraParameters = (nparams > 3);
12263 if (FTP->isVariadic()) {
12264 Diag(FD->getLocation(), diag::ext_variadic_main);
12265 // FIXME: if we had information about the location of the ellipsis, we
12266 // could add a FixIt hint to remove it as a parameter.
12269 // Darwin passes an undocumented fourth argument of type char**. If
12270 // other platforms start sprouting these, the logic below will start
12271 // getting shifty.
12272 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12273 HasExtraParameters = false;
12275 if (HasExtraParameters) {
12276 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12277 FD->setInvalidDecl(true);
12278 nparams = 3;
12281 // FIXME: a lot of the following diagnostics would be improved
12282 // if we had some location information about types.
12284 QualType CharPP =
12285 Context.getPointerType(Context.getPointerType(Context.CharTy));
12286 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12288 for (unsigned i = 0; i < nparams; ++i) {
12289 QualType AT = FTP->getParamType(i);
12291 bool mismatch = true;
12293 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12294 mismatch = false;
12295 else if (Expected[i] == CharPP) {
12296 // As an extension, the following forms are okay:
12297 // char const **
12298 // char const * const *
12299 // char * const *
12301 QualifierCollector qs;
12302 const PointerType* PT;
12303 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12304 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12305 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12306 Context.CharTy)) {
12307 qs.removeConst();
12308 mismatch = !qs.empty();
12312 if (mismatch) {
12313 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12314 // TODO: suggest replacing given type with expected type
12315 FD->setInvalidDecl(true);
12319 if (nparams == 1 && !FD->isInvalidDecl()) {
12320 Diag(FD->getLocation(), diag::warn_main_one_arg);
12323 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12324 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12325 FD->setInvalidDecl();
12329 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12331 // Default calling convention for main and wmain is __cdecl
12332 if (FD->getName() == "main" || FD->getName() == "wmain")
12333 return false;
12335 // Default calling convention for MinGW is __cdecl
12336 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12337 if (T.isWindowsGNUEnvironment())
12338 return false;
12340 // Default calling convention for WinMain, wWinMain and DllMain
12341 // is __stdcall on 32 bit Windows
12342 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12343 return true;
12345 return false;
12348 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12349 QualType T = FD->getType();
12350 assert(T->isFunctionType() && "function decl is not of function type");
12351 const FunctionType *FT = T->castAs<FunctionType>();
12353 // Set an implicit return of 'zero' if the function can return some integral,
12354 // enumeration, pointer or nullptr type.
12355 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12356 FT->getReturnType()->isAnyPointerType() ||
12357 FT->getReturnType()->isNullPtrType())
12358 // DllMain is exempt because a return value of zero means it failed.
12359 if (FD->getName() != "DllMain")
12360 FD->setHasImplicitReturnZero(true);
12362 // Explicity specified calling conventions are applied to MSVC entry points
12363 if (!hasExplicitCallingConv(T)) {
12364 if (isDefaultStdCall(FD, *this)) {
12365 if (FT->getCallConv() != CC_X86StdCall) {
12366 FT = Context.adjustFunctionType(
12367 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12368 FD->setType(QualType(FT, 0));
12370 } else if (FT->getCallConv() != CC_C) {
12371 FT = Context.adjustFunctionType(FT,
12372 FT->getExtInfo().withCallingConv(CC_C));
12373 FD->setType(QualType(FT, 0));
12377 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12378 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12379 FD->setInvalidDecl();
12383 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) {
12384 auto &TargetInfo = getASTContext().getTargetInfo();
12386 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
12387 return;
12389 StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12390 HLSLShaderAttr::ShaderType ShaderType;
12391 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12392 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12393 // The entry point is already annotated - check that it matches the
12394 // triple.
12395 if (Shader->getType() != ShaderType) {
12396 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12397 << Shader;
12398 FD->setInvalidDecl();
12400 } else {
12401 // Implicitly add the shader attribute if the entry function isn't
12402 // explicitly annotated.
12403 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12404 FD->getBeginLoc()));
12406 } else {
12407 switch (TargetInfo.getTriple().getEnvironment()) {
12408 case llvm::Triple::UnknownEnvironment:
12409 case llvm::Triple::Library:
12410 break;
12411 default:
12412 llvm_unreachable("Unhandled environment in triple");
12417 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12418 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12419 assert(ShaderAttr && "Entry point has no shader attribute");
12420 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12422 switch (ST) {
12423 case HLSLShaderAttr::Pixel:
12424 case HLSLShaderAttr::Vertex:
12425 case HLSLShaderAttr::Geometry:
12426 case HLSLShaderAttr::Hull:
12427 case HLSLShaderAttr::Domain:
12428 case HLSLShaderAttr::RayGeneration:
12429 case HLSLShaderAttr::Intersection:
12430 case HLSLShaderAttr::AnyHit:
12431 case HLSLShaderAttr::ClosestHit:
12432 case HLSLShaderAttr::Miss:
12433 case HLSLShaderAttr::Callable:
12434 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12435 DiagnoseHLSLAttrStageMismatch(NT, ST,
12436 {HLSLShaderAttr::Compute,
12437 HLSLShaderAttr::Amplification,
12438 HLSLShaderAttr::Mesh});
12439 FD->setInvalidDecl();
12441 break;
12443 case HLSLShaderAttr::Compute:
12444 case HLSLShaderAttr::Amplification:
12445 case HLSLShaderAttr::Mesh:
12446 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12447 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12448 << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12449 FD->setInvalidDecl();
12451 break;
12454 for (ParmVarDecl *Param : FD->parameters()) {
12455 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12456 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr);
12457 } else {
12458 // FIXME: Handle struct parameters where annotations are on struct fields.
12459 // See: https://github.com/llvm/llvm-project/issues/57875
12460 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12461 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12462 FD->setInvalidDecl();
12465 // FIXME: Verify return type semantic annotation.
12468 void Sema::CheckHLSLSemanticAnnotation(
12469 FunctionDecl *EntryPoint, const Decl *Param,
12470 const HLSLAnnotationAttr *AnnotationAttr) {
12471 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12472 assert(ShaderAttr && "Entry point has no shader attribute");
12473 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12475 switch (AnnotationAttr->getKind()) {
12476 case attr::HLSLSV_DispatchThreadID:
12477 case attr::HLSLSV_GroupIndex:
12478 if (ST == HLSLShaderAttr::Compute)
12479 return;
12480 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12481 {HLSLShaderAttr::Compute});
12482 break;
12483 default:
12484 llvm_unreachable("Unknown HLSLAnnotationAttr");
12488 void Sema::DiagnoseHLSLAttrStageMismatch(
12489 const Attr *A, HLSLShaderAttr::ShaderType Stage,
12490 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12491 SmallVector<StringRef, 8> StageStrings;
12492 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
12493 [](HLSLShaderAttr::ShaderType ST) {
12494 return StringRef(
12495 HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12497 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12498 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12499 << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12502 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12503 // FIXME: Need strict checking. In C89, we need to check for
12504 // any assignment, increment, decrement, function-calls, or
12505 // commas outside of a sizeof. In C99, it's the same list,
12506 // except that the aforementioned are allowed in unevaluated
12507 // expressions. Everything else falls under the
12508 // "may accept other forms of constant expressions" exception.
12510 // Regular C++ code will not end up here (exceptions: language extensions,
12511 // OpenCL C++ etc), so the constant expression rules there don't matter.
12512 if (Init->isValueDependent()) {
12513 assert(Init->containsErrors() &&
12514 "Dependent code should only occur in error-recovery path.");
12515 return true;
12517 const Expr *Culprit;
12518 if (Init->isConstantInitializer(Context, false, &Culprit))
12519 return false;
12520 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12521 << Culprit->getSourceRange();
12522 return true;
12525 namespace {
12526 // Visits an initialization expression to see if OrigDecl is evaluated in
12527 // its own initialization and throws a warning if it does.
12528 class SelfReferenceChecker
12529 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12530 Sema &S;
12531 Decl *OrigDecl;
12532 bool isRecordType;
12533 bool isPODType;
12534 bool isReferenceType;
12536 bool isInitList;
12537 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12539 public:
12540 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12542 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12543 S(S), OrigDecl(OrigDecl) {
12544 isPODType = false;
12545 isRecordType = false;
12546 isReferenceType = false;
12547 isInitList = false;
12548 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12549 isPODType = VD->getType().isPODType(S.Context);
12550 isRecordType = VD->getType()->isRecordType();
12551 isReferenceType = VD->getType()->isReferenceType();
12555 // For most expressions, just call the visitor. For initializer lists,
12556 // track the index of the field being initialized since fields are
12557 // initialized in order allowing use of previously initialized fields.
12558 void CheckExpr(Expr *E) {
12559 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12560 if (!InitList) {
12561 Visit(E);
12562 return;
12565 // Track and increment the index here.
12566 isInitList = true;
12567 InitFieldIndex.push_back(0);
12568 for (auto *Child : InitList->children()) {
12569 CheckExpr(cast<Expr>(Child));
12570 ++InitFieldIndex.back();
12572 InitFieldIndex.pop_back();
12575 // Returns true if MemberExpr is checked and no further checking is needed.
12576 // Returns false if additional checking is required.
12577 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12578 llvm::SmallVector<FieldDecl*, 4> Fields;
12579 Expr *Base = E;
12580 bool ReferenceField = false;
12582 // Get the field members used.
12583 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12584 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12585 if (!FD)
12586 return false;
12587 Fields.push_back(FD);
12588 if (FD->getType()->isReferenceType())
12589 ReferenceField = true;
12590 Base = ME->getBase()->IgnoreParenImpCasts();
12593 // Keep checking only if the base Decl is the same.
12594 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12595 if (!DRE || DRE->getDecl() != OrigDecl)
12596 return false;
12598 // A reference field can be bound to an unininitialized field.
12599 if (CheckReference && !ReferenceField)
12600 return true;
12602 // Convert FieldDecls to their index number.
12603 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12604 for (const FieldDecl *I : llvm::reverse(Fields))
12605 UsedFieldIndex.push_back(I->getFieldIndex());
12607 // See if a warning is needed by checking the first difference in index
12608 // numbers. If field being used has index less than the field being
12609 // initialized, then the use is safe.
12610 for (auto UsedIter = UsedFieldIndex.begin(),
12611 UsedEnd = UsedFieldIndex.end(),
12612 OrigIter = InitFieldIndex.begin(),
12613 OrigEnd = InitFieldIndex.end();
12614 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12615 if (*UsedIter < *OrigIter)
12616 return true;
12617 if (*UsedIter > *OrigIter)
12618 break;
12621 // TODO: Add a different warning which will print the field names.
12622 HandleDeclRefExpr(DRE);
12623 return true;
12626 // For most expressions, the cast is directly above the DeclRefExpr.
12627 // For conditional operators, the cast can be outside the conditional
12628 // operator if both expressions are DeclRefExpr's.
12629 void HandleValue(Expr *E) {
12630 E = E->IgnoreParens();
12631 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12632 HandleDeclRefExpr(DRE);
12633 return;
12636 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12637 Visit(CO->getCond());
12638 HandleValue(CO->getTrueExpr());
12639 HandleValue(CO->getFalseExpr());
12640 return;
12643 if (BinaryConditionalOperator *BCO =
12644 dyn_cast<BinaryConditionalOperator>(E)) {
12645 Visit(BCO->getCond());
12646 HandleValue(BCO->getFalseExpr());
12647 return;
12650 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12651 HandleValue(OVE->getSourceExpr());
12652 return;
12655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12656 if (BO->getOpcode() == BO_Comma) {
12657 Visit(BO->getLHS());
12658 HandleValue(BO->getRHS());
12659 return;
12663 if (isa<MemberExpr>(E)) {
12664 if (isInitList) {
12665 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12666 false /*CheckReference*/))
12667 return;
12670 Expr *Base = E->IgnoreParenImpCasts();
12671 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12672 // Check for static member variables and don't warn on them.
12673 if (!isa<FieldDecl>(ME->getMemberDecl()))
12674 return;
12675 Base = ME->getBase()->IgnoreParenImpCasts();
12677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12678 HandleDeclRefExpr(DRE);
12679 return;
12682 Visit(E);
12685 // Reference types not handled in HandleValue are handled here since all
12686 // uses of references are bad, not just r-value uses.
12687 void VisitDeclRefExpr(DeclRefExpr *E) {
12688 if (isReferenceType)
12689 HandleDeclRefExpr(E);
12692 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12693 if (E->getCastKind() == CK_LValueToRValue) {
12694 HandleValue(E->getSubExpr());
12695 return;
12698 Inherited::VisitImplicitCastExpr(E);
12701 void VisitMemberExpr(MemberExpr *E) {
12702 if (isInitList) {
12703 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12704 return;
12707 // Don't warn on arrays since they can be treated as pointers.
12708 if (E->getType()->canDecayToPointerType()) return;
12710 // Warn when a non-static method call is followed by non-static member
12711 // field accesses, which is followed by a DeclRefExpr.
12712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12713 bool Warn = (MD && !MD->isStatic());
12714 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12715 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12716 if (!isa<FieldDecl>(ME->getMemberDecl()))
12717 Warn = false;
12718 Base = ME->getBase()->IgnoreParenImpCasts();
12721 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12722 if (Warn)
12723 HandleDeclRefExpr(DRE);
12724 return;
12727 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12728 // Visit that expression.
12729 Visit(Base);
12732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12733 Expr *Callee = E->getCallee();
12735 if (isa<UnresolvedLookupExpr>(Callee))
12736 return Inherited::VisitCXXOperatorCallExpr(E);
12738 Visit(Callee);
12739 for (auto Arg: E->arguments())
12740 HandleValue(Arg->IgnoreParenImpCasts());
12743 void VisitUnaryOperator(UnaryOperator *E) {
12744 // For POD record types, addresses of its own members are well-defined.
12745 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12746 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12747 if (!isPODType)
12748 HandleValue(E->getSubExpr());
12749 return;
12752 if (E->isIncrementDecrementOp()) {
12753 HandleValue(E->getSubExpr());
12754 return;
12757 Inherited::VisitUnaryOperator(E);
12760 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12762 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12763 if (E->getConstructor()->isCopyConstructor()) {
12764 Expr *ArgExpr = E->getArg(0);
12765 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12766 if (ILE->getNumInits() == 1)
12767 ArgExpr = ILE->getInit(0);
12768 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12769 if (ICE->getCastKind() == CK_NoOp)
12770 ArgExpr = ICE->getSubExpr();
12771 HandleValue(ArgExpr);
12772 return;
12774 Inherited::VisitCXXConstructExpr(E);
12777 void VisitCallExpr(CallExpr *E) {
12778 // Treat std::move as a use.
12779 if (E->isCallToStdMove()) {
12780 HandleValue(E->getArg(0));
12781 return;
12784 Inherited::VisitCallExpr(E);
12787 void VisitBinaryOperator(BinaryOperator *E) {
12788 if (E->isCompoundAssignmentOp()) {
12789 HandleValue(E->getLHS());
12790 Visit(E->getRHS());
12791 return;
12794 Inherited::VisitBinaryOperator(E);
12797 // A custom visitor for BinaryConditionalOperator is needed because the
12798 // regular visitor would check the condition and true expression separately
12799 // but both point to the same place giving duplicate diagnostics.
12800 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12801 Visit(E->getCond());
12802 Visit(E->getFalseExpr());
12805 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12806 Decl* ReferenceDecl = DRE->getDecl();
12807 if (OrigDecl != ReferenceDecl) return;
12808 unsigned diag;
12809 if (isReferenceType) {
12810 diag = diag::warn_uninit_self_reference_in_reference_init;
12811 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12812 diag = diag::warn_static_self_reference_in_init;
12813 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12814 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12815 DRE->getDecl()->getType()->isRecordType()) {
12816 diag = diag::warn_uninit_self_reference_in_init;
12817 } else {
12818 // Local variables will be handled by the CFG analysis.
12819 return;
12822 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12823 S.PDiag(diag)
12824 << DRE->getDecl() << OrigDecl->getLocation()
12825 << DRE->getSourceRange());
12829 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12830 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12831 bool DirectInit) {
12832 // Parameters arguments are occassionially constructed with itself,
12833 // for instance, in recursive functions. Skip them.
12834 if (isa<ParmVarDecl>(OrigDecl))
12835 return;
12837 E = E->IgnoreParens();
12839 // Skip checking T a = a where T is not a record or reference type.
12840 // Doing so is a way to silence uninitialized warnings.
12841 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12842 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12843 if (ICE->getCastKind() == CK_LValueToRValue)
12844 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12845 if (DRE->getDecl() == OrigDecl)
12846 return;
12848 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12850 } // end anonymous namespace
12852 namespace {
12853 // Simple wrapper to add the name of a variable or (if no variable is
12854 // available) a DeclarationName into a diagnostic.
12855 struct VarDeclOrName {
12856 VarDecl *VDecl;
12857 DeclarationName Name;
12859 friend const Sema::SemaDiagnosticBuilder &
12860 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12861 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12864 } // end anonymous namespace
12866 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12867 DeclarationName Name, QualType Type,
12868 TypeSourceInfo *TSI,
12869 SourceRange Range, bool DirectInit,
12870 Expr *Init) {
12871 bool IsInitCapture = !VDecl;
12872 assert((!VDecl || !VDecl->isInitCapture()) &&
12873 "init captures are expected to be deduced prior to initialization");
12875 VarDeclOrName VN{VDecl, Name};
12877 DeducedType *Deduced = Type->getContainedDeducedType();
12878 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12880 // Diagnose auto array declarations in C23, unless it's a supported extension.
12881 if (getLangOpts().C23 && Type->isArrayType() &&
12882 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12883 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12884 << (int)Deduced->getContainedAutoType()->getKeyword()
12885 << /*in array decl*/ 23 << Range;
12886 return QualType();
12889 // C++11 [dcl.spec.auto]p3
12890 if (!Init) {
12891 assert(VDecl && "no init for init capture deduction?");
12893 // Except for class argument deduction, and then for an initializing
12894 // declaration only, i.e. no static at class scope or extern.
12895 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12896 VDecl->hasExternalStorage() ||
12897 VDecl->isStaticDataMember()) {
12898 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12899 << VDecl->getDeclName() << Type;
12900 return QualType();
12904 ArrayRef<Expr*> DeduceInits;
12905 if (Init)
12906 DeduceInits = Init;
12908 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12909 if (DirectInit && PL)
12910 DeduceInits = PL->exprs();
12912 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12913 assert(VDecl && "non-auto type for init capture deduction?");
12914 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12915 InitializationKind Kind = InitializationKind::CreateForInit(
12916 VDecl->getLocation(), DirectInit, Init);
12917 // FIXME: Initialization should not be taking a mutable list of inits.
12918 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12919 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12920 InitsCopy, PL);
12923 if (DirectInit) {
12924 if (auto *IL = dyn_cast<InitListExpr>(Init))
12925 DeduceInits = IL->inits();
12928 // Deduction only works if we have exactly one source expression.
12929 if (DeduceInits.empty()) {
12930 // It isn't possible to write this directly, but it is possible to
12931 // end up in this situation with "auto x(some_pack...);"
12932 Diag(Init->getBeginLoc(), IsInitCapture
12933 ? diag::err_init_capture_no_expression
12934 : diag::err_auto_var_init_no_expression)
12935 << VN << Type << Range;
12936 return QualType();
12939 if (DeduceInits.size() > 1) {
12940 Diag(DeduceInits[1]->getBeginLoc(),
12941 IsInitCapture ? diag::err_init_capture_multiple_expressions
12942 : diag::err_auto_var_init_multiple_expressions)
12943 << VN << Type << Range;
12944 return QualType();
12947 Expr *DeduceInit = DeduceInits[0];
12948 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12949 Diag(Init->getBeginLoc(), IsInitCapture
12950 ? diag::err_init_capture_paren_braces
12951 : diag::err_auto_var_init_paren_braces)
12952 << isa<InitListExpr>(Init) << VN << Type << Range;
12953 return QualType();
12956 // Expressions default to 'id' when we're in a debugger.
12957 bool DefaultedAnyToId = false;
12958 if (getLangOpts().DebuggerCastResultToId &&
12959 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12960 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12961 if (Result.isInvalid()) {
12962 return QualType();
12964 Init = Result.get();
12965 DefaultedAnyToId = true;
12968 // C++ [dcl.decomp]p1:
12969 // If the assignment-expression [...] has array type A and no ref-qualifier
12970 // is present, e has type cv A
12971 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12972 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12973 DeduceInit->getType()->isConstantArrayType())
12974 return Context.getQualifiedType(DeduceInit->getType(),
12975 Type.getQualifiers());
12977 QualType DeducedType;
12978 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12979 TemplateDeductionResult Result =
12980 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12981 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12982 if (!IsInitCapture)
12983 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12984 else if (isa<InitListExpr>(Init))
12985 Diag(Range.getBegin(),
12986 diag::err_init_capture_deduction_failure_from_init_list)
12987 << VN
12988 << (DeduceInit->getType().isNull() ? TSI->getType()
12989 : DeduceInit->getType())
12990 << DeduceInit->getSourceRange();
12991 else
12992 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12993 << VN << TSI->getType()
12994 << (DeduceInit->getType().isNull() ? TSI->getType()
12995 : DeduceInit->getType())
12996 << DeduceInit->getSourceRange();
12999 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13000 // 'id' instead of a specific object type prevents most of our usual
13001 // checks.
13002 // We only want to warn outside of template instantiations, though:
13003 // inside a template, the 'id' could have come from a parameter.
13004 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13005 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13006 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13007 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13010 return DeducedType;
13013 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13014 Expr *Init) {
13015 assert(!Init || !Init->containsErrors());
13016 QualType DeducedType = deduceVarTypeFromInitializer(
13017 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13018 VDecl->getSourceRange(), DirectInit, Init);
13019 if (DeducedType.isNull()) {
13020 VDecl->setInvalidDecl();
13021 return true;
13024 VDecl->setType(DeducedType);
13025 assert(VDecl->isLinkageValid());
13027 // In ARC, infer lifetime.
13028 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13029 VDecl->setInvalidDecl();
13031 if (getLangOpts().OpenCL)
13032 deduceOpenCLAddressSpace(VDecl);
13034 // If this is a redeclaration, check that the type we just deduced matches
13035 // the previously declared type.
13036 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13037 // We never need to merge the type, because we cannot form an incomplete
13038 // array of auto, nor deduce such a type.
13039 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13042 // Check the deduced type is valid for a variable declaration.
13043 CheckVariableDeclarationType(VDecl);
13044 return VDecl->isInvalidDecl();
13047 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13048 SourceLocation Loc) {
13049 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13050 Init = EWC->getSubExpr();
13052 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13053 Init = CE->getSubExpr();
13055 QualType InitType = Init->getType();
13056 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13057 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13058 "shouldn't be called if type doesn't have a non-trivial C struct");
13059 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13060 for (auto *I : ILE->inits()) {
13061 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13062 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13063 continue;
13064 SourceLocation SL = I->getExprLoc();
13065 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13067 return;
13070 if (isa<ImplicitValueInitExpr>(Init)) {
13071 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13072 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13073 NTCUK_Init);
13074 } else {
13075 // Assume all other explicit initializers involving copying some existing
13076 // object.
13077 // TODO: ignore any explicit initializers where we can guarantee
13078 // copy-elision.
13079 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13080 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13084 namespace {
13086 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13087 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13088 // in the source code or implicitly by the compiler if it is in a union
13089 // defined in a system header and has non-trivial ObjC ownership
13090 // qualifications. We don't want those fields to participate in determining
13091 // whether the containing union is non-trivial.
13092 return FD->hasAttr<UnavailableAttr>();
13095 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13096 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13097 void> {
13098 using Super =
13099 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13100 void>;
13102 DiagNonTrivalCUnionDefaultInitializeVisitor(
13103 QualType OrigTy, SourceLocation OrigLoc,
13104 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13105 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13107 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13108 const FieldDecl *FD, bool InNonTrivialUnion) {
13109 if (const auto *AT = S.Context.getAsArrayType(QT))
13110 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13111 InNonTrivialUnion);
13112 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13115 void visitARCStrong(QualType QT, const FieldDecl *FD,
13116 bool InNonTrivialUnion) {
13117 if (InNonTrivialUnion)
13118 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13119 << 1 << 0 << QT << FD->getName();
13122 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13123 if (InNonTrivialUnion)
13124 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13125 << 1 << 0 << QT << FD->getName();
13128 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13129 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13130 if (RD->isUnion()) {
13131 if (OrigLoc.isValid()) {
13132 bool IsUnion = false;
13133 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13134 IsUnion = OrigRD->isUnion();
13135 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13136 << 0 << OrigTy << IsUnion << UseContext;
13137 // Reset OrigLoc so that this diagnostic is emitted only once.
13138 OrigLoc = SourceLocation();
13140 InNonTrivialUnion = true;
13143 if (InNonTrivialUnion)
13144 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13145 << 0 << 0 << QT.getUnqualifiedType() << "";
13147 for (const FieldDecl *FD : RD->fields())
13148 if (!shouldIgnoreForRecordTriviality(FD))
13149 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13152 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13154 // The non-trivial C union type or the struct/union type that contains a
13155 // non-trivial C union.
13156 QualType OrigTy;
13157 SourceLocation OrigLoc;
13158 Sema::NonTrivialCUnionContext UseContext;
13159 Sema &S;
13162 struct DiagNonTrivalCUnionDestructedTypeVisitor
13163 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13164 using Super =
13165 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13167 DiagNonTrivalCUnionDestructedTypeVisitor(
13168 QualType OrigTy, SourceLocation OrigLoc,
13169 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13170 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13172 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13173 const FieldDecl *FD, bool InNonTrivialUnion) {
13174 if (const auto *AT = S.Context.getAsArrayType(QT))
13175 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13176 InNonTrivialUnion);
13177 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13180 void visitARCStrong(QualType QT, const FieldDecl *FD,
13181 bool InNonTrivialUnion) {
13182 if (InNonTrivialUnion)
13183 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13184 << 1 << 1 << QT << FD->getName();
13187 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13188 if (InNonTrivialUnion)
13189 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13190 << 1 << 1 << QT << FD->getName();
13193 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13194 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13195 if (RD->isUnion()) {
13196 if (OrigLoc.isValid()) {
13197 bool IsUnion = false;
13198 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13199 IsUnion = OrigRD->isUnion();
13200 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13201 << 1 << OrigTy << IsUnion << UseContext;
13202 // Reset OrigLoc so that this diagnostic is emitted only once.
13203 OrigLoc = SourceLocation();
13205 InNonTrivialUnion = true;
13208 if (InNonTrivialUnion)
13209 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13210 << 0 << 1 << QT.getUnqualifiedType() << "";
13212 for (const FieldDecl *FD : RD->fields())
13213 if (!shouldIgnoreForRecordTriviality(FD))
13214 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13217 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13218 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13219 bool InNonTrivialUnion) {}
13221 // The non-trivial C union type or the struct/union type that contains a
13222 // non-trivial C union.
13223 QualType OrigTy;
13224 SourceLocation OrigLoc;
13225 Sema::NonTrivialCUnionContext UseContext;
13226 Sema &S;
13229 struct DiagNonTrivalCUnionCopyVisitor
13230 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13231 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13233 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13234 Sema::NonTrivialCUnionContext UseContext,
13235 Sema &S)
13236 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13238 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13239 const FieldDecl *FD, bool InNonTrivialUnion) {
13240 if (const auto *AT = S.Context.getAsArrayType(QT))
13241 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13242 InNonTrivialUnion);
13243 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13246 void visitARCStrong(QualType QT, const FieldDecl *FD,
13247 bool InNonTrivialUnion) {
13248 if (InNonTrivialUnion)
13249 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13250 << 1 << 2 << QT << FD->getName();
13253 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13254 if (InNonTrivialUnion)
13255 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13256 << 1 << 2 << QT << FD->getName();
13259 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13260 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13261 if (RD->isUnion()) {
13262 if (OrigLoc.isValid()) {
13263 bool IsUnion = false;
13264 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13265 IsUnion = OrigRD->isUnion();
13266 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13267 << 2 << OrigTy << IsUnion << UseContext;
13268 // Reset OrigLoc so that this diagnostic is emitted only once.
13269 OrigLoc = SourceLocation();
13271 InNonTrivialUnion = true;
13274 if (InNonTrivialUnion)
13275 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13276 << 0 << 2 << QT.getUnqualifiedType() << "";
13278 for (const FieldDecl *FD : RD->fields())
13279 if (!shouldIgnoreForRecordTriviality(FD))
13280 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13283 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13284 const FieldDecl *FD, bool InNonTrivialUnion) {}
13285 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13286 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13287 bool InNonTrivialUnion) {}
13289 // The non-trivial C union type or the struct/union type that contains a
13290 // non-trivial C union.
13291 QualType OrigTy;
13292 SourceLocation OrigLoc;
13293 Sema::NonTrivialCUnionContext UseContext;
13294 Sema &S;
13297 } // namespace
13299 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13300 NonTrivialCUnionContext UseContext,
13301 unsigned NonTrivialKind) {
13302 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13303 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13304 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13305 "shouldn't be called if type doesn't have a non-trivial C union");
13307 if ((NonTrivialKind & NTCUK_Init) &&
13308 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13309 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13310 .visit(QT, nullptr, false);
13311 if ((NonTrivialKind & NTCUK_Destruct) &&
13312 QT.hasNonTrivialToPrimitiveDestructCUnion())
13313 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13314 .visit(QT, nullptr, false);
13315 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13316 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13317 .visit(QT, nullptr, false);
13320 /// AddInitializerToDecl - Adds the initializer Init to the
13321 /// declaration dcl. If DirectInit is true, this is C++ direct
13322 /// initialization rather than copy initialization.
13323 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13324 // If there is no declaration, there was an error parsing it. Just ignore
13325 // the initializer.
13326 if (!RealDecl || RealDecl->isInvalidDecl()) {
13327 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13328 return;
13331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13332 // Pure-specifiers are handled in ActOnPureSpecifier.
13333 Diag(Method->getLocation(), diag::err_member_function_initialization)
13334 << Method->getDeclName() << Init->getSourceRange();
13335 Method->setInvalidDecl();
13336 return;
13339 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13340 if (!VDecl) {
13341 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13342 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13343 RealDecl->setInvalidDecl();
13344 return;
13347 // WebAssembly tables can't be used to initialise a variable.
13348 if (Init && !Init->getType().isNull() &&
13349 Init->getType()->isWebAssemblyTableType()) {
13350 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13351 VDecl->setInvalidDecl();
13352 return;
13355 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13356 if (VDecl->getType()->isUndeducedType()) {
13357 // Attempt typo correction early so that the type of the init expression can
13358 // be deduced based on the chosen correction if the original init contains a
13359 // TypoExpr.
13360 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13361 if (!Res.isUsable()) {
13362 // There are unresolved typos in Init, just drop them.
13363 // FIXME: improve the recovery strategy to preserve the Init.
13364 RealDecl->setInvalidDecl();
13365 return;
13367 if (Res.get()->containsErrors()) {
13368 // Invalidate the decl as we don't know the type for recovery-expr yet.
13369 RealDecl->setInvalidDecl();
13370 VDecl->setInit(Res.get());
13371 return;
13373 Init = Res.get();
13375 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13376 return;
13379 // dllimport cannot be used on variable definitions.
13380 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13381 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13382 VDecl->setInvalidDecl();
13383 return;
13386 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13387 // the identifier has external or internal linkage, the declaration shall
13388 // have no initializer for the identifier.
13389 // C++14 [dcl.init]p5 is the same restriction for C++.
13390 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13391 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13392 VDecl->setInvalidDecl();
13393 return;
13396 if (!VDecl->getType()->isDependentType()) {
13397 // A definition must end up with a complete type, which means it must be
13398 // complete with the restriction that an array type might be completed by
13399 // the initializer; note that later code assumes this restriction.
13400 QualType BaseDeclType = VDecl->getType();
13401 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13402 BaseDeclType = Array->getElementType();
13403 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13404 diag::err_typecheck_decl_incomplete_type)) {
13405 RealDecl->setInvalidDecl();
13406 return;
13409 // The variable can not have an abstract class type.
13410 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13411 diag::err_abstract_type_in_decl,
13412 AbstractVariableType))
13413 VDecl->setInvalidDecl();
13416 // C++ [module.import/6] external definitions are not permitted in header
13417 // units.
13418 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13419 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13420 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13421 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13422 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13423 VDecl->setInvalidDecl();
13426 // If adding the initializer will turn this declaration into a definition,
13427 // and we already have a definition for this variable, diagnose or otherwise
13428 // handle the situation.
13429 if (VarDecl *Def = VDecl->getDefinition())
13430 if (Def != VDecl &&
13431 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13432 !VDecl->isThisDeclarationADemotedDefinition() &&
13433 checkVarDeclRedefinition(Def, VDecl))
13434 return;
13436 if (getLangOpts().CPlusPlus) {
13437 // C++ [class.static.data]p4
13438 // If a static data member is of const integral or const
13439 // enumeration type, its declaration in the class definition can
13440 // specify a constant-initializer which shall be an integral
13441 // constant expression (5.19). In that case, the member can appear
13442 // in integral constant expressions. The member shall still be
13443 // defined in a namespace scope if it is used in the program and the
13444 // namespace scope definition shall not contain an initializer.
13446 // We already performed a redefinition check above, but for static
13447 // data members we also need to check whether there was an in-class
13448 // declaration with an initializer.
13449 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13450 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13451 << VDecl->getDeclName();
13452 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13453 diag::note_previous_initializer)
13454 << 0;
13455 return;
13458 if (VDecl->hasLocalStorage())
13459 setFunctionHasBranchProtectedScope();
13461 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13462 VDecl->setInvalidDecl();
13463 return;
13467 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13468 // a kernel function cannot be initialized."
13469 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13470 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13471 VDecl->setInvalidDecl();
13472 return;
13475 // The LoaderUninitialized attribute acts as a definition (of undef).
13476 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13477 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13478 VDecl->setInvalidDecl();
13479 return;
13482 // Get the decls type and save a reference for later, since
13483 // CheckInitializerTypes may change it.
13484 QualType DclT = VDecl->getType(), SavT = DclT;
13486 // Expressions default to 'id' when we're in a debugger
13487 // and we are assigning it to a variable of Objective-C pointer type.
13488 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13489 Init->getType() == Context.UnknownAnyTy) {
13490 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13491 if (Result.isInvalid()) {
13492 VDecl->setInvalidDecl();
13493 return;
13495 Init = Result.get();
13498 // Perform the initialization.
13499 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13500 bool IsParenListInit = false;
13501 if (!VDecl->isInvalidDecl()) {
13502 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13503 InitializationKind Kind = InitializationKind::CreateForInit(
13504 VDecl->getLocation(), DirectInit, Init);
13506 MultiExprArg Args = Init;
13507 if (CXXDirectInit)
13508 Args = MultiExprArg(CXXDirectInit->getExprs(),
13509 CXXDirectInit->getNumExprs());
13511 // Try to correct any TypoExprs in the initialization arguments.
13512 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13513 ExprResult Res = CorrectDelayedTyposInExpr(
13514 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13515 [this, Entity, Kind](Expr *E) {
13516 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13517 return Init.Failed() ? ExprError() : E;
13519 if (Res.isInvalid()) {
13520 VDecl->setInvalidDecl();
13521 } else if (Res.get() != Args[Idx]) {
13522 Args[Idx] = Res.get();
13525 if (VDecl->isInvalidDecl())
13526 return;
13528 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13529 /*TopLevelOfInitList=*/false,
13530 /*TreatUnavailableAsInvalid=*/false);
13531 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13532 if (Result.isInvalid()) {
13533 // If the provided initializer fails to initialize the var decl,
13534 // we attach a recovery expr for better recovery.
13535 auto RecoveryExpr =
13536 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13537 if (RecoveryExpr.get())
13538 VDecl->setInit(RecoveryExpr.get());
13539 return;
13542 Init = Result.getAs<Expr>();
13543 IsParenListInit = !InitSeq.steps().empty() &&
13544 InitSeq.step_begin()->Kind ==
13545 InitializationSequence::SK_ParenthesizedListInit;
13546 QualType VDeclType = VDecl->getType();
13547 if (Init && !Init->getType().isNull() &&
13548 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13549 Context.getAsIncompleteArrayType(VDeclType) &&
13550 Context.getAsIncompleteArrayType(Init->getType())) {
13551 // Bail out if it is not possible to deduce array size from the
13552 // initializer.
13553 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13554 << VDeclType;
13555 VDecl->setInvalidDecl();
13556 return;
13560 // Check for self-references within variable initializers.
13561 // Variables declared within a function/method body (except for references)
13562 // are handled by a dataflow analysis.
13563 // This is undefined behavior in C++, but valid in C.
13564 if (getLangOpts().CPlusPlus)
13565 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13566 VDecl->getType()->isReferenceType())
13567 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13569 // If the type changed, it means we had an incomplete type that was
13570 // completed by the initializer. For example:
13571 // int ary[] = { 1, 3, 5 };
13572 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13573 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13574 VDecl->setType(DclT);
13576 if (!VDecl->isInvalidDecl()) {
13577 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13579 if (VDecl->hasAttr<BlocksAttr>())
13580 checkRetainCycles(VDecl, Init);
13582 // It is safe to assign a weak reference into a strong variable.
13583 // Although this code can still have problems:
13584 // id x = self.weakProp;
13585 // id y = self.weakProp;
13586 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13587 // paths through the function. This should be revisited if
13588 // -Wrepeated-use-of-weak is made flow-sensitive.
13589 if (FunctionScopeInfo *FSI = getCurFunction())
13590 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13591 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13592 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13593 Init->getBeginLoc()))
13594 FSI->markSafeWeakUse(Init);
13597 // The initialization is usually a full-expression.
13599 // FIXME: If this is a braced initialization of an aggregate, it is not
13600 // an expression, and each individual field initializer is a separate
13601 // full-expression. For instance, in:
13603 // struct Temp { ~Temp(); };
13604 // struct S { S(Temp); };
13605 // struct T { S a, b; } t = { Temp(), Temp() }
13607 // we should destroy the first Temp before constructing the second.
13608 ExprResult Result =
13609 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13610 /*DiscardedValue*/ false, VDecl->isConstexpr());
13611 if (Result.isInvalid()) {
13612 VDecl->setInvalidDecl();
13613 return;
13615 Init = Result.get();
13617 // Attach the initializer to the decl.
13618 VDecl->setInit(Init);
13620 if (VDecl->isLocalVarDecl()) {
13621 // Don't check the initializer if the declaration is malformed.
13622 if (VDecl->isInvalidDecl()) {
13623 // do nothing
13625 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13626 // This is true even in C++ for OpenCL.
13627 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13628 CheckForConstantInitializer(Init, DclT);
13630 // Otherwise, C++ does not restrict the initializer.
13631 } else if (getLangOpts().CPlusPlus) {
13632 // do nothing
13634 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13635 // static storage duration shall be constant expressions or string literals.
13636 } else if (VDecl->getStorageClass() == SC_Static) {
13637 CheckForConstantInitializer(Init, DclT);
13639 // C89 is stricter than C99 for aggregate initializers.
13640 // C89 6.5.7p3: All the expressions [...] in an initializer list
13641 // for an object that has aggregate or union type shall be
13642 // constant expressions.
13643 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13644 isa<InitListExpr>(Init)) {
13645 const Expr *Culprit;
13646 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13647 Diag(Culprit->getExprLoc(),
13648 diag::ext_aggregate_init_not_constant)
13649 << Culprit->getSourceRange();
13653 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13654 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13655 if (VDecl->hasLocalStorage())
13656 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13657 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13658 VDecl->getLexicalDeclContext()->isRecord()) {
13659 // This is an in-class initialization for a static data member, e.g.,
13661 // struct S {
13662 // static const int value = 17;
13663 // };
13665 // C++ [class.mem]p4:
13666 // A member-declarator can contain a constant-initializer only
13667 // if it declares a static member (9.4) of const integral or
13668 // const enumeration type, see 9.4.2.
13670 // C++11 [class.static.data]p3:
13671 // If a non-volatile non-inline const static data member is of integral
13672 // or enumeration type, its declaration in the class definition can
13673 // specify a brace-or-equal-initializer in which every initializer-clause
13674 // that is an assignment-expression is a constant expression. A static
13675 // data member of literal type can be declared in the class definition
13676 // with the constexpr specifier; if so, its declaration shall specify a
13677 // brace-or-equal-initializer in which every initializer-clause that is
13678 // an assignment-expression is a constant expression.
13680 // Do nothing on dependent types.
13681 if (DclT->isDependentType()) {
13683 // Allow any 'static constexpr' members, whether or not they are of literal
13684 // type. We separately check that every constexpr variable is of literal
13685 // type.
13686 } else if (VDecl->isConstexpr()) {
13688 // Require constness.
13689 } else if (!DclT.isConstQualified()) {
13690 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13691 << Init->getSourceRange();
13692 VDecl->setInvalidDecl();
13694 // We allow integer constant expressions in all cases.
13695 } else if (DclT->isIntegralOrEnumerationType()) {
13696 // Check whether the expression is a constant expression.
13697 SourceLocation Loc;
13698 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13699 // In C++11, a non-constexpr const static data member with an
13700 // in-class initializer cannot be volatile.
13701 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13702 else if (Init->isValueDependent())
13703 ; // Nothing to check.
13704 else if (Init->isIntegerConstantExpr(Context, &Loc))
13705 ; // Ok, it's an ICE!
13706 else if (Init->getType()->isScopedEnumeralType() &&
13707 Init->isCXX11ConstantExpr(Context))
13708 ; // Ok, it is a scoped-enum constant expression.
13709 else if (Init->isEvaluatable(Context)) {
13710 // If we can constant fold the initializer through heroics, accept it,
13711 // but report this as a use of an extension for -pedantic.
13712 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13713 << Init->getSourceRange();
13714 } else {
13715 // Otherwise, this is some crazy unknown case. Report the issue at the
13716 // location provided by the isIntegerConstantExpr failed check.
13717 Diag(Loc, diag::err_in_class_initializer_non_constant)
13718 << Init->getSourceRange();
13719 VDecl->setInvalidDecl();
13722 // We allow foldable floating-point constants as an extension.
13723 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13724 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13725 // it anyway and provide a fixit to add the 'constexpr'.
13726 if (getLangOpts().CPlusPlus11) {
13727 Diag(VDecl->getLocation(),
13728 diag::ext_in_class_initializer_float_type_cxx11)
13729 << DclT << Init->getSourceRange();
13730 Diag(VDecl->getBeginLoc(),
13731 diag::note_in_class_initializer_float_type_cxx11)
13732 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13733 } else {
13734 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13735 << DclT << Init->getSourceRange();
13737 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13738 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13739 << Init->getSourceRange();
13740 VDecl->setInvalidDecl();
13744 // Suggest adding 'constexpr' in C++11 for literal types.
13745 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13746 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13747 << DclT << Init->getSourceRange()
13748 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13749 VDecl->setConstexpr(true);
13751 } else {
13752 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13753 << DclT << Init->getSourceRange();
13754 VDecl->setInvalidDecl();
13756 } else if (VDecl->isFileVarDecl()) {
13757 // In C, extern is typically used to avoid tentative definitions when
13758 // declaring variables in headers, but adding an intializer makes it a
13759 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13760 // In C++, extern is often used to give implictly static const variables
13761 // external linkage, so don't warn in that case. If selectany is present,
13762 // this might be header code intended for C and C++ inclusion, so apply the
13763 // C++ rules.
13764 if (VDecl->getStorageClass() == SC_Extern &&
13765 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13766 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13767 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13768 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13769 Diag(VDecl->getLocation(), diag::warn_extern_init);
13771 // In Microsoft C++ mode, a const variable defined in namespace scope has
13772 // external linkage by default if the variable is declared with
13773 // __declspec(dllexport).
13774 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13775 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13776 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13777 VDecl->setStorageClass(SC_Extern);
13779 // C99 6.7.8p4. All file scoped initializers need to be constant.
13780 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13781 CheckForConstantInitializer(Init, DclT);
13784 QualType InitType = Init->getType();
13785 if (!InitType.isNull() &&
13786 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13787 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13788 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13790 // We will represent direct-initialization similarly to copy-initialization:
13791 // int x(1); -as-> int x = 1;
13792 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13794 // Clients that want to distinguish between the two forms, can check for
13795 // direct initializer using VarDecl::getInitStyle().
13796 // A major benefit is that clients that don't particularly care about which
13797 // exactly form was it (like the CodeGen) can handle both cases without
13798 // special case code.
13800 // C++ 8.5p11:
13801 // The form of initialization (using parentheses or '=') is generally
13802 // insignificant, but does matter when the entity being initialized has a
13803 // class type.
13804 if (CXXDirectInit) {
13805 assert(DirectInit && "Call-style initializer must be direct init.");
13806 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13807 : VarDecl::CallInit);
13808 } else if (DirectInit) {
13809 // This must be list-initialization. No other way is direct-initialization.
13810 VDecl->setInitStyle(VarDecl::ListInit);
13813 if (LangOpts.OpenMP &&
13814 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13815 VDecl->isFileVarDecl())
13816 DeclsToCheckForDeferredDiags.insert(VDecl);
13817 CheckCompleteVariableDeclaration(VDecl);
13820 /// ActOnInitializerError - Given that there was an error parsing an
13821 /// initializer for the given declaration, try to at least re-establish
13822 /// invariants such as whether a variable's type is either dependent or
13823 /// complete.
13824 void Sema::ActOnInitializerError(Decl *D) {
13825 // Our main concern here is re-establishing invariants like "a
13826 // variable's type is either dependent or complete".
13827 if (!D || D->isInvalidDecl()) return;
13829 VarDecl *VD = dyn_cast<VarDecl>(D);
13830 if (!VD) return;
13832 // Bindings are not usable if we can't make sense of the initializer.
13833 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13834 for (auto *BD : DD->bindings())
13835 BD->setInvalidDecl();
13837 // Auto types are meaningless if we can't make sense of the initializer.
13838 if (VD->getType()->isUndeducedType()) {
13839 D->setInvalidDecl();
13840 return;
13843 QualType Ty = VD->getType();
13844 if (Ty->isDependentType()) return;
13846 // Require a complete type.
13847 if (RequireCompleteType(VD->getLocation(),
13848 Context.getBaseElementType(Ty),
13849 diag::err_typecheck_decl_incomplete_type)) {
13850 VD->setInvalidDecl();
13851 return;
13854 // Require a non-abstract type.
13855 if (RequireNonAbstractType(VD->getLocation(), Ty,
13856 diag::err_abstract_type_in_decl,
13857 AbstractVariableType)) {
13858 VD->setInvalidDecl();
13859 return;
13862 // Don't bother complaining about constructors or destructors,
13863 // though.
13866 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13867 // If there is no declaration, there was an error parsing it. Just ignore it.
13868 if (!RealDecl)
13869 return;
13871 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13872 QualType Type = Var->getType();
13874 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13875 if (isa<DecompositionDecl>(RealDecl)) {
13876 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13877 Var->setInvalidDecl();
13878 return;
13881 if (Type->isUndeducedType() &&
13882 DeduceVariableDeclarationType(Var, false, nullptr))
13883 return;
13885 // C++11 [class.static.data]p3: A static data member can be declared with
13886 // the constexpr specifier; if so, its declaration shall specify
13887 // a brace-or-equal-initializer.
13888 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13889 // the definition of a variable [...] or the declaration of a static data
13890 // member.
13891 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13892 !Var->isThisDeclarationADemotedDefinition()) {
13893 if (Var->isStaticDataMember()) {
13894 // C++1z removes the relevant rule; the in-class declaration is always
13895 // a definition there.
13896 if (!getLangOpts().CPlusPlus17 &&
13897 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13898 Diag(Var->getLocation(),
13899 diag::err_constexpr_static_mem_var_requires_init)
13900 << Var;
13901 Var->setInvalidDecl();
13902 return;
13904 } else {
13905 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13906 Var->setInvalidDecl();
13907 return;
13911 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13912 // be initialized.
13913 if (!Var->isInvalidDecl() &&
13914 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13915 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13916 bool HasConstExprDefaultConstructor = false;
13917 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13918 for (auto *Ctor : RD->ctors()) {
13919 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13920 Ctor->getMethodQualifiers().getAddressSpace() ==
13921 LangAS::opencl_constant) {
13922 HasConstExprDefaultConstructor = true;
13926 if (!HasConstExprDefaultConstructor) {
13927 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13928 Var->setInvalidDecl();
13929 return;
13933 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13934 if (Var->getStorageClass() == SC_Extern) {
13935 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13936 << Var;
13937 Var->setInvalidDecl();
13938 return;
13940 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13941 diag::err_typecheck_decl_incomplete_type)) {
13942 Var->setInvalidDecl();
13943 return;
13945 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13946 if (!RD->hasTrivialDefaultConstructor()) {
13947 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13948 Var->setInvalidDecl();
13949 return;
13952 // The declaration is unitialized, no need for further checks.
13953 return;
13956 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13957 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13958 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13959 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13960 NTCUC_DefaultInitializedObject, NTCUK_Init);
13963 switch (DefKind) {
13964 case VarDecl::Definition:
13965 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13966 break;
13968 // We have an out-of-line definition of a static data member
13969 // that has an in-class initializer, so we type-check this like
13970 // a declaration.
13972 [[fallthrough]];
13974 case VarDecl::DeclarationOnly:
13975 // It's only a declaration.
13977 // Block scope. C99 6.7p7: If an identifier for an object is
13978 // declared with no linkage (C99 6.2.2p6), the type for the
13979 // object shall be complete.
13980 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13981 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13982 RequireCompleteType(Var->getLocation(), Type,
13983 diag::err_typecheck_decl_incomplete_type))
13984 Var->setInvalidDecl();
13986 // Make sure that the type is not abstract.
13987 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13988 RequireNonAbstractType(Var->getLocation(), Type,
13989 diag::err_abstract_type_in_decl,
13990 AbstractVariableType))
13991 Var->setInvalidDecl();
13992 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13993 Var->getStorageClass() == SC_PrivateExtern) {
13994 Diag(Var->getLocation(), diag::warn_private_extern);
13995 Diag(Var->getLocation(), diag::note_private_extern);
13998 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13999 !Var->isInvalidDecl())
14000 ExternalDeclarations.push_back(Var);
14002 return;
14004 case VarDecl::TentativeDefinition:
14005 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14006 // object that has file scope without an initializer, and without a
14007 // storage-class specifier or with the storage-class specifier "static",
14008 // constitutes a tentative definition. Note: A tentative definition with
14009 // external linkage is valid (C99 6.2.2p5).
14010 if (!Var->isInvalidDecl()) {
14011 if (const IncompleteArrayType *ArrayT
14012 = Context.getAsIncompleteArrayType(Type)) {
14013 if (RequireCompleteSizedType(
14014 Var->getLocation(), ArrayT->getElementType(),
14015 diag::err_array_incomplete_or_sizeless_type))
14016 Var->setInvalidDecl();
14017 } else if (Var->getStorageClass() == SC_Static) {
14018 // C99 6.9.2p3: If the declaration of an identifier for an object is
14019 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14020 // declared type shall not be an incomplete type.
14021 // NOTE: code such as the following
14022 // static struct s;
14023 // struct s { int a; };
14024 // is accepted by gcc. Hence here we issue a warning instead of
14025 // an error and we do not invalidate the static declaration.
14026 // NOTE: to avoid multiple warnings, only check the first declaration.
14027 if (Var->isFirstDecl())
14028 RequireCompleteType(Var->getLocation(), Type,
14029 diag::ext_typecheck_decl_incomplete_type);
14033 // Record the tentative definition; we're done.
14034 if (!Var->isInvalidDecl())
14035 TentativeDefinitions.push_back(Var);
14036 return;
14039 // Provide a specific diagnostic for uninitialized variable
14040 // definitions with incomplete array type.
14041 if (Type->isIncompleteArrayType()) {
14042 if (Var->isConstexpr())
14043 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14044 << Var;
14045 else
14046 Diag(Var->getLocation(),
14047 diag::err_typecheck_incomplete_array_needs_initializer);
14048 Var->setInvalidDecl();
14049 return;
14052 // Provide a specific diagnostic for uninitialized variable
14053 // definitions with reference type.
14054 if (Type->isReferenceType()) {
14055 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14056 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14057 return;
14060 // Do not attempt to type-check the default initializer for a
14061 // variable with dependent type.
14062 if (Type->isDependentType())
14063 return;
14065 if (Var->isInvalidDecl())
14066 return;
14068 if (!Var->hasAttr<AliasAttr>()) {
14069 if (RequireCompleteType(Var->getLocation(),
14070 Context.getBaseElementType(Type),
14071 diag::err_typecheck_decl_incomplete_type)) {
14072 Var->setInvalidDecl();
14073 return;
14075 } else {
14076 return;
14079 // The variable can not have an abstract class type.
14080 if (RequireNonAbstractType(Var->getLocation(), Type,
14081 diag::err_abstract_type_in_decl,
14082 AbstractVariableType)) {
14083 Var->setInvalidDecl();
14084 return;
14087 // Check for jumps past the implicit initializer. C++0x
14088 // clarifies that this applies to a "variable with automatic
14089 // storage duration", not a "local variable".
14090 // C++11 [stmt.dcl]p3
14091 // A program that jumps from a point where a variable with automatic
14092 // storage duration is not in scope to a point where it is in scope is
14093 // ill-formed unless the variable has scalar type, class type with a
14094 // trivial default constructor and a trivial destructor, a cv-qualified
14095 // version of one of these types, or an array of one of the preceding
14096 // types and is declared without an initializer.
14097 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14098 if (const RecordType *Record
14099 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14100 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14101 // Mark the function (if we're in one) for further checking even if the
14102 // looser rules of C++11 do not require such checks, so that we can
14103 // diagnose incompatibilities with C++98.
14104 if (!CXXRecord->isPOD())
14105 setFunctionHasBranchProtectedScope();
14108 // In OpenCL, we can't initialize objects in the __local address space,
14109 // even implicitly, so don't synthesize an implicit initializer.
14110 if (getLangOpts().OpenCL &&
14111 Var->getType().getAddressSpace() == LangAS::opencl_local)
14112 return;
14113 // C++03 [dcl.init]p9:
14114 // If no initializer is specified for an object, and the
14115 // object is of (possibly cv-qualified) non-POD class type (or
14116 // array thereof), the object shall be default-initialized; if
14117 // the object is of const-qualified type, the underlying class
14118 // type shall have a user-declared default
14119 // constructor. Otherwise, if no initializer is specified for
14120 // a non- static object, the object and its subobjects, if
14121 // any, have an indeterminate initial value); if the object
14122 // or any of its subobjects are of const-qualified type, the
14123 // program is ill-formed.
14124 // C++0x [dcl.init]p11:
14125 // If no initializer is specified for an object, the object is
14126 // default-initialized; [...].
14127 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14128 InitializationKind Kind
14129 = InitializationKind::CreateDefault(Var->getLocation());
14131 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14132 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14134 if (Init.get()) {
14135 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14136 // This is important for template substitution.
14137 Var->setInitStyle(VarDecl::CallInit);
14138 } else if (Init.isInvalid()) {
14139 // If default-init fails, attach a recovery-expr initializer to track
14140 // that initialization was attempted and failed.
14141 auto RecoveryExpr =
14142 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14143 if (RecoveryExpr.get())
14144 Var->setInit(RecoveryExpr.get());
14147 CheckCompleteVariableDeclaration(Var);
14151 void Sema::ActOnCXXForRangeDecl(Decl *D) {
14152 // If there is no declaration, there was an error parsing it. Ignore it.
14153 if (!D)
14154 return;
14156 VarDecl *VD = dyn_cast<VarDecl>(D);
14157 if (!VD) {
14158 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14159 D->setInvalidDecl();
14160 return;
14163 VD->setCXXForRangeDecl(true);
14165 // for-range-declaration cannot be given a storage class specifier.
14166 int Error = -1;
14167 switch (VD->getStorageClass()) {
14168 case SC_None:
14169 break;
14170 case SC_Extern:
14171 Error = 0;
14172 break;
14173 case SC_Static:
14174 Error = 1;
14175 break;
14176 case SC_PrivateExtern:
14177 Error = 2;
14178 break;
14179 case SC_Auto:
14180 Error = 3;
14181 break;
14182 case SC_Register:
14183 Error = 4;
14184 break;
14187 // for-range-declaration cannot be given a storage class specifier con't.
14188 switch (VD->getTSCSpec()) {
14189 case TSCS_thread_local:
14190 Error = 6;
14191 break;
14192 case TSCS___thread:
14193 case TSCS__Thread_local:
14194 case TSCS_unspecified:
14195 break;
14198 if (Error != -1) {
14199 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14200 << VD << Error;
14201 D->setInvalidDecl();
14205 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14206 IdentifierInfo *Ident,
14207 ParsedAttributes &Attrs) {
14208 // C++1y [stmt.iter]p1:
14209 // A range-based for statement of the form
14210 // for ( for-range-identifier : for-range-initializer ) statement
14211 // is equivalent to
14212 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14213 DeclSpec DS(Attrs.getPool().getFactory());
14215 const char *PrevSpec;
14216 unsigned DiagID;
14217 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14218 getPrintingPolicy());
14220 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14221 D.SetIdentifier(Ident, IdentLoc);
14222 D.takeAttributes(Attrs);
14224 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14225 IdentLoc);
14226 Decl *Var = ActOnDeclarator(S, D);
14227 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14228 FinalizeDeclaration(Var);
14229 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14230 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14231 : IdentLoc);
14234 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14235 if (var->isInvalidDecl()) return;
14237 MaybeAddCUDAConstantAttr(var);
14239 if (getLangOpts().OpenCL) {
14240 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14241 // initialiser
14242 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14243 !var->hasInit()) {
14244 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14245 << 1 /*Init*/;
14246 var->setInvalidDecl();
14247 return;
14251 // In Objective-C, don't allow jumps past the implicit initialization of a
14252 // local retaining variable.
14253 if (getLangOpts().ObjC &&
14254 var->hasLocalStorage()) {
14255 switch (var->getType().getObjCLifetime()) {
14256 case Qualifiers::OCL_None:
14257 case Qualifiers::OCL_ExplicitNone:
14258 case Qualifiers::OCL_Autoreleasing:
14259 break;
14261 case Qualifiers::OCL_Weak:
14262 case Qualifiers::OCL_Strong:
14263 setFunctionHasBranchProtectedScope();
14264 break;
14268 if (var->hasLocalStorage() &&
14269 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14270 setFunctionHasBranchProtectedScope();
14272 // Warn about externally-visible variables being defined without a
14273 // prior declaration. We only want to do this for global
14274 // declarations, but we also specifically need to avoid doing it for
14275 // class members because the linkage of an anonymous class can
14276 // change if it's later given a typedef name.
14277 if (var->isThisDeclarationADefinition() &&
14278 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14279 var->isExternallyVisible() && var->hasLinkage() &&
14280 !var->isInline() && !var->getDescribedVarTemplate() &&
14281 var->getStorageClass() != SC_Register &&
14282 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14283 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14284 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14285 var->getLocation())) {
14286 // Find a previous declaration that's not a definition.
14287 VarDecl *prev = var->getPreviousDecl();
14288 while (prev && prev->isThisDeclarationADefinition())
14289 prev = prev->getPreviousDecl();
14291 if (!prev) {
14292 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14293 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14294 << /* variable */ 0;
14298 // Cache the result of checking for constant initialization.
14299 std::optional<bool> CacheHasConstInit;
14300 const Expr *CacheCulprit = nullptr;
14301 auto checkConstInit = [&]() mutable {
14302 if (!CacheHasConstInit)
14303 CacheHasConstInit = var->getInit()->isConstantInitializer(
14304 Context, var->getType()->isReferenceType(), &CacheCulprit);
14305 return *CacheHasConstInit;
14308 if (var->getTLSKind() == VarDecl::TLS_Static) {
14309 if (var->getType().isDestructedType()) {
14310 // GNU C++98 edits for __thread, [basic.start.term]p3:
14311 // The type of an object with thread storage duration shall not
14312 // have a non-trivial destructor.
14313 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14314 if (getLangOpts().CPlusPlus11)
14315 Diag(var->getLocation(), diag::note_use_thread_local);
14316 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14317 if (!checkConstInit()) {
14318 // GNU C++98 edits for __thread, [basic.start.init]p4:
14319 // An object of thread storage duration shall not require dynamic
14320 // initialization.
14321 // FIXME: Need strict checking here.
14322 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14323 << CacheCulprit->getSourceRange();
14324 if (getLangOpts().CPlusPlus11)
14325 Diag(var->getLocation(), diag::note_use_thread_local);
14331 if (!var->getType()->isStructureType() && var->hasInit() &&
14332 isa<InitListExpr>(var->getInit())) {
14333 const auto *ILE = cast<InitListExpr>(var->getInit());
14334 unsigned NumInits = ILE->getNumInits();
14335 if (NumInits > 2)
14336 for (unsigned I = 0; I < NumInits; ++I) {
14337 const auto *Init = ILE->getInit(I);
14338 if (!Init)
14339 break;
14340 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14341 if (!SL)
14342 break;
14344 unsigned NumConcat = SL->getNumConcatenated();
14345 // Diagnose missing comma in string array initialization.
14346 // Do not warn when all the elements in the initializer are concatenated
14347 // together. Do not warn for macros too.
14348 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14349 bool OnlyOneMissingComma = true;
14350 for (unsigned J = I + 1; J < NumInits; ++J) {
14351 const auto *Init = ILE->getInit(J);
14352 if (!Init)
14353 break;
14354 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14355 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14356 OnlyOneMissingComma = false;
14357 break;
14361 if (OnlyOneMissingComma) {
14362 SmallVector<FixItHint, 1> Hints;
14363 for (unsigned i = 0; i < NumConcat - 1; ++i)
14364 Hints.push_back(FixItHint::CreateInsertion(
14365 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14367 Diag(SL->getStrTokenLoc(1),
14368 diag::warn_concatenated_literal_array_init)
14369 << Hints;
14370 Diag(SL->getBeginLoc(),
14371 diag::note_concatenated_string_literal_silence);
14373 // In any case, stop now.
14374 break;
14380 QualType type = var->getType();
14382 if (var->hasAttr<BlocksAttr>())
14383 getCurFunction()->addByrefBlockVar(var);
14385 Expr *Init = var->getInit();
14386 bool GlobalStorage = var->hasGlobalStorage();
14387 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14388 QualType baseType = Context.getBaseElementType(type);
14389 bool HasConstInit = true;
14391 // Check whether the initializer is sufficiently constant.
14392 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14393 !Init->isValueDependent() &&
14394 (GlobalStorage || var->isConstexpr() ||
14395 var->mightBeUsableInConstantExpressions(Context))) {
14396 // If this variable might have a constant initializer or might be usable in
14397 // constant expressions, check whether or not it actually is now. We can't
14398 // do this lazily, because the result might depend on things that change
14399 // later, such as which constexpr functions happen to be defined.
14400 SmallVector<PartialDiagnosticAt, 8> Notes;
14401 if (!getLangOpts().CPlusPlus11) {
14402 // Prior to C++11, in contexts where a constant initializer is required,
14403 // the set of valid constant initializers is described by syntactic rules
14404 // in [expr.const]p2-6.
14405 // FIXME: Stricter checking for these rules would be useful for constinit /
14406 // -Wglobal-constructors.
14407 HasConstInit = checkConstInit();
14409 // Compute and cache the constant value, and remember that we have a
14410 // constant initializer.
14411 if (HasConstInit) {
14412 (void)var->checkForConstantInitialization(Notes);
14413 Notes.clear();
14414 } else if (CacheCulprit) {
14415 Notes.emplace_back(CacheCulprit->getExprLoc(),
14416 PDiag(diag::note_invalid_subexpr_in_const_expr));
14417 Notes.back().second << CacheCulprit->getSourceRange();
14419 } else {
14420 // Evaluate the initializer to see if it's a constant initializer.
14421 HasConstInit = var->checkForConstantInitialization(Notes);
14424 if (HasConstInit) {
14425 // FIXME: Consider replacing the initializer with a ConstantExpr.
14426 } else if (var->isConstexpr()) {
14427 SourceLocation DiagLoc = var->getLocation();
14428 // If the note doesn't add any useful information other than a source
14429 // location, fold it into the primary diagnostic.
14430 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14431 diag::note_invalid_subexpr_in_const_expr) {
14432 DiagLoc = Notes[0].first;
14433 Notes.clear();
14435 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14436 << var << Init->getSourceRange();
14437 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14438 Diag(Notes[I].first, Notes[I].second);
14439 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14440 auto *Attr = var->getAttr<ConstInitAttr>();
14441 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14442 << Init->getSourceRange();
14443 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14444 << Attr->getRange() << Attr->isConstinit();
14445 for (auto &it : Notes)
14446 Diag(it.first, it.second);
14447 } else if (IsGlobal &&
14448 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14449 var->getLocation())) {
14450 // Warn about globals which don't have a constant initializer. Don't
14451 // warn about globals with a non-trivial destructor because we already
14452 // warned about them.
14453 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14454 if (!(RD && !RD->hasTrivialDestructor())) {
14455 // checkConstInit() here permits trivial default initialization even in
14456 // C++11 onwards, where such an initializer is not a constant initializer
14457 // but nonetheless doesn't require a global constructor.
14458 if (!checkConstInit())
14459 Diag(var->getLocation(), diag::warn_global_constructor)
14460 << Init->getSourceRange();
14465 // Apply section attributes and pragmas to global variables.
14466 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14467 !inTemplateInstantiation()) {
14468 PragmaStack<StringLiteral *> *Stack = nullptr;
14469 int SectionFlags = ASTContext::PSF_Read;
14470 bool MSVCEnv =
14471 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14472 std::optional<QualType::NonConstantStorageReason> Reason;
14473 if (HasConstInit &&
14474 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14475 Stack = &ConstSegStack;
14476 } else {
14477 SectionFlags |= ASTContext::PSF_Write;
14478 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14480 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14481 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14482 SectionFlags |= ASTContext::PSF_Implicit;
14483 UnifySection(SA->getName(), SectionFlags, var);
14484 } else if (Stack->CurrentValue) {
14485 if (Stack != &ConstSegStack && MSVCEnv &&
14486 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14487 var->getType().isConstQualified()) {
14488 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14489 NonConstNonReferenceType) &&
14490 "This case should've already been handled elsewhere");
14491 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14492 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14493 ? QualType::NonConstantStorageReason::NonTrivialCtor
14494 : *Reason);
14496 SectionFlags |= ASTContext::PSF_Implicit;
14497 auto SectionName = Stack->CurrentValue->getString();
14498 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14499 Stack->CurrentPragmaLocation,
14500 SectionAttr::Declspec_allocate));
14501 if (UnifySection(SectionName, SectionFlags, var))
14502 var->dropAttr<SectionAttr>();
14505 // Apply the init_seg attribute if this has an initializer. If the
14506 // initializer turns out to not be dynamic, we'll end up ignoring this
14507 // attribute.
14508 if (CurInitSeg && var->getInit())
14509 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14510 CurInitSegLoc));
14513 // All the following checks are C++ only.
14514 if (!getLangOpts().CPlusPlus) {
14515 // If this variable must be emitted, add it as an initializer for the
14516 // current module.
14517 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14518 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14519 return;
14522 // Require the destructor.
14523 if (!type->isDependentType())
14524 if (const RecordType *recordType = baseType->getAs<RecordType>())
14525 FinalizeVarWithDestructor(var, recordType);
14527 // If this variable must be emitted, add it as an initializer for the current
14528 // module.
14529 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14530 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14532 // Build the bindings if this is a structured binding declaration.
14533 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14534 CheckCompleteDecompositionDeclaration(DD);
14537 /// Check if VD needs to be dllexport/dllimport due to being in a
14538 /// dllexport/import function.
14539 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14540 assert(VD->isStaticLocal());
14542 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14544 // Find outermost function when VD is in lambda function.
14545 while (FD && !getDLLAttr(FD) &&
14546 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14547 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14548 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14551 if (!FD)
14552 return;
14554 // Static locals inherit dll attributes from their function.
14555 if (Attr *A = getDLLAttr(FD)) {
14556 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14557 NewAttr->setInherited(true);
14558 VD->addAttr(NewAttr);
14559 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14560 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14561 NewAttr->setInherited(true);
14562 VD->addAttr(NewAttr);
14564 // Export this function to enforce exporting this static variable even
14565 // if it is not used in this compilation unit.
14566 if (!FD->hasAttr<DLLExportAttr>())
14567 FD->addAttr(NewAttr);
14569 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14570 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14571 NewAttr->setInherited(true);
14572 VD->addAttr(NewAttr);
14576 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14577 assert(VD->getTLSKind());
14579 // Perform TLS alignment check here after attributes attached to the variable
14580 // which may affect the alignment have been processed. Only perform the check
14581 // if the target has a maximum TLS alignment (zero means no constraints).
14582 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14583 // Protect the check so that it's not performed on dependent types and
14584 // dependent alignments (we can't determine the alignment in that case).
14585 if (!VD->hasDependentAlignment()) {
14586 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14587 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14588 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14589 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14590 << (unsigned)MaxAlignChars.getQuantity();
14596 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14597 /// any semantic actions necessary after any initializer has been attached.
14598 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14599 // Note that we are no longer parsing the initializer for this declaration.
14600 ParsingInitForAutoVars.erase(ThisDecl);
14602 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14603 if (!VD)
14604 return;
14606 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14607 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14608 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14609 if (PragmaClangBSSSection.Valid)
14610 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14611 Context, PragmaClangBSSSection.SectionName,
14612 PragmaClangBSSSection.PragmaLocation));
14613 if (PragmaClangDataSection.Valid)
14614 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14615 Context, PragmaClangDataSection.SectionName,
14616 PragmaClangDataSection.PragmaLocation));
14617 if (PragmaClangRodataSection.Valid)
14618 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14619 Context, PragmaClangRodataSection.SectionName,
14620 PragmaClangRodataSection.PragmaLocation));
14621 if (PragmaClangRelroSection.Valid)
14622 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14623 Context, PragmaClangRelroSection.SectionName,
14624 PragmaClangRelroSection.PragmaLocation));
14627 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14628 for (auto *BD : DD->bindings()) {
14629 FinalizeDeclaration(BD);
14633 checkAttributesAfterMerging(*this, *VD);
14635 if (VD->isStaticLocal())
14636 CheckStaticLocalForDllExport(VD);
14638 if (VD->getTLSKind())
14639 CheckThreadLocalForLargeAlignment(VD);
14641 // Perform check for initializers of device-side global variables.
14642 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14643 // 7.5). We must also apply the same checks to all __shared__
14644 // variables whether they are local or not. CUDA also allows
14645 // constant initializers for __constant__ and __device__ variables.
14646 if (getLangOpts().CUDA)
14647 checkAllowedCUDAInitializer(VD);
14649 // Grab the dllimport or dllexport attribute off of the VarDecl.
14650 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14652 // Imported static data members cannot be defined out-of-line.
14653 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14654 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14655 VD->isThisDeclarationADefinition()) {
14656 // We allow definitions of dllimport class template static data members
14657 // with a warning.
14658 CXXRecordDecl *Context =
14659 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14660 bool IsClassTemplateMember =
14661 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14662 Context->getDescribedClassTemplate();
14664 Diag(VD->getLocation(),
14665 IsClassTemplateMember
14666 ? diag::warn_attribute_dllimport_static_field_definition
14667 : diag::err_attribute_dllimport_static_field_definition);
14668 Diag(IA->getLocation(), diag::note_attribute);
14669 if (!IsClassTemplateMember)
14670 VD->setInvalidDecl();
14674 // dllimport/dllexport variables cannot be thread local, their TLS index
14675 // isn't exported with the variable.
14676 if (DLLAttr && VD->getTLSKind()) {
14677 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14678 if (F && getDLLAttr(F)) {
14679 assert(VD->isStaticLocal());
14680 // But if this is a static local in a dlimport/dllexport function, the
14681 // function will never be inlined, which means the var would never be
14682 // imported, so having it marked import/export is safe.
14683 } else {
14684 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14685 << DLLAttr;
14686 VD->setInvalidDecl();
14690 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14691 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14692 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14693 << Attr;
14694 VD->dropAttr<UsedAttr>();
14697 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14698 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14699 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14700 << Attr;
14701 VD->dropAttr<RetainAttr>();
14705 const DeclContext *DC = VD->getDeclContext();
14706 // If there's a #pragma GCC visibility in scope, and this isn't a class
14707 // member, set the visibility of this variable.
14708 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14709 AddPushedVisibilityAttribute(VD);
14711 // FIXME: Warn on unused var template partial specializations.
14712 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14713 MarkUnusedFileScopedDecl(VD);
14715 // Now we have parsed the initializer and can update the table of magic
14716 // tag values.
14717 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14718 !VD->getType()->isIntegralOrEnumerationType())
14719 return;
14721 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14722 const Expr *MagicValueExpr = VD->getInit();
14723 if (!MagicValueExpr) {
14724 continue;
14726 std::optional<llvm::APSInt> MagicValueInt;
14727 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14728 Diag(I->getRange().getBegin(),
14729 diag::err_type_tag_for_datatype_not_ice)
14730 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14731 continue;
14733 if (MagicValueInt->getActiveBits() > 64) {
14734 Diag(I->getRange().getBegin(),
14735 diag::err_type_tag_for_datatype_too_large)
14736 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14737 continue;
14739 uint64_t MagicValue = MagicValueInt->getZExtValue();
14740 RegisterTypeTagForDatatype(I->getArgumentKind(),
14741 MagicValue,
14742 I->getMatchingCType(),
14743 I->getLayoutCompatible(),
14744 I->getMustBeNull());
14748 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14749 auto *VD = dyn_cast<VarDecl>(DD);
14750 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14753 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14754 ArrayRef<Decl *> Group) {
14755 SmallVector<Decl*, 8> Decls;
14757 if (DS.isTypeSpecOwned())
14758 Decls.push_back(DS.getRepAsDecl());
14760 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14761 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14762 bool DiagnosedMultipleDecomps = false;
14763 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14764 bool DiagnosedNonDeducedAuto = false;
14766 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14767 if (Decl *D = Group[i]) {
14768 // Check if the Decl has been declared in '#pragma omp declare target'
14769 // directive and has static storage duration.
14770 if (auto *VD = dyn_cast<VarDecl>(D);
14771 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14772 VD->hasGlobalStorage())
14773 ActOnOpenMPDeclareTargetInitializer(D);
14774 // For declarators, there are some additional syntactic-ish checks we need
14775 // to perform.
14776 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14777 if (!FirstDeclaratorInGroup)
14778 FirstDeclaratorInGroup = DD;
14779 if (!FirstDecompDeclaratorInGroup)
14780 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14781 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14782 !hasDeducedAuto(DD))
14783 FirstNonDeducedAutoInGroup = DD;
14785 if (FirstDeclaratorInGroup != DD) {
14786 // A decomposition declaration cannot be combined with any other
14787 // declaration in the same group.
14788 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14789 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14790 diag::err_decomp_decl_not_alone)
14791 << FirstDeclaratorInGroup->getSourceRange()
14792 << DD->getSourceRange();
14793 DiagnosedMultipleDecomps = true;
14796 // A declarator that uses 'auto' in any way other than to declare a
14797 // variable with a deduced type cannot be combined with any other
14798 // declarator in the same group.
14799 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14800 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14801 diag::err_auto_non_deduced_not_alone)
14802 << FirstNonDeducedAutoInGroup->getType()
14803 ->hasAutoForTrailingReturnType()
14804 << FirstDeclaratorInGroup->getSourceRange()
14805 << DD->getSourceRange();
14806 DiagnosedNonDeducedAuto = true;
14811 Decls.push_back(D);
14815 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14816 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14817 handleTagNumbering(Tag, S);
14818 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14819 getLangOpts().CPlusPlus)
14820 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14824 return BuildDeclaratorGroup(Decls);
14827 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14828 /// group, performing any necessary semantic checking.
14829 Sema::DeclGroupPtrTy
14830 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14831 // C++14 [dcl.spec.auto]p7: (DR1347)
14832 // If the type that replaces the placeholder type is not the same in each
14833 // deduction, the program is ill-formed.
14834 if (Group.size() > 1) {
14835 QualType Deduced;
14836 VarDecl *DeducedDecl = nullptr;
14837 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14838 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14839 if (!D || D->isInvalidDecl())
14840 break;
14841 DeducedType *DT = D->getType()->getContainedDeducedType();
14842 if (!DT || DT->getDeducedType().isNull())
14843 continue;
14844 if (Deduced.isNull()) {
14845 Deduced = DT->getDeducedType();
14846 DeducedDecl = D;
14847 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14848 auto *AT = dyn_cast<AutoType>(DT);
14849 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14850 diag::err_auto_different_deductions)
14851 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14852 << DeducedDecl->getDeclName() << DT->getDeducedType()
14853 << D->getDeclName();
14854 if (DeducedDecl->hasInit())
14855 Dia << DeducedDecl->getInit()->getSourceRange();
14856 if (D->getInit())
14857 Dia << D->getInit()->getSourceRange();
14858 D->setInvalidDecl();
14859 break;
14864 ActOnDocumentableDecls(Group);
14866 return DeclGroupPtrTy::make(
14867 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14870 void Sema::ActOnDocumentableDecl(Decl *D) {
14871 ActOnDocumentableDecls(D);
14874 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14875 // Don't parse the comment if Doxygen diagnostics are ignored.
14876 if (Group.empty() || !Group[0])
14877 return;
14879 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14880 Group[0]->getLocation()) &&
14881 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14882 Group[0]->getLocation()))
14883 return;
14885 if (Group.size() >= 2) {
14886 // This is a decl group. Normally it will contain only declarations
14887 // produced from declarator list. But in case we have any definitions or
14888 // additional declaration references:
14889 // 'typedef struct S {} S;'
14890 // 'typedef struct S *S;'
14891 // 'struct S *pS;'
14892 // FinalizeDeclaratorGroup adds these as separate declarations.
14893 Decl *MaybeTagDecl = Group[0];
14894 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14895 Group = Group.slice(1);
14899 // FIMXE: We assume every Decl in the group is in the same file.
14900 // This is false when preprocessor constructs the group from decls in
14901 // different files (e. g. macros or #include).
14902 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14905 /// Common checks for a parameter-declaration that should apply to both function
14906 /// parameters and non-type template parameters.
14907 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14908 // Check that there are no default arguments inside the type of this
14909 // parameter.
14910 if (getLangOpts().CPlusPlus)
14911 CheckExtraCXXDefaultArguments(D);
14913 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14914 if (D.getCXXScopeSpec().isSet()) {
14915 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14916 << D.getCXXScopeSpec().getRange();
14919 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14920 // simple identifier except [...irrelevant cases...].
14921 switch (D.getName().getKind()) {
14922 case UnqualifiedIdKind::IK_Identifier:
14923 break;
14925 case UnqualifiedIdKind::IK_OperatorFunctionId:
14926 case UnqualifiedIdKind::IK_ConversionFunctionId:
14927 case UnqualifiedIdKind::IK_LiteralOperatorId:
14928 case UnqualifiedIdKind::IK_ConstructorName:
14929 case UnqualifiedIdKind::IK_DestructorName:
14930 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14931 case UnqualifiedIdKind::IK_DeductionGuideName:
14932 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14933 << GetNameForDeclarator(D).getName();
14934 break;
14936 case UnqualifiedIdKind::IK_TemplateId:
14937 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14938 // GetNameForDeclarator would not produce a useful name in this case.
14939 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14940 break;
14944 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
14945 SourceLocation ExplicitThisLoc) {
14946 if (!ExplicitThisLoc.isValid())
14947 return;
14948 assert(S.getLangOpts().CPlusPlus &&
14949 "explicit parameter in non-cplusplus mode");
14950 if (!S.getLangOpts().CPlusPlus23)
14951 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14952 << P->getSourceRange();
14954 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14955 // parameter pack.
14956 if (P->isParameterPack()) {
14957 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14958 << P->getSourceRange();
14959 return;
14961 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14962 if (LambdaScopeInfo *LSI = S.getCurLambda())
14963 LSI->ExplicitObjectParameter = P;
14966 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14967 /// to introduce parameters into function prototype scope.
14968 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
14969 SourceLocation ExplicitThisLoc) {
14970 const DeclSpec &DS = D.getDeclSpec();
14972 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14974 // C++03 [dcl.stc]p2 also permits 'auto'.
14975 StorageClass SC = SC_None;
14976 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14977 SC = SC_Register;
14978 // In C++11, the 'register' storage class specifier is deprecated.
14979 // In C++17, it is not allowed, but we tolerate it as an extension.
14980 if (getLangOpts().CPlusPlus11) {
14981 Diag(DS.getStorageClassSpecLoc(),
14982 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14983 : diag::warn_deprecated_register)
14984 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14986 } else if (getLangOpts().CPlusPlus &&
14987 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14988 SC = SC_Auto;
14989 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14990 Diag(DS.getStorageClassSpecLoc(),
14991 diag::err_invalid_storage_class_in_func_decl);
14992 D.getMutableDeclSpec().ClearStorageClassSpecs();
14995 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14996 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14997 << DeclSpec::getSpecifierName(TSCS);
14998 if (DS.isInlineSpecified())
14999 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15000 << getLangOpts().CPlusPlus17;
15001 if (DS.hasConstexprSpecifier())
15002 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15003 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15005 DiagnoseFunctionSpecifiers(DS);
15007 CheckFunctionOrTemplateParamDeclarator(S, D);
15009 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15010 QualType parmDeclType = TInfo->getType();
15012 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15013 IdentifierInfo *II = D.getIdentifier();
15014 if (II) {
15015 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15016 ForVisibleRedeclaration);
15017 LookupName(R, S);
15018 if (!R.empty()) {
15019 NamedDecl *PrevDecl = *R.begin();
15020 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15021 // Maybe we will complain about the shadowed template parameter.
15022 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15023 // Just pretend that we didn't see the previous declaration.
15024 PrevDecl = nullptr;
15026 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15027 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15028 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15029 // Recover by removing the name
15030 II = nullptr;
15031 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15032 D.setInvalidType(true);
15037 // Temporarily put parameter variables in the translation unit, not
15038 // the enclosing context. This prevents them from accidentally
15039 // looking like class members in C++.
15040 ParmVarDecl *New =
15041 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15042 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15044 if (D.isInvalidType())
15045 New->setInvalidDecl();
15047 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15049 assert(S->isFunctionPrototypeScope());
15050 assert(S->getFunctionPrototypeDepth() >= 1);
15051 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15052 S->getNextFunctionPrototypeIndex());
15054 // Add the parameter declaration into this scope.
15055 S->AddDecl(New);
15056 if (II)
15057 IdResolver.AddDecl(New);
15059 ProcessDeclAttributes(S, New, D);
15061 if (D.getDeclSpec().isModulePrivateSpecified())
15062 Diag(New->getLocation(), diag::err_module_private_local)
15063 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15064 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15066 if (New->hasAttr<BlocksAttr>()) {
15067 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15070 if (getLangOpts().OpenCL)
15071 deduceOpenCLAddressSpace(New);
15073 return New;
15076 /// Synthesizes a variable for a parameter arising from a
15077 /// typedef.
15078 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15079 SourceLocation Loc,
15080 QualType T) {
15081 /* FIXME: setting StartLoc == Loc.
15082 Would it be worth to modify callers so as to provide proper source
15083 location for the unnamed parameters, embedding the parameter's type? */
15084 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15085 T, Context.getTrivialTypeSourceInfo(T, Loc),
15086 SC_None, nullptr);
15087 Param->setImplicit();
15088 return Param;
15091 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15092 // Don't diagnose unused-parameter errors in template instantiations; we
15093 // will already have done so in the template itself.
15094 if (inTemplateInstantiation())
15095 return;
15097 for (const ParmVarDecl *Parameter : Parameters) {
15098 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15099 !Parameter->hasAttr<UnusedAttr>() &&
15100 !Parameter->getIdentifier()->isPlaceholder()) {
15101 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15102 << Parameter->getDeclName();
15107 void Sema::DiagnoseSizeOfParametersAndReturnValue(
15108 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15109 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15110 return;
15112 // Warn if the return value is pass-by-value and larger than the specified
15113 // threshold.
15114 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15115 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15116 if (Size > LangOpts.NumLargeByValueCopy)
15117 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15120 // Warn if any parameter is pass-by-value and larger than the specified
15121 // threshold.
15122 for (const ParmVarDecl *Parameter : Parameters) {
15123 QualType T = Parameter->getType();
15124 if (T->isDependentType() || !T.isPODType(Context))
15125 continue;
15126 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15127 if (Size > LangOpts.NumLargeByValueCopy)
15128 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15129 << Parameter << Size;
15133 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15134 SourceLocation NameLoc, IdentifierInfo *Name,
15135 QualType T, TypeSourceInfo *TSInfo,
15136 StorageClass SC) {
15137 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15138 if (getLangOpts().ObjCAutoRefCount &&
15139 T.getObjCLifetime() == Qualifiers::OCL_None &&
15140 T->isObjCLifetimeType()) {
15142 Qualifiers::ObjCLifetime lifetime;
15144 // Special cases for arrays:
15145 // - if it's const, use __unsafe_unretained
15146 // - otherwise, it's an error
15147 if (T->isArrayType()) {
15148 if (!T.isConstQualified()) {
15149 if (DelayedDiagnostics.shouldDelayDiagnostics())
15150 DelayedDiagnostics.add(
15151 sema::DelayedDiagnostic::makeForbiddenType(
15152 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15153 else
15154 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15155 << TSInfo->getTypeLoc().getSourceRange();
15157 lifetime = Qualifiers::OCL_ExplicitNone;
15158 } else {
15159 lifetime = T->getObjCARCImplicitLifetime();
15161 T = Context.getLifetimeQualifiedType(T, lifetime);
15164 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15165 Context.getAdjustedParameterType(T),
15166 TSInfo, SC, nullptr);
15168 // Make a note if we created a new pack in the scope of a lambda, so that
15169 // we know that references to that pack must also be expanded within the
15170 // lambda scope.
15171 if (New->isParameterPack())
15172 if (auto *LSI = getEnclosingLambda())
15173 LSI->LocalPacks.push_back(New);
15175 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15176 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15177 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15178 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15180 // Parameter declarators cannot be interface types. All ObjC objects are
15181 // passed by reference.
15182 if (T->isObjCObjectType()) {
15183 SourceLocation TypeEndLoc =
15184 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15185 Diag(NameLoc,
15186 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15187 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15188 T = Context.getObjCObjectPointerType(T);
15189 New->setType(T);
15192 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15193 // duration shall not be qualified by an address-space qualifier."
15194 // Since all parameters have automatic store duration, they can not have
15195 // an address space.
15196 if (T.getAddressSpace() != LangAS::Default &&
15197 // OpenCL allows function arguments declared to be an array of a type
15198 // to be qualified with an address space.
15199 !(getLangOpts().OpenCL &&
15200 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15201 // WebAssembly allows reference types as parameters. Funcref in particular
15202 // lives in a different address space.
15203 !(T->isFunctionPointerType() &&
15204 T.getAddressSpace() == LangAS::wasm_funcref)) {
15205 Diag(NameLoc, diag::err_arg_with_address_space);
15206 New->setInvalidDecl();
15209 // PPC MMA non-pointer types are not allowed as function argument types.
15210 if (Context.getTargetInfo().getTriple().isPPC64() &&
15211 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15212 New->setInvalidDecl();
15215 return New;
15218 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15219 SourceLocation LocAfterDecls) {
15220 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15222 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15223 // in the declaration list shall have at least one declarator, those
15224 // declarators shall only declare identifiers from the identifier list, and
15225 // every identifier in the identifier list shall be declared.
15227 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15228 // identifiers it names shall be declared in the declaration list."
15230 // This is why we only diagnose in C99 and later. Note, the other conditions
15231 // listed are checked elsewhere.
15232 if (!FTI.hasPrototype) {
15233 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15234 --i;
15235 if (FTI.Params[i].Param == nullptr) {
15236 if (getLangOpts().C99) {
15237 SmallString<256> Code;
15238 llvm::raw_svector_ostream(Code)
15239 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15240 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15241 << FTI.Params[i].Ident
15242 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15245 // Implicitly declare the argument as type 'int' for lack of a better
15246 // type.
15247 AttributeFactory attrs;
15248 DeclSpec DS(attrs);
15249 const char* PrevSpec; // unused
15250 unsigned DiagID; // unused
15251 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15252 DiagID, Context.getPrintingPolicy());
15253 // Use the identifier location for the type source range.
15254 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15255 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15256 Declarator ParamD(DS, ParsedAttributesView::none(),
15257 DeclaratorContext::KNRTypeList);
15258 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15259 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15265 Decl *
15266 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15267 MultiTemplateParamsArg TemplateParameterLists,
15268 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15269 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15270 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15271 Scope *ParentScope = FnBodyScope->getParent();
15273 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15274 // we define a non-templated function definition, we will create a declaration
15275 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15276 // The base function declaration will have the equivalent of an `omp declare
15277 // variant` annotation which specifies the mangled definition as a
15278 // specialization function under the OpenMP context defined as part of the
15279 // `omp begin declare variant`.
15280 SmallVector<FunctionDecl *, 4> Bases;
15281 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15282 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15283 ParentScope, D, TemplateParameterLists, Bases);
15285 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15286 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15287 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15289 if (!Bases.empty())
15290 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15292 return Dcl;
15295 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15296 Consumer.HandleInlineFunctionDefinition(D);
15299 static bool FindPossiblePrototype(const FunctionDecl *FD,
15300 const FunctionDecl *&PossiblePrototype) {
15301 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15302 Prev = Prev->getPreviousDecl()) {
15303 // Ignore any declarations that occur in function or method
15304 // scope, because they aren't visible from the header.
15305 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15306 continue;
15308 PossiblePrototype = Prev;
15309 return Prev->getType()->isFunctionProtoType();
15311 return false;
15314 static bool
15315 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15316 const FunctionDecl *&PossiblePrototype) {
15317 // Don't warn about invalid declarations.
15318 if (FD->isInvalidDecl())
15319 return false;
15321 // Or declarations that aren't global.
15322 if (!FD->isGlobal())
15323 return false;
15325 // Don't warn about C++ member functions.
15326 if (isa<CXXMethodDecl>(FD))
15327 return false;
15329 // Don't warn about 'main'.
15330 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15331 if (IdentifierInfo *II = FD->getIdentifier())
15332 if (II->isStr("main") || II->isStr("efi_main"))
15333 return false;
15335 // Don't warn about inline functions.
15336 if (FD->isInlined())
15337 return false;
15339 // Don't warn about function templates.
15340 if (FD->getDescribedFunctionTemplate())
15341 return false;
15343 // Don't warn about function template specializations.
15344 if (FD->isFunctionTemplateSpecialization())
15345 return false;
15347 // Don't warn for OpenCL kernels.
15348 if (FD->hasAttr<OpenCLKernelAttr>())
15349 return false;
15351 // Don't warn on explicitly deleted functions.
15352 if (FD->isDeleted())
15353 return false;
15355 // Don't warn on implicitly local functions (such as having local-typed
15356 // parameters).
15357 if (!FD->isExternallyVisible())
15358 return false;
15360 // If we were able to find a potential prototype, don't warn.
15361 if (FindPossiblePrototype(FD, PossiblePrototype))
15362 return false;
15364 return true;
15367 void
15368 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15369 const FunctionDecl *EffectiveDefinition,
15370 SkipBodyInfo *SkipBody) {
15371 const FunctionDecl *Definition = EffectiveDefinition;
15372 if (!Definition &&
15373 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15374 return;
15376 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15377 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15378 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15379 // A merged copy of the same function, instantiated as a member of
15380 // the same class, is OK.
15381 if (declaresSameEntity(OrigFD, OrigDef) &&
15382 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15383 cast<Decl>(FD->getLexicalDeclContext())))
15384 return;
15389 if (canRedefineFunction(Definition, getLangOpts()))
15390 return;
15392 // Don't emit an error when this is redefinition of a typo-corrected
15393 // definition.
15394 if (TypoCorrectedFunctionDefinitions.count(Definition))
15395 return;
15397 // If we don't have a visible definition of the function, and it's inline or
15398 // a template, skip the new definition.
15399 if (SkipBody && !hasVisibleDefinition(Definition) &&
15400 (Definition->getFormalLinkage() == Linkage::Internal ||
15401 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15402 Definition->getNumTemplateParameterLists())) {
15403 SkipBody->ShouldSkip = true;
15404 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15405 if (auto *TD = Definition->getDescribedFunctionTemplate())
15406 makeMergedDefinitionVisible(TD);
15407 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15408 return;
15411 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15412 Definition->getStorageClass() == SC_Extern)
15413 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15414 << FD << getLangOpts().CPlusPlus;
15415 else
15416 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15418 Diag(Definition->getLocation(), diag::note_previous_definition);
15419 FD->setInvalidDecl();
15422 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15423 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15425 LambdaScopeInfo *LSI = PushLambdaScope();
15426 LSI->CallOperator = CallOperator;
15427 LSI->Lambda = LambdaClass;
15428 LSI->ReturnType = CallOperator->getReturnType();
15429 // This function in calls in situation where the context of the call operator
15430 // is not entered, so we set AfterParameterList to false, so that
15431 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15432 LSI->AfterParameterList = false;
15433 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15435 if (LCD == LCD_None)
15436 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15437 else if (LCD == LCD_ByCopy)
15438 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15439 else if (LCD == LCD_ByRef)
15440 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15441 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15443 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15444 LSI->Mutable = !CallOperator->isConst();
15445 if (CallOperator->isExplicitObjectMemberFunction())
15446 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15448 // Add the captures to the LSI so they can be noted as already
15449 // captured within tryCaptureVar.
15450 auto I = LambdaClass->field_begin();
15451 for (const auto &C : LambdaClass->captures()) {
15452 if (C.capturesVariable()) {
15453 ValueDecl *VD = C.getCapturedVar();
15454 if (VD->isInitCapture())
15455 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15456 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15457 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15458 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15459 /*EllipsisLoc*/C.isPackExpansion()
15460 ? C.getEllipsisLoc() : SourceLocation(),
15461 I->getType(), /*Invalid*/false);
15463 } else if (C.capturesThis()) {
15464 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15465 C.getCaptureKind() == LCK_StarThis);
15466 } else {
15467 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15468 I->getType());
15470 ++I;
15472 return LSI;
15475 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15476 SkipBodyInfo *SkipBody,
15477 FnBodyKind BodyKind) {
15478 if (!D) {
15479 // Parsing the function declaration failed in some way. Push on a fake scope
15480 // anyway so we can try to parse the function body.
15481 PushFunctionScope();
15482 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15483 return D;
15486 FunctionDecl *FD = nullptr;
15488 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15489 FD = FunTmpl->getTemplatedDecl();
15490 else
15491 FD = cast<FunctionDecl>(D);
15493 // Do not push if it is a lambda because one is already pushed when building
15494 // the lambda in ActOnStartOfLambdaDefinition().
15495 if (!isLambdaCallOperator(FD))
15496 // [expr.const]/p14.1
15497 // An expression or conversion is in an immediate function context if it is
15498 // potentially evaluated and either: its innermost enclosing non-block scope
15499 // is a function parameter scope of an immediate function.
15500 PushExpressionEvaluationContext(
15501 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15502 : ExprEvalContexts.back().Context);
15504 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15505 // context is nested in an immediate function context, so smaller contexts
15506 // that appear inside immediate functions (like variable initializers) are
15507 // considered to be inside an immediate function context even though by
15508 // themselves they are not immediate function contexts. But when a new
15509 // function is entered, we need to reset this tracking, since the entered
15510 // function might be not an immediate function.
15511 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15512 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15513 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15515 // Check for defining attributes before the check for redefinition.
15516 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15517 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15518 FD->dropAttr<AliasAttr>();
15519 FD->setInvalidDecl();
15521 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15522 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15523 FD->dropAttr<IFuncAttr>();
15524 FD->setInvalidDecl();
15526 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15527 if (!Context.getTargetInfo().hasFeature("fmv") &&
15528 !Attr->isDefaultVersion()) {
15529 // If function multi versioning disabled skip parsing function body
15530 // defined with non-default target_version attribute
15531 if (SkipBody)
15532 SkipBody->ShouldSkip = true;
15533 return nullptr;
15537 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15538 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15539 Ctor->isDefaultConstructor() &&
15540 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15541 // If this is an MS ABI dllexport default constructor, instantiate any
15542 // default arguments.
15543 InstantiateDefaultCtorDefaultArgs(Ctor);
15547 // See if this is a redefinition. If 'will have body' (or similar) is already
15548 // set, then these checks were already performed when it was set.
15549 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15550 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15551 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15553 // If we're skipping the body, we're done. Don't enter the scope.
15554 if (SkipBody && SkipBody->ShouldSkip)
15555 return D;
15558 // Mark this function as "will have a body eventually". This lets users to
15559 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15560 // this function.
15561 FD->setWillHaveBody();
15563 // If we are instantiating a generic lambda call operator, push
15564 // a LambdaScopeInfo onto the function stack. But use the information
15565 // that's already been calculated (ActOnLambdaExpr) to prime the current
15566 // LambdaScopeInfo.
15567 // When the template operator is being specialized, the LambdaScopeInfo,
15568 // has to be properly restored so that tryCaptureVariable doesn't try
15569 // and capture any new variables. In addition when calculating potential
15570 // captures during transformation of nested lambdas, it is necessary to
15571 // have the LSI properly restored.
15572 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15573 assert(inTemplateInstantiation() &&
15574 "There should be an active template instantiation on the stack "
15575 "when instantiating a generic lambda!");
15576 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15577 } else {
15578 // Enter a new function scope
15579 PushFunctionScope();
15582 // Builtin functions cannot be defined.
15583 if (unsigned BuiltinID = FD->getBuiltinID()) {
15584 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15585 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15586 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15587 FD->setInvalidDecl();
15591 // The return type of a function definition must be complete (C99 6.9.1p3).
15592 // C++23 [dcl.fct.def.general]/p2
15593 // The type of [...] the return for a function definition
15594 // shall not be a (possibly cv-qualified) class type that is incomplete
15595 // or abstract within the function body unless the function is deleted.
15596 QualType ResultType = FD->getReturnType();
15597 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15598 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15599 (RequireCompleteType(FD->getLocation(), ResultType,
15600 diag::err_func_def_incomplete_result) ||
15601 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15602 diag::err_abstract_type_in_decl,
15603 AbstractReturnType)))
15604 FD->setInvalidDecl();
15606 if (FnBodyScope)
15607 PushDeclContext(FnBodyScope, FD);
15609 // Check the validity of our function parameters
15610 if (BodyKind != FnBodyKind::Delete)
15611 CheckParmsForFunctionDef(FD->parameters(),
15612 /*CheckParameterNames=*/true);
15614 // Add non-parameter declarations already in the function to the current
15615 // scope.
15616 if (FnBodyScope) {
15617 for (Decl *NPD : FD->decls()) {
15618 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15619 if (!NonParmDecl)
15620 continue;
15621 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15622 "parameters should not be in newly created FD yet");
15624 // If the decl has a name, make it accessible in the current scope.
15625 if (NonParmDecl->getDeclName())
15626 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15628 // Similarly, dive into enums and fish their constants out, making them
15629 // accessible in this scope.
15630 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15631 for (auto *EI : ED->enumerators())
15632 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15637 // Introduce our parameters into the function scope
15638 for (auto *Param : FD->parameters()) {
15639 Param->setOwningFunction(FD);
15641 // If this has an identifier, add it to the scope stack.
15642 if (Param->getIdentifier() && FnBodyScope) {
15643 CheckShadow(FnBodyScope, Param);
15645 PushOnScopeChains(Param, FnBodyScope);
15649 // C++ [module.import/6] external definitions are not permitted in header
15650 // units. Deleted and Defaulted functions are implicitly inline (but the
15651 // inline state is not set at this point, so check the BodyKind explicitly).
15652 // FIXME: Consider an alternate location for the test where the inlined()
15653 // state is complete.
15654 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15655 !FD->isInvalidDecl() && !FD->isInlined() &&
15656 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15657 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15658 !FD->isTemplateInstantiation()) {
15659 assert(FD->isThisDeclarationADefinition());
15660 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15661 FD->setInvalidDecl();
15664 // Ensure that the function's exception specification is instantiated.
15665 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15666 ResolveExceptionSpec(D->getLocation(), FPT);
15668 // dllimport cannot be applied to non-inline function definitions.
15669 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15670 !FD->isTemplateInstantiation()) {
15671 assert(!FD->hasAttr<DLLExportAttr>());
15672 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15673 FD->setInvalidDecl();
15674 return D;
15676 // We want to attach documentation to original Decl (which might be
15677 // a function template).
15678 ActOnDocumentableDecl(D);
15679 if (getCurLexicalContext()->isObjCContainer() &&
15680 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15681 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15682 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15684 return D;
15687 /// Given the set of return statements within a function body,
15688 /// compute the variables that are subject to the named return value
15689 /// optimization.
15691 /// Each of the variables that is subject to the named return value
15692 /// optimization will be marked as NRVO variables in the AST, and any
15693 /// return statement that has a marked NRVO variable as its NRVO candidate can
15694 /// use the named return value optimization.
15696 /// This function applies a very simplistic algorithm for NRVO: if every return
15697 /// statement in the scope of a variable has the same NRVO candidate, that
15698 /// candidate is an NRVO variable.
15699 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15700 ReturnStmt **Returns = Scope->Returns.data();
15702 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15703 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15704 if (!NRVOCandidate->isNRVOVariable())
15705 Returns[I]->setNRVOCandidate(nullptr);
15710 bool Sema::canDelayFunctionBody(const Declarator &D) {
15711 // We can't delay parsing the body of a constexpr function template (yet).
15712 if (D.getDeclSpec().hasConstexprSpecifier())
15713 return false;
15715 // We can't delay parsing the body of a function template with a deduced
15716 // return type (yet).
15717 if (D.getDeclSpec().hasAutoTypeSpec()) {
15718 // If the placeholder introduces a non-deduced trailing return type,
15719 // we can still delay parsing it.
15720 if (D.getNumTypeObjects()) {
15721 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15722 if (Outer.Kind == DeclaratorChunk::Function &&
15723 Outer.Fun.hasTrailingReturnType()) {
15724 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15725 return Ty.isNull() || !Ty->isUndeducedType();
15728 return false;
15731 return true;
15734 bool Sema::canSkipFunctionBody(Decl *D) {
15735 // We cannot skip the body of a function (or function template) which is
15736 // constexpr, since we may need to evaluate its body in order to parse the
15737 // rest of the file.
15738 // We cannot skip the body of a function with an undeduced return type,
15739 // because any callers of that function need to know the type.
15740 if (const FunctionDecl *FD = D->getAsFunction()) {
15741 if (FD->isConstexpr())
15742 return false;
15743 // We can't simply call Type::isUndeducedType here, because inside template
15744 // auto can be deduced to a dependent type, which is not considered
15745 // "undeduced".
15746 if (FD->getReturnType()->getContainedDeducedType())
15747 return false;
15749 return Consumer.shouldSkipFunctionBody(D);
15752 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15753 if (!Decl)
15754 return nullptr;
15755 if (FunctionDecl *FD = Decl->getAsFunction())
15756 FD->setHasSkippedBody();
15757 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15758 MD->setHasSkippedBody();
15759 return Decl;
15762 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15763 return ActOnFinishFunctionBody(D, BodyArg, false);
15766 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15767 /// body.
15768 class ExitFunctionBodyRAII {
15769 public:
15770 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15771 ~ExitFunctionBodyRAII() {
15772 if (!IsLambda)
15773 S.PopExpressionEvaluationContext();
15776 private:
15777 Sema &S;
15778 bool IsLambda = false;
15781 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15782 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15784 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15785 if (EscapeInfo.count(BD))
15786 return EscapeInfo[BD];
15788 bool R = false;
15789 const BlockDecl *CurBD = BD;
15791 do {
15792 R = !CurBD->doesNotEscape();
15793 if (R)
15794 break;
15795 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15796 } while (CurBD);
15798 return EscapeInfo[BD] = R;
15801 // If the location where 'self' is implicitly retained is inside a escaping
15802 // block, emit a diagnostic.
15803 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15804 S.ImplicitlyRetainedSelfLocs)
15805 if (IsOrNestedInEscapingBlock(P.second))
15806 S.Diag(P.first, diag::warn_implicitly_retains_self)
15807 << FixItHint::CreateInsertion(P.first, "self->");
15810 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15811 bool IsInstantiation) {
15812 FunctionScopeInfo *FSI = getCurFunction();
15813 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15815 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15816 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15818 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15819 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15821 if (getLangOpts().Coroutines && FSI->isCoroutine())
15822 CheckCompletedCoroutineBody(FD, Body);
15825 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15826 // one is already popped when finishing the lambda in BuildLambdaExpr().
15827 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15828 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15829 if (FD) {
15830 FD->setBody(Body);
15831 FD->setWillHaveBody(false);
15832 CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15834 if (getLangOpts().CPlusPlus14) {
15835 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15836 FD->getReturnType()->isUndeducedType()) {
15837 // For a function with a deduced result type to return void,
15838 // the result type as written must be 'auto' or 'decltype(auto)',
15839 // possibly cv-qualified or constrained, but not ref-qualified.
15840 if (!FD->getReturnType()->getAs<AutoType>()) {
15841 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15842 << FD->getReturnType();
15843 FD->setInvalidDecl();
15844 } else {
15845 // Falling off the end of the function is the same as 'return;'.
15846 Expr *Dummy = nullptr;
15847 if (DeduceFunctionTypeFromReturnExpr(
15848 FD, dcl->getLocation(), Dummy,
15849 FD->getReturnType()->getAs<AutoType>()))
15850 FD->setInvalidDecl();
15853 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15854 // In C++11, we don't use 'auto' deduction rules for lambda call
15855 // operators because we don't support return type deduction.
15856 auto *LSI = getCurLambda();
15857 if (LSI->HasImplicitReturnType) {
15858 deduceClosureReturnType(*LSI);
15860 // C++11 [expr.prim.lambda]p4:
15861 // [...] if there are no return statements in the compound-statement
15862 // [the deduced type is] the type void
15863 QualType RetType =
15864 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15866 // Update the return type to the deduced type.
15867 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15868 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15869 Proto->getExtProtoInfo()));
15873 // If the function implicitly returns zero (like 'main') or is naked,
15874 // don't complain about missing return statements.
15875 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15876 WP.disableCheckFallThrough();
15878 // MSVC permits the use of pure specifier (=0) on function definition,
15879 // defined at class scope, warn about this non-standard construct.
15880 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15881 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15883 if (!FD->isInvalidDecl()) {
15884 // Don't diagnose unused parameters of defaulted, deleted or naked
15885 // functions.
15886 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15887 !FD->hasAttr<NakedAttr>())
15888 DiagnoseUnusedParameters(FD->parameters());
15889 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15890 FD->getReturnType(), FD);
15892 // If this is a structor, we need a vtable.
15893 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15894 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15895 else if (CXXDestructorDecl *Destructor =
15896 dyn_cast<CXXDestructorDecl>(FD))
15897 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15899 // Try to apply the named return value optimization. We have to check
15900 // if we can do this here because lambdas keep return statements around
15901 // to deduce an implicit return type.
15902 if (FD->getReturnType()->isRecordType() &&
15903 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15904 computeNRVO(Body, FSI);
15907 // GNU warning -Wmissing-prototypes:
15908 // Warn if a global function is defined without a previous
15909 // prototype declaration. This warning is issued even if the
15910 // definition itself provides a prototype. The aim is to detect
15911 // global functions that fail to be declared in header files.
15912 const FunctionDecl *PossiblePrototype = nullptr;
15913 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15914 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15916 if (PossiblePrototype) {
15917 // We found a declaration that is not a prototype,
15918 // but that could be a zero-parameter prototype
15919 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15920 TypeLoc TL = TI->getTypeLoc();
15921 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15922 Diag(PossiblePrototype->getLocation(),
15923 diag::note_declaration_not_a_prototype)
15924 << (FD->getNumParams() != 0)
15925 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15926 FTL.getRParenLoc(), "void")
15927 : FixItHint{});
15929 } else {
15930 // Returns true if the token beginning at this Loc is `const`.
15931 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15932 const LangOptions &LangOpts) {
15933 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15934 if (LocInfo.first.isInvalid())
15935 return false;
15937 bool Invalid = false;
15938 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15939 if (Invalid)
15940 return false;
15942 if (LocInfo.second > Buffer.size())
15943 return false;
15945 const char *LexStart = Buffer.data() + LocInfo.second;
15946 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15948 return StartTok.consume_front("const") &&
15949 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15950 StartTok.startswith("/*") || StartTok.startswith("//"));
15953 auto findBeginLoc = [&]() {
15954 // If the return type has `const` qualifier, we want to insert
15955 // `static` before `const` (and not before the typename).
15956 if ((FD->getReturnType()->isAnyPointerType() &&
15957 FD->getReturnType()->getPointeeType().isConstQualified()) ||
15958 FD->getReturnType().isConstQualified()) {
15959 // But only do this if we can determine where the `const` is.
15961 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15962 getLangOpts()))
15964 return FD->getBeginLoc();
15966 return FD->getTypeSpecStartLoc();
15968 Diag(FD->getTypeSpecStartLoc(),
15969 diag::note_static_for_internal_linkage)
15970 << /* function */ 1
15971 << (FD->getStorageClass() == SC_None
15972 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15973 : FixItHint{});
15977 // We might not have found a prototype because we didn't wish to warn on
15978 // the lack of a missing prototype. Try again without the checks for
15979 // whether we want to warn on the missing prototype.
15980 if (!PossiblePrototype)
15981 (void)FindPossiblePrototype(FD, PossiblePrototype);
15983 // If the function being defined does not have a prototype, then we may
15984 // need to diagnose it as changing behavior in C23 because we now know
15985 // whether the function accepts arguments or not. This only handles the
15986 // case where the definition has no prototype but does have parameters
15987 // and either there is no previous potential prototype, or the previous
15988 // potential prototype also has no actual prototype. This handles cases
15989 // like:
15990 // void f(); void f(a) int a; {}
15991 // void g(a) int a; {}
15992 // See MergeFunctionDecl() for other cases of the behavior change
15993 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15994 // type without a prototype.
15995 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15996 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15997 !PossiblePrototype->isImplicit()))) {
15998 // The function definition has parameters, so this will change behavior
15999 // in C23. If there is a possible prototype, it comes before the
16000 // function definition.
16001 // FIXME: The declaration may have already been diagnosed as being
16002 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16003 // there's no way to test for the "changes behavior" condition in
16004 // SemaType.cpp when forming the declaration's function type. So, we do
16005 // this awkward dance instead.
16007 // If we have a possible prototype and it declares a function with a
16008 // prototype, we don't want to diagnose it; if we have a possible
16009 // prototype and it has no prototype, it may have already been
16010 // diagnosed in SemaType.cpp as deprecated depending on whether
16011 // -Wstrict-prototypes is enabled. If we already warned about it being
16012 // deprecated, add a note that it also changes behavior. If we didn't
16013 // warn about it being deprecated (because the diagnostic is not
16014 // enabled), warn now that it is deprecated and changes behavior.
16016 // This K&R C function definition definitely changes behavior in C23,
16017 // so diagnose it.
16018 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16019 << /*definition*/ 1 << /* not supported in C23 */ 0;
16021 // If we have a possible prototype for the function which is a user-
16022 // visible declaration, we already tested that it has no prototype.
16023 // This will change behavior in C23. This gets a warning rather than a
16024 // note because it's the same behavior-changing problem as with the
16025 // definition.
16026 if (PossiblePrototype)
16027 Diag(PossiblePrototype->getLocation(),
16028 diag::warn_non_prototype_changes_behavior)
16029 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16030 << /*definition*/ 1;
16033 // Warn on CPUDispatch with an actual body.
16034 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16035 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16036 if (!CmpndBody->body_empty())
16037 Diag(CmpndBody->body_front()->getBeginLoc(),
16038 diag::warn_dispatch_body_ignored);
16040 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16041 const CXXMethodDecl *KeyFunction;
16042 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16043 MD->isVirtual() &&
16044 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16045 MD == KeyFunction->getCanonicalDecl()) {
16046 // Update the key-function state if necessary for this ABI.
16047 if (FD->isInlined() &&
16048 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16049 Context.setNonKeyFunction(MD);
16051 // If the newly-chosen key function is already defined, then we
16052 // need to mark the vtable as used retroactively.
16053 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16054 const FunctionDecl *Definition;
16055 if (KeyFunction && KeyFunction->isDefined(Definition))
16056 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16057 } else {
16058 // We just defined they key function; mark the vtable as used.
16059 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16064 assert(
16065 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
16066 "Function parsing confused");
16067 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16068 assert(MD == getCurMethodDecl() && "Method parsing confused");
16069 MD->setBody(Body);
16070 if (!MD->isInvalidDecl()) {
16071 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16072 MD->getReturnType(), MD);
16074 if (Body)
16075 computeNRVO(Body, FSI);
16077 if (FSI->ObjCShouldCallSuper) {
16078 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16079 << MD->getSelector().getAsString();
16080 FSI->ObjCShouldCallSuper = false;
16082 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16083 const ObjCMethodDecl *InitMethod = nullptr;
16084 bool isDesignated =
16085 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16086 assert(isDesignated && InitMethod);
16087 (void)isDesignated;
16089 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16090 auto IFace = MD->getClassInterface();
16091 if (!IFace)
16092 return false;
16093 auto SuperD = IFace->getSuperClass();
16094 if (!SuperD)
16095 return false;
16096 return SuperD->getIdentifier() ==
16097 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16099 // Don't issue this warning for unavailable inits or direct subclasses
16100 // of NSObject.
16101 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16102 Diag(MD->getLocation(),
16103 diag::warn_objc_designated_init_missing_super_call);
16104 Diag(InitMethod->getLocation(),
16105 diag::note_objc_designated_init_marked_here);
16107 FSI->ObjCWarnForNoDesignatedInitChain = false;
16109 if (FSI->ObjCWarnForNoInitDelegation) {
16110 // Don't issue this warning for unavaialable inits.
16111 if (!MD->isUnavailable())
16112 Diag(MD->getLocation(),
16113 diag::warn_objc_secondary_init_missing_init_call);
16114 FSI->ObjCWarnForNoInitDelegation = false;
16117 diagnoseImplicitlyRetainedSelf(*this);
16118 } else {
16119 // Parsing the function declaration failed in some way. Pop the fake scope
16120 // we pushed on.
16121 PopFunctionScopeInfo(ActivePolicy, dcl);
16122 return nullptr;
16125 if (Body && FSI->HasPotentialAvailabilityViolations)
16126 DiagnoseUnguardedAvailabilityViolations(dcl);
16128 assert(!FSI->ObjCShouldCallSuper &&
16129 "This should only be set for ObjC methods, which should have been "
16130 "handled in the block above.");
16132 // Verify and clean out per-function state.
16133 if (Body && (!FD || !FD->isDefaulted())) {
16134 // C++ constructors that have function-try-blocks can't have return
16135 // statements in the handlers of that block. (C++ [except.handle]p14)
16136 // Verify this.
16137 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16138 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16140 // Verify that gotos and switch cases don't jump into scopes illegally.
16141 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16142 DiagnoseInvalidJumps(Body);
16144 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16145 if (!Destructor->getParent()->isDependentType())
16146 CheckDestructor(Destructor);
16148 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16149 Destructor->getParent());
16152 // If any errors have occurred, clear out any temporaries that may have
16153 // been leftover. This ensures that these temporaries won't be picked up
16154 // for deletion in some later function.
16155 if (hasUncompilableErrorOccurred() ||
16156 hasAnyUnrecoverableErrorsInThisFunction() ||
16157 getDiagnostics().getSuppressAllDiagnostics()) {
16158 DiscardCleanupsInEvaluationContext();
16160 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16161 // Since the body is valid, issue any analysis-based warnings that are
16162 // enabled.
16163 ActivePolicy = &WP;
16166 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
16167 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16168 FD->setInvalidDecl();
16170 if (FD && FD->hasAttr<NakedAttr>()) {
16171 for (const Stmt *S : Body->children()) {
16172 // Allow local register variables without initializer as they don't
16173 // require prologue.
16174 bool RegisterVariables = false;
16175 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16176 for (const auto *Decl : DS->decls()) {
16177 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16178 RegisterVariables =
16179 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16180 if (!RegisterVariables)
16181 break;
16185 if (RegisterVariables)
16186 continue;
16187 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16188 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16189 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16190 FD->setInvalidDecl();
16191 break;
16196 assert(ExprCleanupObjects.size() ==
16197 ExprEvalContexts.back().NumCleanupObjects &&
16198 "Leftover temporaries in function");
16199 assert(!Cleanup.exprNeedsCleanups() &&
16200 "Unaccounted cleanups in function");
16201 assert(MaybeODRUseExprs.empty() &&
16202 "Leftover expressions for odr-use checking");
16204 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16205 // the declaration context below. Otherwise, we're unable to transform
16206 // 'this' expressions when transforming immediate context functions.
16208 if (!IsInstantiation)
16209 PopDeclContext();
16211 PopFunctionScopeInfo(ActivePolicy, dcl);
16212 // If any errors have occurred, clear out any temporaries that may have
16213 // been leftover. This ensures that these temporaries won't be picked up for
16214 // deletion in some later function.
16215 if (hasUncompilableErrorOccurred()) {
16216 DiscardCleanupsInEvaluationContext();
16219 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16220 !LangOpts.OMPTargetTriples.empty())) ||
16221 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16222 auto ES = getEmissionStatus(FD);
16223 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16224 ES == Sema::FunctionEmissionStatus::Unknown)
16225 DeclsToCheckForDeferredDiags.insert(FD);
16228 if (FD && !FD->isDeleted())
16229 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16231 return dcl;
16234 /// When we finish delayed parsing of an attribute, we must attach it to the
16235 /// relevant Decl.
16236 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16237 ParsedAttributes &Attrs) {
16238 // Always attach attributes to the underlying decl.
16239 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16240 D = TD->getTemplatedDecl();
16241 ProcessDeclAttributeList(S, D, Attrs);
16243 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16244 if (Method->isStatic())
16245 checkThisInStaticMemberFunctionAttributes(Method);
16248 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16249 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16250 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16251 IdentifierInfo &II, Scope *S) {
16252 // It is not valid to implicitly define a function in C23.
16253 assert(LangOpts.implicitFunctionsAllowed() &&
16254 "Implicit function declarations aren't allowed in this language mode");
16256 // Find the scope in which the identifier is injected and the corresponding
16257 // DeclContext.
16258 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16259 // In that case, we inject the declaration into the translation unit scope
16260 // instead.
16261 Scope *BlockScope = S;
16262 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16263 BlockScope = BlockScope->getParent();
16265 // Loop until we find a DeclContext that is either a function/method or the
16266 // translation unit, which are the only two valid places to implicitly define
16267 // a function. This avoids accidentally defining the function within a tag
16268 // declaration, for example.
16269 Scope *ContextScope = BlockScope;
16270 while (!ContextScope->getEntity() ||
16271 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16272 !ContextScope->getEntity()->isTranslationUnit()))
16273 ContextScope = ContextScope->getParent();
16274 ContextRAII SavedContext(*this, ContextScope->getEntity());
16276 // Before we produce a declaration for an implicitly defined
16277 // function, see whether there was a locally-scoped declaration of
16278 // this name as a function or variable. If so, use that
16279 // (non-visible) declaration, and complain about it.
16280 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16281 if (ExternCPrev) {
16282 // We still need to inject the function into the enclosing block scope so
16283 // that later (non-call) uses can see it.
16284 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16286 // C89 footnote 38:
16287 // If in fact it is not defined as having type "function returning int",
16288 // the behavior is undefined.
16289 if (!isa<FunctionDecl>(ExternCPrev) ||
16290 !Context.typesAreCompatible(
16291 cast<FunctionDecl>(ExternCPrev)->getType(),
16292 Context.getFunctionNoProtoType(Context.IntTy))) {
16293 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16294 << ExternCPrev << !getLangOpts().C99;
16295 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16296 return ExternCPrev;
16300 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16301 unsigned diag_id;
16302 if (II.getName().startswith("__builtin_"))
16303 diag_id = diag::warn_builtin_unknown;
16304 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16305 else if (getLangOpts().C99)
16306 diag_id = diag::ext_implicit_function_decl_c99;
16307 else
16308 diag_id = diag::warn_implicit_function_decl;
16310 TypoCorrection Corrected;
16311 // Because typo correction is expensive, only do it if the implicit
16312 // function declaration is going to be treated as an error.
16314 // Perform the correction before issuing the main diagnostic, as some
16315 // consumers use typo-correction callbacks to enhance the main diagnostic.
16316 if (S && !ExternCPrev &&
16317 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16318 DeclFilterCCC<FunctionDecl> CCC{};
16319 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16320 S, nullptr, CCC, CTK_NonError);
16323 Diag(Loc, diag_id) << &II;
16324 if (Corrected) {
16325 // If the correction is going to suggest an implicitly defined function,
16326 // skip the correction as not being a particularly good idea.
16327 bool Diagnose = true;
16328 if (const auto *D = Corrected.getCorrectionDecl())
16329 Diagnose = !D->isImplicit();
16330 if (Diagnose)
16331 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16332 /*ErrorRecovery*/ false);
16335 // If we found a prior declaration of this function, don't bother building
16336 // another one. We've already pushed that one into scope, so there's nothing
16337 // more to do.
16338 if (ExternCPrev)
16339 return ExternCPrev;
16341 // Set a Declarator for the implicit definition: int foo();
16342 const char *Dummy;
16343 AttributeFactory attrFactory;
16344 DeclSpec DS(attrFactory);
16345 unsigned DiagID;
16346 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16347 Context.getPrintingPolicy());
16348 (void)Error; // Silence warning.
16349 assert(!Error && "Error setting up implicit decl!");
16350 SourceLocation NoLoc;
16351 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16352 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16353 /*IsAmbiguous=*/false,
16354 /*LParenLoc=*/NoLoc,
16355 /*Params=*/nullptr,
16356 /*NumParams=*/0,
16357 /*EllipsisLoc=*/NoLoc,
16358 /*RParenLoc=*/NoLoc,
16359 /*RefQualifierIsLvalueRef=*/true,
16360 /*RefQualifierLoc=*/NoLoc,
16361 /*MutableLoc=*/NoLoc, EST_None,
16362 /*ESpecRange=*/SourceRange(),
16363 /*Exceptions=*/nullptr,
16364 /*ExceptionRanges=*/nullptr,
16365 /*NumExceptions=*/0,
16366 /*NoexceptExpr=*/nullptr,
16367 /*ExceptionSpecTokens=*/nullptr,
16368 /*DeclsInPrototype=*/std::nullopt,
16369 Loc, Loc, D),
16370 std::move(DS.getAttributes()), SourceLocation());
16371 D.SetIdentifier(&II, Loc);
16373 // Insert this function into the enclosing block scope.
16374 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16375 FD->setImplicit();
16377 AddKnownFunctionAttributes(FD);
16379 return FD;
16382 /// If this function is a C++ replaceable global allocation function
16383 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16384 /// adds any function attributes that we know a priori based on the standard.
16386 /// We need to check for duplicate attributes both here and where user-written
16387 /// attributes are applied to declarations.
16388 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16389 FunctionDecl *FD) {
16390 if (FD->isInvalidDecl())
16391 return;
16393 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16394 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16395 return;
16397 std::optional<unsigned> AlignmentParam;
16398 bool IsNothrow = false;
16399 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16400 return;
16402 // C++2a [basic.stc.dynamic.allocation]p4:
16403 // An allocation function that has a non-throwing exception specification
16404 // indicates failure by returning a null pointer value. Any other allocation
16405 // function never returns a null pointer value and indicates failure only by
16406 // throwing an exception [...]
16408 // However, -fcheck-new invalidates this possible assumption, so don't add
16409 // NonNull when that is enabled.
16410 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16411 !getLangOpts().CheckNew)
16412 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16414 // C++2a [basic.stc.dynamic.allocation]p2:
16415 // An allocation function attempts to allocate the requested amount of
16416 // storage. [...] If the request succeeds, the value returned by a
16417 // replaceable allocation function is a [...] pointer value p0 different
16418 // from any previously returned value p1 [...]
16420 // However, this particular information is being added in codegen,
16421 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16423 // C++2a [basic.stc.dynamic.allocation]p2:
16424 // An allocation function attempts to allocate the requested amount of
16425 // storage. If it is successful, it returns the address of the start of a
16426 // block of storage whose length in bytes is at least as large as the
16427 // requested size.
16428 if (!FD->hasAttr<AllocSizeAttr>()) {
16429 FD->addAttr(AllocSizeAttr::CreateImplicit(
16430 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16431 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16434 // C++2a [basic.stc.dynamic.allocation]p3:
16435 // For an allocation function [...], the pointer returned on a successful
16436 // call shall represent the address of storage that is aligned as follows:
16437 // (3.1) If the allocation function takes an argument of type
16438 // std​::​align_­val_­t, the storage will have the alignment
16439 // specified by the value of this argument.
16440 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16441 FD->addAttr(AllocAlignAttr::CreateImplicit(
16442 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16445 // FIXME:
16446 // C++2a [basic.stc.dynamic.allocation]p3:
16447 // For an allocation function [...], the pointer returned on a successful
16448 // call shall represent the address of storage that is aligned as follows:
16449 // (3.2) Otherwise, if the allocation function is named operator new[],
16450 // the storage is aligned for any object that does not have
16451 // new-extended alignment ([basic.align]) and is no larger than the
16452 // requested size.
16453 // (3.3) Otherwise, the storage is aligned for any object that does not
16454 // have new-extended alignment and is of the requested size.
16457 /// Adds any function attributes that we know a priori based on
16458 /// the declaration of this function.
16460 /// These attributes can apply both to implicitly-declared builtins
16461 /// (like __builtin___printf_chk) or to library-declared functions
16462 /// like NSLog or printf.
16464 /// We need to check for duplicate attributes both here and where user-written
16465 /// attributes are applied to declarations.
16466 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16467 if (FD->isInvalidDecl())
16468 return;
16470 // If this is a built-in function, map its builtin attributes to
16471 // actual attributes.
16472 if (unsigned BuiltinID = FD->getBuiltinID()) {
16473 // Handle printf-formatting attributes.
16474 unsigned FormatIdx;
16475 bool HasVAListArg;
16476 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16477 if (!FD->hasAttr<FormatAttr>()) {
16478 const char *fmt = "printf";
16479 unsigned int NumParams = FD->getNumParams();
16480 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16481 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16482 fmt = "NSString";
16483 FD->addAttr(FormatAttr::CreateImplicit(Context,
16484 &Context.Idents.get(fmt),
16485 FormatIdx+1,
16486 HasVAListArg ? 0 : FormatIdx+2,
16487 FD->getLocation()));
16490 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16491 HasVAListArg)) {
16492 if (!FD->hasAttr<FormatAttr>())
16493 FD->addAttr(FormatAttr::CreateImplicit(Context,
16494 &Context.Idents.get("scanf"),
16495 FormatIdx+1,
16496 HasVAListArg ? 0 : FormatIdx+2,
16497 FD->getLocation()));
16500 // Handle automatically recognized callbacks.
16501 SmallVector<int, 4> Encoding;
16502 if (!FD->hasAttr<CallbackAttr>() &&
16503 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16504 FD->addAttr(CallbackAttr::CreateImplicit(
16505 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16507 // Mark const if we don't care about errno and/or floating point exceptions
16508 // that are the only thing preventing the function from being const. This
16509 // allows IRgen to use LLVM intrinsics for such functions.
16510 bool NoExceptions =
16511 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16512 bool ConstWithoutErrnoAndExceptions =
16513 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16514 bool ConstWithoutExceptions =
16515 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16516 if (!FD->hasAttr<ConstAttr>() &&
16517 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16518 (!ConstWithoutErrnoAndExceptions ||
16519 (!getLangOpts().MathErrno && NoExceptions)) &&
16520 (!ConstWithoutExceptions || NoExceptions))
16521 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16523 // We make "fma" on GNU or Windows const because we know it does not set
16524 // errno in those environments even though it could set errno based on the
16525 // C standard.
16526 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16527 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16528 !FD->hasAttr<ConstAttr>()) {
16529 switch (BuiltinID) {
16530 case Builtin::BI__builtin_fma:
16531 case Builtin::BI__builtin_fmaf:
16532 case Builtin::BI__builtin_fmal:
16533 case Builtin::BIfma:
16534 case Builtin::BIfmaf:
16535 case Builtin::BIfmal:
16536 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16537 break;
16538 default:
16539 break;
16543 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16544 !FD->hasAttr<ReturnsTwiceAttr>())
16545 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16546 FD->getLocation()));
16547 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16548 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16549 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16550 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16551 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16552 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16553 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16554 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16555 // Add the appropriate attribute, depending on the CUDA compilation mode
16556 // and which target the builtin belongs to. For example, during host
16557 // compilation, aux builtins are __device__, while the rest are __host__.
16558 if (getLangOpts().CUDAIsDevice !=
16559 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16560 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16561 else
16562 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16565 // Add known guaranteed alignment for allocation functions.
16566 switch (BuiltinID) {
16567 case Builtin::BImemalign:
16568 case Builtin::BIaligned_alloc:
16569 if (!FD->hasAttr<AllocAlignAttr>())
16570 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16571 FD->getLocation()));
16572 break;
16573 default:
16574 break;
16577 // Add allocsize attribute for allocation functions.
16578 switch (BuiltinID) {
16579 case Builtin::BIcalloc:
16580 FD->addAttr(AllocSizeAttr::CreateImplicit(
16581 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16582 break;
16583 case Builtin::BImemalign:
16584 case Builtin::BIaligned_alloc:
16585 case Builtin::BIrealloc:
16586 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16587 ParamIdx(), FD->getLocation()));
16588 break;
16589 case Builtin::BImalloc:
16590 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16591 ParamIdx(), FD->getLocation()));
16592 break;
16593 default:
16594 break;
16597 // Add lifetime attribute to std::move, std::fowrard et al.
16598 switch (BuiltinID) {
16599 case Builtin::BIaddressof:
16600 case Builtin::BI__addressof:
16601 case Builtin::BI__builtin_addressof:
16602 case Builtin::BIas_const:
16603 case Builtin::BIforward:
16604 case Builtin::BIforward_like:
16605 case Builtin::BImove:
16606 case Builtin::BImove_if_noexcept:
16607 if (ParmVarDecl *P = FD->getParamDecl(0u);
16608 !P->hasAttr<LifetimeBoundAttr>())
16609 P->addAttr(
16610 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16611 break;
16612 default:
16613 break;
16617 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16619 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16620 // throw, add an implicit nothrow attribute to any extern "C" function we come
16621 // across.
16622 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16623 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16624 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16625 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16626 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16629 IdentifierInfo *Name = FD->getIdentifier();
16630 if (!Name)
16631 return;
16632 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16633 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16634 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16635 LinkageSpecLanguageIDs::C)) {
16636 // Okay: this could be a libc/libm/Objective-C function we know
16637 // about.
16638 } else
16639 return;
16641 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16642 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16643 // target-specific builtins, perhaps?
16644 if (!FD->hasAttr<FormatAttr>())
16645 FD->addAttr(FormatAttr::CreateImplicit(Context,
16646 &Context.Idents.get("printf"), 2,
16647 Name->isStr("vasprintf") ? 0 : 3,
16648 FD->getLocation()));
16651 if (Name->isStr("__CFStringMakeConstantString")) {
16652 // We already have a __builtin___CFStringMakeConstantString,
16653 // but builds that use -fno-constant-cfstrings don't go through that.
16654 if (!FD->hasAttr<FormatArgAttr>())
16655 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16656 FD->getLocation()));
16660 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16661 TypeSourceInfo *TInfo) {
16662 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16663 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16665 if (!TInfo) {
16666 assert(D.isInvalidType() && "no declarator info for valid type");
16667 TInfo = Context.getTrivialTypeSourceInfo(T);
16670 // Scope manipulation handled by caller.
16671 TypedefDecl *NewTD =
16672 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16673 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16675 // Bail out immediately if we have an invalid declaration.
16676 if (D.isInvalidType()) {
16677 NewTD->setInvalidDecl();
16678 return NewTD;
16681 if (D.getDeclSpec().isModulePrivateSpecified()) {
16682 if (CurContext->isFunctionOrMethod())
16683 Diag(NewTD->getLocation(), diag::err_module_private_local)
16684 << 2 << NewTD
16685 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16686 << FixItHint::CreateRemoval(
16687 D.getDeclSpec().getModulePrivateSpecLoc());
16688 else
16689 NewTD->setModulePrivate();
16692 // C++ [dcl.typedef]p8:
16693 // If the typedef declaration defines an unnamed class (or
16694 // enum), the first typedef-name declared by the declaration
16695 // to be that class type (or enum type) is used to denote the
16696 // class type (or enum type) for linkage purposes only.
16697 // We need to check whether the type was declared in the declaration.
16698 switch (D.getDeclSpec().getTypeSpecType()) {
16699 case TST_enum:
16700 case TST_struct:
16701 case TST_interface:
16702 case TST_union:
16703 case TST_class: {
16704 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16705 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16706 break;
16709 default:
16710 break;
16713 return NewTD;
16716 /// Check that this is a valid underlying type for an enum declaration.
16717 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16718 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16719 QualType T = TI->getType();
16721 if (T->isDependentType())
16722 return false;
16724 // This doesn't use 'isIntegralType' despite the error message mentioning
16725 // integral type because isIntegralType would also allow enum types in C.
16726 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16727 if (BT->isInteger())
16728 return false;
16730 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16731 << T << T->isBitIntType();
16734 /// Check whether this is a valid redeclaration of a previous enumeration.
16735 /// \return true if the redeclaration was invalid.
16736 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16737 QualType EnumUnderlyingTy, bool IsFixed,
16738 const EnumDecl *Prev) {
16739 if (IsScoped != Prev->isScoped()) {
16740 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16741 << Prev->isScoped();
16742 Diag(Prev->getLocation(), diag::note_previous_declaration);
16743 return true;
16746 if (IsFixed && Prev->isFixed()) {
16747 if (!EnumUnderlyingTy->isDependentType() &&
16748 !Prev->getIntegerType()->isDependentType() &&
16749 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16750 Prev->getIntegerType())) {
16751 // TODO: Highlight the underlying type of the redeclaration.
16752 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16753 << EnumUnderlyingTy << Prev->getIntegerType();
16754 Diag(Prev->getLocation(), diag::note_previous_declaration)
16755 << Prev->getIntegerTypeRange();
16756 return true;
16758 } else if (IsFixed != Prev->isFixed()) {
16759 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16760 << Prev->isFixed();
16761 Diag(Prev->getLocation(), diag::note_previous_declaration);
16762 return true;
16765 return false;
16768 /// Get diagnostic %select index for tag kind for
16769 /// redeclaration diagnostic message.
16770 /// WARNING: Indexes apply to particular diagnostics only!
16772 /// \returns diagnostic %select index.
16773 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16774 switch (Tag) {
16775 case TagTypeKind::Struct:
16776 return 0;
16777 case TagTypeKind::Interface:
16778 return 1;
16779 case TagTypeKind::Class:
16780 return 2;
16781 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16785 /// Determine if tag kind is a class-key compatible with
16786 /// class for redeclaration (class, struct, or __interface).
16788 /// \returns true iff the tag kind is compatible.
16789 static bool isClassCompatTagKind(TagTypeKind Tag)
16791 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16792 Tag == TagTypeKind::Interface;
16795 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16796 TagTypeKind TTK) {
16797 if (isa<TypedefDecl>(PrevDecl))
16798 return NTK_Typedef;
16799 else if (isa<TypeAliasDecl>(PrevDecl))
16800 return NTK_TypeAlias;
16801 else if (isa<ClassTemplateDecl>(PrevDecl))
16802 return NTK_Template;
16803 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16804 return NTK_TypeAliasTemplate;
16805 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16806 return NTK_TemplateTemplateArgument;
16807 switch (TTK) {
16808 case TagTypeKind::Struct:
16809 case TagTypeKind::Interface:
16810 case TagTypeKind::Class:
16811 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16812 case TagTypeKind::Union:
16813 return NTK_NonUnion;
16814 case TagTypeKind::Enum:
16815 return NTK_NonEnum;
16817 llvm_unreachable("invalid TTK");
16820 /// Determine whether a tag with a given kind is acceptable
16821 /// as a redeclaration of the given tag declaration.
16823 /// \returns true if the new tag kind is acceptable, false otherwise.
16824 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16825 TagTypeKind NewTag, bool isDefinition,
16826 SourceLocation NewTagLoc,
16827 const IdentifierInfo *Name) {
16828 // C++ [dcl.type.elab]p3:
16829 // The class-key or enum keyword present in the
16830 // elaborated-type-specifier shall agree in kind with the
16831 // declaration to which the name in the elaborated-type-specifier
16832 // refers. This rule also applies to the form of
16833 // elaborated-type-specifier that declares a class-name or
16834 // friend class since it can be construed as referring to the
16835 // definition of the class. Thus, in any
16836 // elaborated-type-specifier, the enum keyword shall be used to
16837 // refer to an enumeration (7.2), the union class-key shall be
16838 // used to refer to a union (clause 9), and either the class or
16839 // struct class-key shall be used to refer to a class (clause 9)
16840 // declared using the class or struct class-key.
16841 TagTypeKind OldTag = Previous->getTagKind();
16842 if (OldTag != NewTag &&
16843 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16844 return false;
16846 // Tags are compatible, but we might still want to warn on mismatched tags.
16847 // Non-class tags can't be mismatched at this point.
16848 if (!isClassCompatTagKind(NewTag))
16849 return true;
16851 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16852 // by our warning analysis. We don't want to warn about mismatches with (eg)
16853 // declarations in system headers that are designed to be specialized, but if
16854 // a user asks us to warn, we should warn if their code contains mismatched
16855 // declarations.
16856 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16857 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16858 Loc);
16860 if (IsIgnoredLoc(NewTagLoc))
16861 return true;
16863 auto IsIgnored = [&](const TagDecl *Tag) {
16864 return IsIgnoredLoc(Tag->getLocation());
16866 while (IsIgnored(Previous)) {
16867 Previous = Previous->getPreviousDecl();
16868 if (!Previous)
16869 return true;
16870 OldTag = Previous->getTagKind();
16873 bool isTemplate = false;
16874 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16875 isTemplate = Record->getDescribedClassTemplate();
16877 if (inTemplateInstantiation()) {
16878 if (OldTag != NewTag) {
16879 // In a template instantiation, do not offer fix-its for tag mismatches
16880 // since they usually mess up the template instead of fixing the problem.
16881 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16882 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16883 << getRedeclDiagFromTagKind(OldTag);
16884 // FIXME: Note previous location?
16886 return true;
16889 if (isDefinition) {
16890 // On definitions, check all previous tags and issue a fix-it for each
16891 // one that doesn't match the current tag.
16892 if (Previous->getDefinition()) {
16893 // Don't suggest fix-its for redefinitions.
16894 return true;
16897 bool previousMismatch = false;
16898 for (const TagDecl *I : Previous->redecls()) {
16899 if (I->getTagKind() != NewTag) {
16900 // Ignore previous declarations for which the warning was disabled.
16901 if (IsIgnored(I))
16902 continue;
16904 if (!previousMismatch) {
16905 previousMismatch = true;
16906 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16907 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16908 << getRedeclDiagFromTagKind(I->getTagKind());
16910 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16911 << getRedeclDiagFromTagKind(NewTag)
16912 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16913 TypeWithKeyword::getTagTypeKindName(NewTag));
16916 return true;
16919 // Identify the prevailing tag kind: this is the kind of the definition (if
16920 // there is a non-ignored definition), or otherwise the kind of the prior
16921 // (non-ignored) declaration.
16922 const TagDecl *PrevDef = Previous->getDefinition();
16923 if (PrevDef && IsIgnored(PrevDef))
16924 PrevDef = nullptr;
16925 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16926 if (Redecl->getTagKind() != NewTag) {
16927 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16928 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16929 << getRedeclDiagFromTagKind(OldTag);
16930 Diag(Redecl->getLocation(), diag::note_previous_use);
16932 // If there is a previous definition, suggest a fix-it.
16933 if (PrevDef) {
16934 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16935 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16936 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16937 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16941 return true;
16944 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16945 /// from an outer enclosing namespace or file scope inside a friend declaration.
16946 /// This should provide the commented out code in the following snippet:
16947 /// namespace N {
16948 /// struct X;
16949 /// namespace M {
16950 /// struct Y { friend struct /*N::*/ X; };
16951 /// }
16952 /// }
16953 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16954 SourceLocation NameLoc) {
16955 // While the decl is in a namespace, do repeated lookup of that name and see
16956 // if we get the same namespace back. If we do not, continue until
16957 // translation unit scope, at which point we have a fully qualified NNS.
16958 SmallVector<IdentifierInfo *, 4> Namespaces;
16959 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16960 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16961 // This tag should be declared in a namespace, which can only be enclosed by
16962 // other namespaces. Bail if there's an anonymous namespace in the chain.
16963 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16964 if (!Namespace || Namespace->isAnonymousNamespace())
16965 return FixItHint();
16966 IdentifierInfo *II = Namespace->getIdentifier();
16967 Namespaces.push_back(II);
16968 NamedDecl *Lookup = SemaRef.LookupSingleName(
16969 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16970 if (Lookup == Namespace)
16971 break;
16974 // Once we have all the namespaces, reverse them to go outermost first, and
16975 // build an NNS.
16976 SmallString<64> Insertion;
16977 llvm::raw_svector_ostream OS(Insertion);
16978 if (DC->isTranslationUnit())
16979 OS << "::";
16980 std::reverse(Namespaces.begin(), Namespaces.end());
16981 for (auto *II : Namespaces)
16982 OS << II->getName() << "::";
16983 return FixItHint::CreateInsertion(NameLoc, Insertion);
16986 /// Determine whether a tag originally declared in context \p OldDC can
16987 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16988 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16989 /// using-declaration).
16990 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16991 DeclContext *NewDC) {
16992 OldDC = OldDC->getRedeclContext();
16993 NewDC = NewDC->getRedeclContext();
16995 if (OldDC->Equals(NewDC))
16996 return true;
16998 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16999 // encloses the other).
17000 if (S.getLangOpts().MSVCCompat &&
17001 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17002 return true;
17004 return false;
17007 /// This is invoked when we see 'struct foo' or 'struct {'. In the
17008 /// former case, Name will be non-null. In the later case, Name will be null.
17009 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17010 /// reference/declaration/definition of a tag.
17012 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
17013 /// trailing-type-specifier) other than one in an alias-declaration.
17015 /// \param SkipBody If non-null, will be set to indicate if the caller should
17016 /// skip the definition of this tag and treat it as if it were a declaration.
17017 DeclResult
17018 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17019 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17020 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17021 SourceLocation ModulePrivateLoc,
17022 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17023 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17024 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17025 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17026 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17027 // If this is not a definition, it must have a name.
17028 IdentifierInfo *OrigName = Name;
17029 assert((Name != nullptr || TUK == TUK_Definition) &&
17030 "Nameless record must be a definition!");
17031 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17033 OwnedDecl = false;
17034 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17035 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17037 // FIXME: Check member specializations more carefully.
17038 bool isMemberSpecialization = false;
17039 bool Invalid = false;
17041 // We only need to do this matching if we have template parameters
17042 // or a scope specifier, which also conveniently avoids this work
17043 // for non-C++ cases.
17044 if (TemplateParameterLists.size() > 0 ||
17045 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17046 if (TemplateParameterList *TemplateParams =
17047 MatchTemplateParametersToScopeSpecifier(
17048 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17049 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
17050 if (Kind == TagTypeKind::Enum) {
17051 Diag(KWLoc, diag::err_enum_template);
17052 return true;
17055 if (TemplateParams->size() > 0) {
17056 // This is a declaration or definition of a class template (which may
17057 // be a member of another template).
17059 if (Invalid)
17060 return true;
17062 OwnedDecl = false;
17063 DeclResult Result = CheckClassTemplate(
17064 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17065 AS, ModulePrivateLoc,
17066 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17067 TemplateParameterLists.data(), SkipBody);
17068 return Result.get();
17069 } else {
17070 // The "template<>" header is extraneous.
17071 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17072 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17073 isMemberSpecialization = true;
17077 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17078 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17079 return true;
17082 // Figure out the underlying type if this a enum declaration. We need to do
17083 // this early, because it's needed to detect if this is an incompatible
17084 // redeclaration.
17085 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17086 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17088 if (Kind == TagTypeKind::Enum) {
17089 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17090 // No underlying type explicitly specified, or we failed to parse the
17091 // type, default to int.
17092 EnumUnderlying = Context.IntTy.getTypePtr();
17093 } else if (UnderlyingType.get()) {
17094 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17095 // integral type; any cv-qualification is ignored.
17096 TypeSourceInfo *TI = nullptr;
17097 GetTypeFromParser(UnderlyingType.get(), &TI);
17098 EnumUnderlying = TI;
17100 if (CheckEnumUnderlyingType(TI))
17101 // Recover by falling back to int.
17102 EnumUnderlying = Context.IntTy.getTypePtr();
17104 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17105 UPPC_FixedUnderlyingType))
17106 EnumUnderlying = Context.IntTy.getTypePtr();
17108 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17109 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17110 // of 'int'. However, if this is an unfixed forward declaration, don't set
17111 // the underlying type unless the user enables -fms-compatibility. This
17112 // makes unfixed forward declared enums incomplete and is more conforming.
17113 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17114 EnumUnderlying = Context.IntTy.getTypePtr();
17118 DeclContext *SearchDC = CurContext;
17119 DeclContext *DC = CurContext;
17120 bool isStdBadAlloc = false;
17121 bool isStdAlignValT = false;
17123 RedeclarationKind Redecl = forRedeclarationInCurContext();
17124 if (TUK == TUK_Friend || TUK == TUK_Reference)
17125 Redecl = NotForRedeclaration;
17127 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17128 /// implemented asks for structural equivalence checking, the returned decl
17129 /// here is passed back to the parser, allowing the tag body to be parsed.
17130 auto createTagFromNewDecl = [&]() -> TagDecl * {
17131 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17132 // If there is an identifier, use the location of the identifier as the
17133 // location of the decl, otherwise use the location of the struct/union
17134 // keyword.
17135 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17136 TagDecl *New = nullptr;
17138 if (Kind == TagTypeKind::Enum) {
17139 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17140 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17141 // If this is an undefined enum, bail.
17142 if (TUK != TUK_Definition && !Invalid)
17143 return nullptr;
17144 if (EnumUnderlying) {
17145 EnumDecl *ED = cast<EnumDecl>(New);
17146 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17147 ED->setIntegerTypeSourceInfo(TI);
17148 else
17149 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17150 QualType EnumTy = ED->getIntegerType();
17151 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17152 ? Context.getPromotedIntegerType(EnumTy)
17153 : EnumTy);
17155 } else { // struct/union
17156 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17157 nullptr);
17160 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17161 // Add alignment attributes if necessary; these attributes are checked
17162 // when the ASTContext lays out the structure.
17164 // It is important for implementing the correct semantics that this
17165 // happen here (in ActOnTag). The #pragma pack stack is
17166 // maintained as a result of parser callbacks which can occur at
17167 // many points during the parsing of a struct declaration (because
17168 // the #pragma tokens are effectively skipped over during the
17169 // parsing of the struct).
17170 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17171 AddAlignmentAttributesForRecord(RD);
17172 AddMsStructLayoutForRecord(RD);
17175 New->setLexicalDeclContext(CurContext);
17176 return New;
17179 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17180 if (Name && SS.isNotEmpty()) {
17181 // We have a nested-name tag ('struct foo::bar').
17183 // Check for invalid 'foo::'.
17184 if (SS.isInvalid()) {
17185 Name = nullptr;
17186 goto CreateNewDecl;
17189 // If this is a friend or a reference to a class in a dependent
17190 // context, don't try to make a decl for it.
17191 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17192 DC = computeDeclContext(SS, false);
17193 if (!DC) {
17194 IsDependent = true;
17195 return true;
17197 } else {
17198 DC = computeDeclContext(SS, true);
17199 if (!DC) {
17200 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17201 << SS.getRange();
17202 return true;
17206 if (RequireCompleteDeclContext(SS, DC))
17207 return true;
17209 SearchDC = DC;
17210 // Look-up name inside 'foo::'.
17211 LookupQualifiedName(Previous, DC);
17213 if (Previous.isAmbiguous())
17214 return true;
17216 if (Previous.empty()) {
17217 // Name lookup did not find anything. However, if the
17218 // nested-name-specifier refers to the current instantiation,
17219 // and that current instantiation has any dependent base
17220 // classes, we might find something at instantiation time: treat
17221 // this as a dependent elaborated-type-specifier.
17222 // But this only makes any sense for reference-like lookups.
17223 if (Previous.wasNotFoundInCurrentInstantiation() &&
17224 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17225 IsDependent = true;
17226 return true;
17229 // A tag 'foo::bar' must already exist.
17230 Diag(NameLoc, diag::err_not_tag_in_scope)
17231 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17232 Name = nullptr;
17233 Invalid = true;
17234 goto CreateNewDecl;
17236 } else if (Name) {
17237 // C++14 [class.mem]p14:
17238 // If T is the name of a class, then each of the following shall have a
17239 // name different from T:
17240 // -- every member of class T that is itself a type
17241 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17242 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17243 return true;
17245 // If this is a named struct, check to see if there was a previous forward
17246 // declaration or definition.
17247 // FIXME: We're looking into outer scopes here, even when we
17248 // shouldn't be. Doing so can result in ambiguities that we
17249 // shouldn't be diagnosing.
17250 LookupName(Previous, S);
17252 // When declaring or defining a tag, ignore ambiguities introduced
17253 // by types using'ed into this scope.
17254 if (Previous.isAmbiguous() &&
17255 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17256 LookupResult::Filter F = Previous.makeFilter();
17257 while (F.hasNext()) {
17258 NamedDecl *ND = F.next();
17259 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17260 SearchDC->getRedeclContext()))
17261 F.erase();
17263 F.done();
17266 // C++11 [namespace.memdef]p3:
17267 // If the name in a friend declaration is neither qualified nor
17268 // a template-id and the declaration is a function or an
17269 // elaborated-type-specifier, the lookup to determine whether
17270 // the entity has been previously declared shall not consider
17271 // any scopes outside the innermost enclosing namespace.
17273 // MSVC doesn't implement the above rule for types, so a friend tag
17274 // declaration may be a redeclaration of a type declared in an enclosing
17275 // scope. They do implement this rule for friend functions.
17277 // Does it matter that this should be by scope instead of by
17278 // semantic context?
17279 if (!Previous.empty() && TUK == TUK_Friend) {
17280 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17281 LookupResult::Filter F = Previous.makeFilter();
17282 bool FriendSawTagOutsideEnclosingNamespace = false;
17283 while (F.hasNext()) {
17284 NamedDecl *ND = F.next();
17285 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17286 if (DC->isFileContext() &&
17287 !EnclosingNS->Encloses(ND->getDeclContext())) {
17288 if (getLangOpts().MSVCCompat)
17289 FriendSawTagOutsideEnclosingNamespace = true;
17290 else
17291 F.erase();
17294 F.done();
17296 // Diagnose this MSVC extension in the easy case where lookup would have
17297 // unambiguously found something outside the enclosing namespace.
17298 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17299 NamedDecl *ND = Previous.getFoundDecl();
17300 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17301 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17305 // Note: there used to be some attempt at recovery here.
17306 if (Previous.isAmbiguous())
17307 return true;
17309 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17310 // FIXME: This makes sure that we ignore the contexts associated
17311 // with C structs, unions, and enums when looking for a matching
17312 // tag declaration or definition. See the similar lookup tweak
17313 // in Sema::LookupName; is there a better way to deal with this?
17314 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17315 SearchDC = SearchDC->getParent();
17316 } else if (getLangOpts().CPlusPlus) {
17317 // Inside ObjCContainer want to keep it as a lexical decl context but go
17318 // past it (most often to TranslationUnit) to find the semantic decl
17319 // context.
17320 while (isa<ObjCContainerDecl>(SearchDC))
17321 SearchDC = SearchDC->getParent();
17323 } else if (getLangOpts().CPlusPlus) {
17324 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17325 // TagDecl the same way as we skip it for named TagDecl.
17326 while (isa<ObjCContainerDecl>(SearchDC))
17327 SearchDC = SearchDC->getParent();
17330 if (Previous.isSingleResult() &&
17331 Previous.getFoundDecl()->isTemplateParameter()) {
17332 // Maybe we will complain about the shadowed template parameter.
17333 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17334 // Just pretend that we didn't see the previous declaration.
17335 Previous.clear();
17338 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17339 DC->Equals(getStdNamespace())) {
17340 if (Name->isStr("bad_alloc")) {
17341 // This is a declaration of or a reference to "std::bad_alloc".
17342 isStdBadAlloc = true;
17344 // If std::bad_alloc has been implicitly declared (but made invisible to
17345 // name lookup), fill in this implicit declaration as the previous
17346 // declaration, so that the declarations get chained appropriately.
17347 if (Previous.empty() && StdBadAlloc)
17348 Previous.addDecl(getStdBadAlloc());
17349 } else if (Name->isStr("align_val_t")) {
17350 isStdAlignValT = true;
17351 if (Previous.empty() && StdAlignValT)
17352 Previous.addDecl(getStdAlignValT());
17356 // If we didn't find a previous declaration, and this is a reference
17357 // (or friend reference), move to the correct scope. In C++, we
17358 // also need to do a redeclaration lookup there, just in case
17359 // there's a shadow friend decl.
17360 if (Name && Previous.empty() &&
17361 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17362 if (Invalid) goto CreateNewDecl;
17363 assert(SS.isEmpty());
17365 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17366 // C++ [basic.scope.pdecl]p5:
17367 // -- for an elaborated-type-specifier of the form
17369 // class-key identifier
17371 // if the elaborated-type-specifier is used in the
17372 // decl-specifier-seq or parameter-declaration-clause of a
17373 // function defined in namespace scope, the identifier is
17374 // declared as a class-name in the namespace that contains
17375 // the declaration; otherwise, except as a friend
17376 // declaration, the identifier is declared in the smallest
17377 // non-class, non-function-prototype scope that contains the
17378 // declaration.
17380 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17381 // C structs and unions.
17383 // It is an error in C++ to declare (rather than define) an enum
17384 // type, including via an elaborated type specifier. We'll
17385 // diagnose that later; for now, declare the enum in the same
17386 // scope as we would have picked for any other tag type.
17388 // GNU C also supports this behavior as part of its incomplete
17389 // enum types extension, while GNU C++ does not.
17391 // Find the context where we'll be declaring the tag.
17392 // FIXME: We would like to maintain the current DeclContext as the
17393 // lexical context,
17394 SearchDC = getTagInjectionContext(SearchDC);
17396 // Find the scope where we'll be declaring the tag.
17397 S = getTagInjectionScope(S, getLangOpts());
17398 } else {
17399 assert(TUK == TUK_Friend);
17400 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17402 // C++ [namespace.memdef]p3:
17403 // If a friend declaration in a non-local class first declares a
17404 // class or function, the friend class or function is a member of
17405 // the innermost enclosing namespace.
17406 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17407 : SearchDC->getEnclosingNamespaceContext();
17410 // In C++, we need to do a redeclaration lookup to properly
17411 // diagnose some problems.
17412 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17413 // hidden declaration so that we don't get ambiguity errors when using a
17414 // type declared by an elaborated-type-specifier. In C that is not correct
17415 // and we should instead merge compatible types found by lookup.
17416 if (getLangOpts().CPlusPlus) {
17417 // FIXME: This can perform qualified lookups into function contexts,
17418 // which are meaningless.
17419 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17420 LookupQualifiedName(Previous, SearchDC);
17421 } else {
17422 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17423 LookupName(Previous, S);
17427 // If we have a known previous declaration to use, then use it.
17428 if (Previous.empty() && SkipBody && SkipBody->Previous)
17429 Previous.addDecl(SkipBody->Previous);
17431 if (!Previous.empty()) {
17432 NamedDecl *PrevDecl = Previous.getFoundDecl();
17433 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17435 // It's okay to have a tag decl in the same scope as a typedef
17436 // which hides a tag decl in the same scope. Finding this
17437 // with a redeclaration lookup can only actually happen in C++.
17439 // This is also okay for elaborated-type-specifiers, which is
17440 // technically forbidden by the current standard but which is
17441 // okay according to the likely resolution of an open issue;
17442 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17443 if (getLangOpts().CPlusPlus) {
17444 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17445 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17446 TagDecl *Tag = TT->getDecl();
17447 if (Tag->getDeclName() == Name &&
17448 Tag->getDeclContext()->getRedeclContext()
17449 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17450 PrevDecl = Tag;
17451 Previous.clear();
17452 Previous.addDecl(Tag);
17453 Previous.resolveKind();
17459 // If this is a redeclaration of a using shadow declaration, it must
17460 // declare a tag in the same context. In MSVC mode, we allow a
17461 // redefinition if either context is within the other.
17462 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17463 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17464 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17465 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17466 !(OldTag && isAcceptableTagRedeclContext(
17467 *this, OldTag->getDeclContext(), SearchDC))) {
17468 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17469 Diag(Shadow->getTargetDecl()->getLocation(),
17470 diag::note_using_decl_target);
17471 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17472 << 0;
17473 // Recover by ignoring the old declaration.
17474 Previous.clear();
17475 goto CreateNewDecl;
17479 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17480 // If this is a use of a previous tag, or if the tag is already declared
17481 // in the same scope (so that the definition/declaration completes or
17482 // rementions the tag), reuse the decl.
17483 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17484 isDeclInScope(DirectPrevDecl, SearchDC, S,
17485 SS.isNotEmpty() || isMemberSpecialization)) {
17486 // Make sure that this wasn't declared as an enum and now used as a
17487 // struct or something similar.
17488 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17489 TUK == TUK_Definition, KWLoc,
17490 Name)) {
17491 bool SafeToContinue =
17492 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17493 Kind != TagTypeKind::Enum);
17494 if (SafeToContinue)
17495 Diag(KWLoc, diag::err_use_with_wrong_tag)
17496 << Name
17497 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17498 PrevTagDecl->getKindName());
17499 else
17500 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17501 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17503 if (SafeToContinue)
17504 Kind = PrevTagDecl->getTagKind();
17505 else {
17506 // Recover by making this an anonymous redefinition.
17507 Name = nullptr;
17508 Previous.clear();
17509 Invalid = true;
17513 if (Kind == TagTypeKind::Enum &&
17514 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17515 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17516 if (TUK == TUK_Reference || TUK == TUK_Friend)
17517 return PrevTagDecl;
17519 QualType EnumUnderlyingTy;
17520 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17521 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17522 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17523 EnumUnderlyingTy = QualType(T, 0);
17525 // All conflicts with previous declarations are recovered by
17526 // returning the previous declaration, unless this is a definition,
17527 // in which case we want the caller to bail out.
17528 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17529 ScopedEnum, EnumUnderlyingTy,
17530 IsFixed, PrevEnum))
17531 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17534 // C++11 [class.mem]p1:
17535 // A member shall not be declared twice in the member-specification,
17536 // except that a nested class or member class template can be declared
17537 // and then later defined.
17538 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17539 S->isDeclScope(PrevDecl)) {
17540 Diag(NameLoc, diag::ext_member_redeclared);
17541 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17544 if (!Invalid) {
17545 // If this is a use, just return the declaration we found, unless
17546 // we have attributes.
17547 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17548 if (!Attrs.empty()) {
17549 // FIXME: Diagnose these attributes. For now, we create a new
17550 // declaration to hold them.
17551 } else if (TUK == TUK_Reference &&
17552 (PrevTagDecl->getFriendObjectKind() ==
17553 Decl::FOK_Undeclared ||
17554 PrevDecl->getOwningModule() != getCurrentModule()) &&
17555 SS.isEmpty()) {
17556 // This declaration is a reference to an existing entity, but
17557 // has different visibility from that entity: it either makes
17558 // a friend visible or it makes a type visible in a new module.
17559 // In either case, create a new declaration. We only do this if
17560 // the declaration would have meant the same thing if no prior
17561 // declaration were found, that is, if it was found in the same
17562 // scope where we would have injected a declaration.
17563 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17564 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17565 return PrevTagDecl;
17566 // This is in the injected scope, create a new declaration in
17567 // that scope.
17568 S = getTagInjectionScope(S, getLangOpts());
17569 } else {
17570 return PrevTagDecl;
17574 // Diagnose attempts to redefine a tag.
17575 if (TUK == TUK_Definition) {
17576 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17577 // If we're defining a specialization and the previous definition
17578 // is from an implicit instantiation, don't emit an error
17579 // here; we'll catch this in the general case below.
17580 bool IsExplicitSpecializationAfterInstantiation = false;
17581 if (isMemberSpecialization) {
17582 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17583 IsExplicitSpecializationAfterInstantiation =
17584 RD->getTemplateSpecializationKind() !=
17585 TSK_ExplicitSpecialization;
17586 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17587 IsExplicitSpecializationAfterInstantiation =
17588 ED->getTemplateSpecializationKind() !=
17589 TSK_ExplicitSpecialization;
17592 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17593 // not keep more that one definition around (merge them). However,
17594 // ensure the decl passes the structural compatibility check in
17595 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17596 NamedDecl *Hidden = nullptr;
17597 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17598 // There is a definition of this tag, but it is not visible. We
17599 // explicitly make use of C++'s one definition rule here, and
17600 // assume that this definition is identical to the hidden one
17601 // we already have. Make the existing definition visible and
17602 // use it in place of this one.
17603 if (!getLangOpts().CPlusPlus) {
17604 // Postpone making the old definition visible until after we
17605 // complete parsing the new one and do the structural
17606 // comparison.
17607 SkipBody->CheckSameAsPrevious = true;
17608 SkipBody->New = createTagFromNewDecl();
17609 SkipBody->Previous = Def;
17610 return Def;
17611 } else {
17612 SkipBody->ShouldSkip = true;
17613 SkipBody->Previous = Def;
17614 makeMergedDefinitionVisible(Hidden);
17615 // Carry on and handle it like a normal definition. We'll
17616 // skip starting the definitiion later.
17618 } else if (!IsExplicitSpecializationAfterInstantiation) {
17619 // A redeclaration in function prototype scope in C isn't
17620 // visible elsewhere, so merely issue a warning.
17621 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17622 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17623 else
17624 Diag(NameLoc, diag::err_redefinition) << Name;
17625 notePreviousDefinition(Def,
17626 NameLoc.isValid() ? NameLoc : KWLoc);
17627 // If this is a redefinition, recover by making this
17628 // struct be anonymous, which will make any later
17629 // references get the previous definition.
17630 Name = nullptr;
17631 Previous.clear();
17632 Invalid = true;
17634 } else {
17635 // If the type is currently being defined, complain
17636 // about a nested redefinition.
17637 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17638 if (TD->isBeingDefined()) {
17639 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17640 Diag(PrevTagDecl->getLocation(),
17641 diag::note_previous_definition);
17642 Name = nullptr;
17643 Previous.clear();
17644 Invalid = true;
17648 // Okay, this is definition of a previously declared or referenced
17649 // tag. We're going to create a new Decl for it.
17652 // Okay, we're going to make a redeclaration. If this is some kind
17653 // of reference, make sure we build the redeclaration in the same DC
17654 // as the original, and ignore the current access specifier.
17655 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17656 SearchDC = PrevTagDecl->getDeclContext();
17657 AS = AS_none;
17660 // If we get here we have (another) forward declaration or we
17661 // have a definition. Just create a new decl.
17663 } else {
17664 // If we get here, this is a definition of a new tag type in a nested
17665 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17666 // new decl/type. We set PrevDecl to NULL so that the entities
17667 // have distinct types.
17668 Previous.clear();
17670 // If we get here, we're going to create a new Decl. If PrevDecl
17671 // is non-NULL, it's a definition of the tag declared by
17672 // PrevDecl. If it's NULL, we have a new definition.
17674 // Otherwise, PrevDecl is not a tag, but was found with tag
17675 // lookup. This is only actually possible in C++, where a few
17676 // things like templates still live in the tag namespace.
17677 } else {
17678 // Use a better diagnostic if an elaborated-type-specifier
17679 // found the wrong kind of type on the first
17680 // (non-redeclaration) lookup.
17681 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17682 !Previous.isForRedeclaration()) {
17683 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17684 Diag(NameLoc, diag::err_tag_reference_non_tag)
17685 << PrevDecl << NTK << llvm::to_underlying(Kind);
17686 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17687 Invalid = true;
17689 // Otherwise, only diagnose if the declaration is in scope.
17690 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17691 SS.isNotEmpty() || isMemberSpecialization)) {
17692 // do nothing
17694 // Diagnose implicit declarations introduced by elaborated types.
17695 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17696 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17697 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17698 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17699 Invalid = true;
17701 // Otherwise it's a declaration. Call out a particularly common
17702 // case here.
17703 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17704 unsigned Kind = 0;
17705 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17706 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17707 << Name << Kind << TND->getUnderlyingType();
17708 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17709 Invalid = true;
17711 // Otherwise, diagnose.
17712 } else {
17713 // The tag name clashes with something else in the target scope,
17714 // issue an error and recover by making this tag be anonymous.
17715 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17716 notePreviousDefinition(PrevDecl, NameLoc);
17717 Name = nullptr;
17718 Invalid = true;
17721 // The existing declaration isn't relevant to us; we're in a
17722 // new scope, so clear out the previous declaration.
17723 Previous.clear();
17727 CreateNewDecl:
17729 TagDecl *PrevDecl = nullptr;
17730 if (Previous.isSingleResult())
17731 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17733 // If there is an identifier, use the location of the identifier as the
17734 // location of the decl, otherwise use the location of the struct/union
17735 // keyword.
17736 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17738 // Otherwise, create a new declaration. If there is a previous
17739 // declaration of the same entity, the two will be linked via
17740 // PrevDecl.
17741 TagDecl *New;
17743 if (Kind == TagTypeKind::Enum) {
17744 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17745 // enum X { A, B, C } D; D should chain to X.
17746 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17747 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17748 ScopedEnumUsesClassTag, IsFixed);
17750 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17751 StdAlignValT = cast<EnumDecl>(New);
17753 // If this is an undefined enum, warn.
17754 if (TUK != TUK_Definition && !Invalid) {
17755 TagDecl *Def;
17756 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17757 // C++0x: 7.2p2: opaque-enum-declaration.
17758 // Conflicts are diagnosed above. Do nothing.
17760 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17761 Diag(Loc, diag::ext_forward_ref_enum_def)
17762 << New;
17763 Diag(Def->getLocation(), diag::note_previous_definition);
17764 } else {
17765 unsigned DiagID = diag::ext_forward_ref_enum;
17766 if (getLangOpts().MSVCCompat)
17767 DiagID = diag::ext_ms_forward_ref_enum;
17768 else if (getLangOpts().CPlusPlus)
17769 DiagID = diag::err_forward_ref_enum;
17770 Diag(Loc, DiagID);
17774 if (EnumUnderlying) {
17775 EnumDecl *ED = cast<EnumDecl>(New);
17776 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17777 ED->setIntegerTypeSourceInfo(TI);
17778 else
17779 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17780 QualType EnumTy = ED->getIntegerType();
17781 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17782 ? Context.getPromotedIntegerType(EnumTy)
17783 : EnumTy);
17784 assert(ED->isComplete() && "enum with type should be complete");
17786 } else {
17787 // struct/union/class
17789 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17790 // struct X { int A; } D; D should chain to X.
17791 if (getLangOpts().CPlusPlus) {
17792 // FIXME: Look for a way to use RecordDecl for simple structs.
17793 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17794 cast_or_null<CXXRecordDecl>(PrevDecl));
17796 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17797 StdBadAlloc = cast<CXXRecordDecl>(New);
17798 } else
17799 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17800 cast_or_null<RecordDecl>(PrevDecl));
17803 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17804 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17805 << (OOK == OOK_Macro) << New->getSourceRange();
17807 // C++11 [dcl.type]p3:
17808 // A type-specifier-seq shall not define a class or enumeration [...].
17809 if (!Invalid && getLangOpts().CPlusPlus &&
17810 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17811 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17812 << Context.getTagDeclType(New);
17813 Invalid = true;
17816 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17817 DC->getDeclKind() == Decl::Enum) {
17818 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17819 << Context.getTagDeclType(New);
17820 Invalid = true;
17823 // Maybe add qualifier info.
17824 if (SS.isNotEmpty()) {
17825 if (SS.isSet()) {
17826 // If this is either a declaration or a definition, check the
17827 // nested-name-specifier against the current context.
17828 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17829 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17830 isMemberSpecialization))
17831 Invalid = true;
17833 New->setQualifierInfo(SS.getWithLocInContext(Context));
17834 if (TemplateParameterLists.size() > 0) {
17835 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17838 else
17839 Invalid = true;
17842 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17843 // Add alignment attributes if necessary; these attributes are checked when
17844 // the ASTContext lays out the structure.
17846 // It is important for implementing the correct semantics that this
17847 // happen here (in ActOnTag). The #pragma pack stack is
17848 // maintained as a result of parser callbacks which can occur at
17849 // many points during the parsing of a struct declaration (because
17850 // the #pragma tokens are effectively skipped over during the
17851 // parsing of the struct).
17852 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17853 AddAlignmentAttributesForRecord(RD);
17854 AddMsStructLayoutForRecord(RD);
17858 if (ModulePrivateLoc.isValid()) {
17859 if (isMemberSpecialization)
17860 Diag(New->getLocation(), diag::err_module_private_specialization)
17861 << 2
17862 << FixItHint::CreateRemoval(ModulePrivateLoc);
17863 // __module_private__ does not apply to local classes. However, we only
17864 // diagnose this as an error when the declaration specifiers are
17865 // freestanding. Here, we just ignore the __module_private__.
17866 else if (!SearchDC->isFunctionOrMethod())
17867 New->setModulePrivate();
17870 // If this is a specialization of a member class (of a class template),
17871 // check the specialization.
17872 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17873 Invalid = true;
17875 // If we're declaring or defining a tag in function prototype scope in C,
17876 // note that this type can only be used within the function and add it to
17877 // the list of decls to inject into the function definition scope.
17878 if ((Name || Kind == TagTypeKind::Enum) &&
17879 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17880 if (getLangOpts().CPlusPlus) {
17881 // C++ [dcl.fct]p6:
17882 // Types shall not be defined in return or parameter types.
17883 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17884 Diag(Loc, diag::err_type_defined_in_param_type)
17885 << Name;
17886 Invalid = true;
17888 } else if (!PrevDecl) {
17889 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17893 if (Invalid)
17894 New->setInvalidDecl();
17896 // Set the lexical context. If the tag has a C++ scope specifier, the
17897 // lexical context will be different from the semantic context.
17898 New->setLexicalDeclContext(CurContext);
17900 // Mark this as a friend decl if applicable.
17901 // In Microsoft mode, a friend declaration also acts as a forward
17902 // declaration so we always pass true to setObjectOfFriendDecl to make
17903 // the tag name visible.
17904 if (TUK == TUK_Friend)
17905 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17907 // Set the access specifier.
17908 if (!Invalid && SearchDC->isRecord())
17909 SetMemberAccessSpecifier(New, PrevDecl, AS);
17911 if (PrevDecl)
17912 CheckRedeclarationInModule(New, PrevDecl);
17914 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17915 New->startDefinition();
17917 ProcessDeclAttributeList(S, New, Attrs);
17918 AddPragmaAttributes(S, New);
17920 // If this has an identifier, add it to the scope stack.
17921 if (TUK == TUK_Friend) {
17922 // We might be replacing an existing declaration in the lookup tables;
17923 // if so, borrow its access specifier.
17924 if (PrevDecl)
17925 New->setAccess(PrevDecl->getAccess());
17927 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17928 DC->makeDeclVisibleInContext(New);
17929 if (Name) // can be null along some error paths
17930 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17931 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17932 } else if (Name) {
17933 S = getNonFieldDeclScope(S);
17934 PushOnScopeChains(New, S, true);
17935 } else {
17936 CurContext->addDecl(New);
17939 // If this is the C FILE type, notify the AST context.
17940 if (IdentifierInfo *II = New->getIdentifier())
17941 if (!New->isInvalidDecl() &&
17942 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17943 II->isStr("FILE"))
17944 Context.setFILEDecl(New);
17946 if (PrevDecl)
17947 mergeDeclAttributes(New, PrevDecl);
17949 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17950 inferGslOwnerPointerAttribute(CXXRD);
17952 // If there's a #pragma GCC visibility in scope, set the visibility of this
17953 // record.
17954 AddPushedVisibilityAttribute(New);
17956 if (isMemberSpecialization && !New->isInvalidDecl())
17957 CompleteMemberSpecialization(New, Previous);
17959 OwnedDecl = true;
17960 // In C++, don't return an invalid declaration. We can't recover well from
17961 // the cases where we make the type anonymous.
17962 if (Invalid && getLangOpts().CPlusPlus) {
17963 if (New->isBeingDefined())
17964 if (auto RD = dyn_cast<RecordDecl>(New))
17965 RD->completeDefinition();
17966 return true;
17967 } else if (SkipBody && SkipBody->ShouldSkip) {
17968 return SkipBody->Previous;
17969 } else {
17970 return New;
17974 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17975 AdjustDeclIfTemplate(TagD);
17976 TagDecl *Tag = cast<TagDecl>(TagD);
17978 // Enter the tag context.
17979 PushDeclContext(S, Tag);
17981 ActOnDocumentableDecl(TagD);
17983 // If there's a #pragma GCC visibility in scope, set the visibility of this
17984 // record.
17985 AddPushedVisibilityAttribute(Tag);
17988 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17989 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17990 return false;
17992 // Make the previous decl visible.
17993 makeMergedDefinitionVisible(SkipBody.Previous);
17994 return true;
17997 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17998 assert(IDecl->getLexicalParent() == CurContext &&
17999 "The next DeclContext should be lexically contained in the current one.");
18000 CurContext = IDecl;
18003 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18004 SourceLocation FinalLoc,
18005 bool IsFinalSpelledSealed,
18006 bool IsAbstract,
18007 SourceLocation LBraceLoc) {
18008 AdjustDeclIfTemplate(TagD);
18009 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18011 FieldCollector->StartClass();
18013 if (!Record->getIdentifier())
18014 return;
18016 if (IsAbstract)
18017 Record->markAbstract();
18019 if (FinalLoc.isValid()) {
18020 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18021 IsFinalSpelledSealed
18022 ? FinalAttr::Keyword_sealed
18023 : FinalAttr::Keyword_final));
18025 // C++ [class]p2:
18026 // [...] The class-name is also inserted into the scope of the
18027 // class itself; this is known as the injected-class-name. For
18028 // purposes of access checking, the injected-class-name is treated
18029 // as if it were a public member name.
18030 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18031 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18032 Record->getLocation(), Record->getIdentifier(),
18033 /*PrevDecl=*/nullptr,
18034 /*DelayTypeCreation=*/true);
18035 Context.getTypeDeclType(InjectedClassName, Record);
18036 InjectedClassName->setImplicit();
18037 InjectedClassName->setAccess(AS_public);
18038 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18039 InjectedClassName->setDescribedClassTemplate(Template);
18040 PushOnScopeChains(InjectedClassName, S);
18041 assert(InjectedClassName->isInjectedClassName() &&
18042 "Broken injected-class-name");
18045 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18046 SourceRange BraceRange) {
18047 AdjustDeclIfTemplate(TagD);
18048 TagDecl *Tag = cast<TagDecl>(TagD);
18049 Tag->setBraceRange(BraceRange);
18051 // Make sure we "complete" the definition even it is invalid.
18052 if (Tag->isBeingDefined()) {
18053 assert(Tag->isInvalidDecl() && "We should already have completed it");
18054 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18055 RD->completeDefinition();
18058 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18059 FieldCollector->FinishClass();
18060 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18061 auto *Def = RD->getDefinition();
18062 assert(Def && "The record is expected to have a completed definition");
18063 unsigned NumInitMethods = 0;
18064 for (auto *Method : Def->methods()) {
18065 if (!Method->getIdentifier())
18066 continue;
18067 if (Method->getName() == "__init")
18068 NumInitMethods++;
18070 if (NumInitMethods > 1 || !Def->hasInitMethod())
18071 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18075 // Exit this scope of this tag's definition.
18076 PopDeclContext();
18078 if (getCurLexicalContext()->isObjCContainer() &&
18079 Tag->getDeclContext()->isFileContext())
18080 Tag->setTopLevelDeclInObjCContainer();
18082 // Notify the consumer that we've defined a tag.
18083 if (!Tag->isInvalidDecl())
18084 Consumer.HandleTagDeclDefinition(Tag);
18086 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18087 // from XLs and instead matches the XL #pragma pack(1) behavior.
18088 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18089 AlignPackStack.hasValue()) {
18090 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18091 // Only diagnose #pragma align(packed).
18092 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18093 return;
18094 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18095 if (!RD)
18096 return;
18097 // Only warn if there is at least 1 bitfield member.
18098 if (llvm::any_of(RD->fields(),
18099 [](const FieldDecl *FD) { return FD->isBitField(); }))
18100 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18104 void Sema::ActOnObjCContainerFinishDefinition() {
18105 // Exit this scope of this interface definition.
18106 PopDeclContext();
18109 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18110 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18111 OriginalLexicalContext = ObjCCtx;
18112 ActOnObjCContainerFinishDefinition();
18115 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18116 ActOnObjCContainerStartDefinition(ObjCCtx);
18117 OriginalLexicalContext = nullptr;
18120 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18121 AdjustDeclIfTemplate(TagD);
18122 TagDecl *Tag = cast<TagDecl>(TagD);
18123 Tag->setInvalidDecl();
18125 // Make sure we "complete" the definition even it is invalid.
18126 if (Tag->isBeingDefined()) {
18127 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18128 RD->completeDefinition();
18131 // We're undoing ActOnTagStartDefinition here, not
18132 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18133 // the FieldCollector.
18135 PopDeclContext();
18138 // Note that FieldName may be null for anonymous bitfields.
18139 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18140 IdentifierInfo *FieldName, QualType FieldTy,
18141 bool IsMsStruct, Expr *BitWidth) {
18142 assert(BitWidth);
18143 if (BitWidth->containsErrors())
18144 return ExprError();
18146 // C99 6.7.2.1p4 - verify the field type.
18147 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18148 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18149 // Handle incomplete and sizeless types with a specific error.
18150 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18151 diag::err_field_incomplete_or_sizeless))
18152 return ExprError();
18153 if (FieldName)
18154 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18155 << FieldName << FieldTy << BitWidth->getSourceRange();
18156 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18157 << FieldTy << BitWidth->getSourceRange();
18158 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18159 UPPC_BitFieldWidth))
18160 return ExprError();
18162 // If the bit-width is type- or value-dependent, don't try to check
18163 // it now.
18164 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18165 return BitWidth;
18167 llvm::APSInt Value;
18168 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18169 if (ICE.isInvalid())
18170 return ICE;
18171 BitWidth = ICE.get();
18173 // Zero-width bitfield is ok for anonymous field.
18174 if (Value == 0 && FieldName)
18175 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18176 << FieldName << BitWidth->getSourceRange();
18178 if (Value.isSigned() && Value.isNegative()) {
18179 if (FieldName)
18180 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18181 << FieldName << toString(Value, 10);
18182 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18183 << toString(Value, 10);
18186 // The size of the bit-field must not exceed our maximum permitted object
18187 // size.
18188 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18189 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18190 << !FieldName << FieldName << toString(Value, 10);
18193 if (!FieldTy->isDependentType()) {
18194 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18195 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18196 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18198 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18199 // ABI.
18200 bool CStdConstraintViolation =
18201 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18202 bool MSBitfieldViolation =
18203 Value.ugt(TypeStorageSize) &&
18204 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18205 if (CStdConstraintViolation || MSBitfieldViolation) {
18206 unsigned DiagWidth =
18207 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18208 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18209 << (bool)FieldName << FieldName << toString(Value, 10)
18210 << !CStdConstraintViolation << DiagWidth;
18213 // Warn on types where the user might conceivably expect to get all
18214 // specified bits as value bits: that's all integral types other than
18215 // 'bool'.
18216 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18217 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18218 << FieldName << toString(Value, 10)
18219 << (unsigned)TypeWidth;
18223 return BitWidth;
18226 /// ActOnField - Each field of a C struct/union is passed into this in order
18227 /// to create a FieldDecl object for it.
18228 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18229 Declarator &D, Expr *BitfieldWidth) {
18230 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18231 D, BitfieldWidth,
18232 /*InitStyle=*/ICIS_NoInit, AS_public);
18233 return Res;
18236 /// HandleField - Analyze a field of a C struct or a C++ data member.
18238 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18239 SourceLocation DeclStart,
18240 Declarator &D, Expr *BitWidth,
18241 InClassInitStyle InitStyle,
18242 AccessSpecifier AS) {
18243 if (D.isDecompositionDeclarator()) {
18244 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18245 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18246 << Decomp.getSourceRange();
18247 return nullptr;
18250 IdentifierInfo *II = D.getIdentifier();
18251 SourceLocation Loc = DeclStart;
18252 if (II) Loc = D.getIdentifierLoc();
18254 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18255 QualType T = TInfo->getType();
18256 if (getLangOpts().CPlusPlus) {
18257 CheckExtraCXXDefaultArguments(D);
18259 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18260 UPPC_DataMemberType)) {
18261 D.setInvalidType();
18262 T = Context.IntTy;
18263 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18267 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18269 if (D.getDeclSpec().isInlineSpecified())
18270 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18271 << getLangOpts().CPlusPlus17;
18272 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18273 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18274 diag::err_invalid_thread)
18275 << DeclSpec::getSpecifierName(TSCS);
18277 // Check to see if this name was declared as a member previously
18278 NamedDecl *PrevDecl = nullptr;
18279 LookupResult Previous(*this, II, Loc, LookupMemberName,
18280 ForVisibleRedeclaration);
18281 LookupName(Previous, S);
18282 switch (Previous.getResultKind()) {
18283 case LookupResult::Found:
18284 case LookupResult::FoundUnresolvedValue:
18285 PrevDecl = Previous.getAsSingle<NamedDecl>();
18286 break;
18288 case LookupResult::FoundOverloaded:
18289 PrevDecl = Previous.getRepresentativeDecl();
18290 break;
18292 case LookupResult::NotFound:
18293 case LookupResult::NotFoundInCurrentInstantiation:
18294 case LookupResult::Ambiguous:
18295 break;
18297 Previous.suppressDiagnostics();
18299 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18300 // Maybe we will complain about the shadowed template parameter.
18301 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18302 // Just pretend that we didn't see the previous declaration.
18303 PrevDecl = nullptr;
18306 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18307 PrevDecl = nullptr;
18309 bool Mutable
18310 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18311 SourceLocation TSSL = D.getBeginLoc();
18312 FieldDecl *NewFD
18313 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18314 TSSL, AS, PrevDecl, &D);
18316 if (NewFD->isInvalidDecl())
18317 Record->setInvalidDecl();
18319 if (D.getDeclSpec().isModulePrivateSpecified())
18320 NewFD->setModulePrivate();
18322 if (NewFD->isInvalidDecl() && PrevDecl) {
18323 // Don't introduce NewFD into scope; there's already something
18324 // with the same name in the same scope.
18325 } else if (II) {
18326 PushOnScopeChains(NewFD, S);
18327 } else
18328 Record->addDecl(NewFD);
18330 return NewFD;
18333 /// Build a new FieldDecl and check its well-formedness.
18335 /// This routine builds a new FieldDecl given the fields name, type,
18336 /// record, etc. \p PrevDecl should refer to any previous declaration
18337 /// with the same name and in the same scope as the field to be
18338 /// created.
18340 /// \returns a new FieldDecl.
18342 /// \todo The Declarator argument is a hack. It will be removed once
18343 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18344 TypeSourceInfo *TInfo,
18345 RecordDecl *Record, SourceLocation Loc,
18346 bool Mutable, Expr *BitWidth,
18347 InClassInitStyle InitStyle,
18348 SourceLocation TSSL,
18349 AccessSpecifier AS, NamedDecl *PrevDecl,
18350 Declarator *D) {
18351 IdentifierInfo *II = Name.getAsIdentifierInfo();
18352 bool InvalidDecl = false;
18353 if (D) InvalidDecl = D->isInvalidType();
18355 // If we receive a broken type, recover by assuming 'int' and
18356 // marking this declaration as invalid.
18357 if (T.isNull() || T->containsErrors()) {
18358 InvalidDecl = true;
18359 T = Context.IntTy;
18362 QualType EltTy = Context.getBaseElementType(T);
18363 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18364 if (RequireCompleteSizedType(Loc, EltTy,
18365 diag::err_field_incomplete_or_sizeless)) {
18366 // Fields of incomplete type force their record to be invalid.
18367 Record->setInvalidDecl();
18368 InvalidDecl = true;
18369 } else {
18370 NamedDecl *Def;
18371 EltTy->isIncompleteType(&Def);
18372 if (Def && Def->isInvalidDecl()) {
18373 Record->setInvalidDecl();
18374 InvalidDecl = true;
18379 // TR 18037 does not allow fields to be declared with address space
18380 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18381 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18382 Diag(Loc, diag::err_field_with_address_space);
18383 Record->setInvalidDecl();
18384 InvalidDecl = true;
18387 if (LangOpts.OpenCL) {
18388 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18389 // used as structure or union field: image, sampler, event or block types.
18390 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18391 T->isBlockPointerType()) {
18392 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18393 Record->setInvalidDecl();
18394 InvalidDecl = true;
18396 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18397 // is enabled.
18398 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18399 "__cl_clang_bitfields", LangOpts)) {
18400 Diag(Loc, diag::err_opencl_bitfields);
18401 InvalidDecl = true;
18405 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18406 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18407 T.hasQualifiers()) {
18408 InvalidDecl = true;
18409 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18412 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18413 // than a variably modified type.
18414 if (!InvalidDecl && T->isVariablyModifiedType()) {
18415 if (!tryToFixVariablyModifiedVarType(
18416 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18417 InvalidDecl = true;
18420 // Fields can not have abstract class types
18421 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18422 diag::err_abstract_type_in_decl,
18423 AbstractFieldType))
18424 InvalidDecl = true;
18426 if (InvalidDecl)
18427 BitWidth = nullptr;
18428 // If this is declared as a bit-field, check the bit-field.
18429 if (BitWidth) {
18430 BitWidth =
18431 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18432 if (!BitWidth) {
18433 InvalidDecl = true;
18434 BitWidth = nullptr;
18438 // Check that 'mutable' is consistent with the type of the declaration.
18439 if (!InvalidDecl && Mutable) {
18440 unsigned DiagID = 0;
18441 if (T->isReferenceType())
18442 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18443 : diag::err_mutable_reference;
18444 else if (T.isConstQualified())
18445 DiagID = diag::err_mutable_const;
18447 if (DiagID) {
18448 SourceLocation ErrLoc = Loc;
18449 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18450 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18451 Diag(ErrLoc, DiagID);
18452 if (DiagID != diag::ext_mutable_reference) {
18453 Mutable = false;
18454 InvalidDecl = true;
18459 // C++11 [class.union]p8 (DR1460):
18460 // At most one variant member of a union may have a
18461 // brace-or-equal-initializer.
18462 if (InitStyle != ICIS_NoInit)
18463 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18465 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18466 BitWidth, Mutable, InitStyle);
18467 if (InvalidDecl)
18468 NewFD->setInvalidDecl();
18470 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18471 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18472 Diag(Loc, diag::err_duplicate_member) << II;
18473 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18474 NewFD->setInvalidDecl();
18477 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18478 if (Record->isUnion()) {
18479 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18480 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18481 if (RDecl->getDefinition()) {
18482 // C++ [class.union]p1: An object of a class with a non-trivial
18483 // constructor, a non-trivial copy constructor, a non-trivial
18484 // destructor, or a non-trivial copy assignment operator
18485 // cannot be a member of a union, nor can an array of such
18486 // objects.
18487 if (CheckNontrivialField(NewFD))
18488 NewFD->setInvalidDecl();
18492 // C++ [class.union]p1: If a union contains a member of reference type,
18493 // the program is ill-formed, except when compiling with MSVC extensions
18494 // enabled.
18495 if (EltTy->isReferenceType()) {
18496 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18497 diag::ext_union_member_of_reference_type :
18498 diag::err_union_member_of_reference_type)
18499 << NewFD->getDeclName() << EltTy;
18500 if (!getLangOpts().MicrosoftExt)
18501 NewFD->setInvalidDecl();
18506 // FIXME: We need to pass in the attributes given an AST
18507 // representation, not a parser representation.
18508 if (D) {
18509 // FIXME: The current scope is almost... but not entirely... correct here.
18510 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18512 if (NewFD->hasAttrs())
18513 CheckAlignasUnderalignment(NewFD);
18516 // In auto-retain/release, infer strong retension for fields of
18517 // retainable type.
18518 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18519 NewFD->setInvalidDecl();
18521 if (T.isObjCGCWeak())
18522 Diag(Loc, diag::warn_attribute_weak_on_field);
18524 // PPC MMA non-pointer types are not allowed as field types.
18525 if (Context.getTargetInfo().getTriple().isPPC64() &&
18526 CheckPPCMMAType(T, NewFD->getLocation()))
18527 NewFD->setInvalidDecl();
18529 NewFD->setAccess(AS);
18530 return NewFD;
18533 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18534 assert(FD);
18535 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18537 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18538 return false;
18540 QualType EltTy = Context.getBaseElementType(FD->getType());
18541 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18542 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18543 if (RDecl->getDefinition()) {
18544 // We check for copy constructors before constructors
18545 // because otherwise we'll never get complaints about
18546 // copy constructors.
18548 CXXSpecialMember member = CXXInvalid;
18549 // We're required to check for any non-trivial constructors. Since the
18550 // implicit default constructor is suppressed if there are any
18551 // user-declared constructors, we just need to check that there is a
18552 // trivial default constructor and a trivial copy constructor. (We don't
18553 // worry about move constructors here, since this is a C++98 check.)
18554 if (RDecl->hasNonTrivialCopyConstructor())
18555 member = CXXCopyConstructor;
18556 else if (!RDecl->hasTrivialDefaultConstructor())
18557 member = CXXDefaultConstructor;
18558 else if (RDecl->hasNonTrivialCopyAssignment())
18559 member = CXXCopyAssignment;
18560 else if (RDecl->hasNonTrivialDestructor())
18561 member = CXXDestructor;
18563 if (member != CXXInvalid) {
18564 if (!getLangOpts().CPlusPlus11 &&
18565 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18566 // Objective-C++ ARC: it is an error to have a non-trivial field of
18567 // a union. However, system headers in Objective-C programs
18568 // occasionally have Objective-C lifetime objects within unions,
18569 // and rather than cause the program to fail, we make those
18570 // members unavailable.
18571 SourceLocation Loc = FD->getLocation();
18572 if (getSourceManager().isInSystemHeader(Loc)) {
18573 if (!FD->hasAttr<UnavailableAttr>())
18574 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18575 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18576 return false;
18580 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18581 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18582 diag::err_illegal_union_or_anon_struct_member)
18583 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18584 DiagnoseNontrivial(RDecl, member);
18585 return !getLangOpts().CPlusPlus11;
18590 return false;
18593 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18594 /// AST enum value.
18595 static ObjCIvarDecl::AccessControl
18596 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18597 switch (ivarVisibility) {
18598 default: llvm_unreachable("Unknown visitibility kind");
18599 case tok::objc_private: return ObjCIvarDecl::Private;
18600 case tok::objc_public: return ObjCIvarDecl::Public;
18601 case tok::objc_protected: return ObjCIvarDecl::Protected;
18602 case tok::objc_package: return ObjCIvarDecl::Package;
18606 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18607 /// in order to create an IvarDecl object for it.
18608 Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18609 Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18611 IdentifierInfo *II = D.getIdentifier();
18612 SourceLocation Loc = DeclStart;
18613 if (II) Loc = D.getIdentifierLoc();
18615 // FIXME: Unnamed fields can be handled in various different ways, for
18616 // example, unnamed unions inject all members into the struct namespace!
18618 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18619 QualType T = TInfo->getType();
18621 if (BitWidth) {
18622 // 6.7.2.1p3, 6.7.2.1p4
18623 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18624 if (!BitWidth)
18625 D.setInvalidType();
18626 } else {
18627 // Not a bitfield.
18629 // validate II.
18632 if (T->isReferenceType()) {
18633 Diag(Loc, diag::err_ivar_reference_type);
18634 D.setInvalidType();
18636 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18637 // than a variably modified type.
18638 else if (T->isVariablyModifiedType()) {
18639 if (!tryToFixVariablyModifiedVarType(
18640 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18641 D.setInvalidType();
18644 // Get the visibility (access control) for this ivar.
18645 ObjCIvarDecl::AccessControl ac =
18646 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18647 : ObjCIvarDecl::None;
18648 // Must set ivar's DeclContext to its enclosing interface.
18649 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18650 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18651 return nullptr;
18652 ObjCContainerDecl *EnclosingContext;
18653 if (ObjCImplementationDecl *IMPDecl =
18654 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18655 if (LangOpts.ObjCRuntime.isFragile()) {
18656 // Case of ivar declared in an implementation. Context is that of its class.
18657 EnclosingContext = IMPDecl->getClassInterface();
18658 assert(EnclosingContext && "Implementation has no class interface!");
18660 else
18661 EnclosingContext = EnclosingDecl;
18662 } else {
18663 if (ObjCCategoryDecl *CDecl =
18664 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18665 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18666 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18667 return nullptr;
18670 EnclosingContext = EnclosingDecl;
18673 // Construct the decl.
18674 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
18675 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
18677 if (T->containsErrors())
18678 NewID->setInvalidDecl();
18680 if (II) {
18681 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18682 ForVisibleRedeclaration);
18683 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18684 && !isa<TagDecl>(PrevDecl)) {
18685 Diag(Loc, diag::err_duplicate_member) << II;
18686 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18687 NewID->setInvalidDecl();
18691 // Process attributes attached to the ivar.
18692 ProcessDeclAttributes(S, NewID, D);
18694 if (D.isInvalidType())
18695 NewID->setInvalidDecl();
18697 // In ARC, infer 'retaining' for ivars of retainable type.
18698 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18699 NewID->setInvalidDecl();
18701 if (D.getDeclSpec().isModulePrivateSpecified())
18702 NewID->setModulePrivate();
18704 if (II) {
18705 // FIXME: When interfaces are DeclContexts, we'll need to add
18706 // these to the interface.
18707 S->AddDecl(NewID);
18708 IdResolver.AddDecl(NewID);
18711 if (LangOpts.ObjCRuntime.isNonFragile() &&
18712 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18713 Diag(Loc, diag::warn_ivars_in_interface);
18715 return NewID;
18718 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18719 /// class and class extensions. For every class \@interface and class
18720 /// extension \@interface, if the last ivar is a bitfield of any type,
18721 /// then add an implicit `char :0` ivar to the end of that interface.
18722 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18723 SmallVectorImpl<Decl *> &AllIvarDecls) {
18724 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18725 return;
18727 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18728 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18730 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18731 return;
18732 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18733 if (!ID) {
18734 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18735 if (!CD->IsClassExtension())
18736 return;
18738 // No need to add this to end of @implementation.
18739 else
18740 return;
18742 // All conditions are met. Add a new bitfield to the tail end of ivars.
18743 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18744 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18746 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18747 DeclLoc, DeclLoc, nullptr,
18748 Context.CharTy,
18749 Context.getTrivialTypeSourceInfo(Context.CharTy,
18750 DeclLoc),
18751 ObjCIvarDecl::Private, BW,
18752 true);
18753 AllIvarDecls.push_back(Ivar);
18756 /// [class.dtor]p4:
18757 /// At the end of the definition of a class, overload resolution is
18758 /// performed among the prospective destructors declared in that class with
18759 /// an empty argument list to select the destructor for the class, also
18760 /// known as the selected destructor.
18762 /// We do the overload resolution here, then mark the selected constructor in the AST.
18763 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18764 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18765 if (!Record->hasUserDeclaredDestructor()) {
18766 return;
18769 SourceLocation Loc = Record->getLocation();
18770 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18772 for (auto *Decl : Record->decls()) {
18773 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18774 if (DD->isInvalidDecl())
18775 continue;
18776 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18777 OCS);
18778 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18782 if (OCS.empty()) {
18783 return;
18785 OverloadCandidateSet::iterator Best;
18786 unsigned Msg = 0;
18787 OverloadCandidateDisplayKind DisplayKind;
18789 switch (OCS.BestViableFunction(S, Loc, Best)) {
18790 case OR_Success:
18791 case OR_Deleted:
18792 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18793 break;
18795 case OR_Ambiguous:
18796 Msg = diag::err_ambiguous_destructor;
18797 DisplayKind = OCD_AmbiguousCandidates;
18798 break;
18800 case OR_No_Viable_Function:
18801 Msg = diag::err_no_viable_destructor;
18802 DisplayKind = OCD_AllCandidates;
18803 break;
18806 if (Msg) {
18807 // OpenCL have got their own thing going with destructors. It's slightly broken,
18808 // but we allow it.
18809 if (!S.LangOpts.OpenCL) {
18810 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18811 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18812 Record->setInvalidDecl();
18814 // It's a bit hacky: At this point we've raised an error but we want the
18815 // rest of the compiler to continue somehow working. However almost
18816 // everything we'll try to do with the class will depend on there being a
18817 // destructor. So let's pretend the first one is selected and hope for the
18818 // best.
18819 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18823 /// [class.mem.special]p5
18824 /// Two special member functions are of the same kind if:
18825 /// - they are both default constructors,
18826 /// - they are both copy or move constructors with the same first parameter
18827 /// type, or
18828 /// - they are both copy or move assignment operators with the same first
18829 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18830 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18831 CXXMethodDecl *M1,
18832 CXXMethodDecl *M2,
18833 Sema::CXXSpecialMember CSM) {
18834 // We don't want to compare templates to non-templates: See
18835 // https://github.com/llvm/llvm-project/issues/59206
18836 if (CSM == Sema::CXXDefaultConstructor)
18837 return bool(M1->getDescribedFunctionTemplate()) ==
18838 bool(M2->getDescribedFunctionTemplate());
18839 // FIXME: better resolve CWG
18840 // https://cplusplus.github.io/CWG/issues/2787.html
18841 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18842 M2->getNonObjectParameter(0)->getType()))
18843 return false;
18844 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18845 M2->getFunctionObjectParameterReferenceType()))
18846 return false;
18848 return true;
18851 /// [class.mem.special]p6:
18852 /// An eligible special member function is a special member function for which:
18853 /// - the function is not deleted,
18854 /// - the associated constraints, if any, are satisfied, and
18855 /// - no special member function of the same kind whose associated constraints
18856 /// [CWG2595], if any, are satisfied is more constrained.
18857 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18858 ArrayRef<CXXMethodDecl *> Methods,
18859 Sema::CXXSpecialMember CSM) {
18860 SmallVector<bool, 4> SatisfactionStatus;
18862 for (CXXMethodDecl *Method : Methods) {
18863 const Expr *Constraints = Method->getTrailingRequiresClause();
18864 if (!Constraints)
18865 SatisfactionStatus.push_back(true);
18866 else {
18867 ConstraintSatisfaction Satisfaction;
18868 if (S.CheckFunctionConstraints(Method, Satisfaction))
18869 SatisfactionStatus.push_back(false);
18870 else
18871 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18875 for (size_t i = 0; i < Methods.size(); i++) {
18876 if (!SatisfactionStatus[i])
18877 continue;
18878 CXXMethodDecl *Method = Methods[i];
18879 CXXMethodDecl *OrigMethod = Method;
18880 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18881 OrigMethod = cast<CXXMethodDecl>(MF);
18883 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18884 bool AnotherMethodIsMoreConstrained = false;
18885 for (size_t j = 0; j < Methods.size(); j++) {
18886 if (i == j || !SatisfactionStatus[j])
18887 continue;
18888 CXXMethodDecl *OtherMethod = Methods[j];
18889 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18890 OtherMethod = cast<CXXMethodDecl>(MF);
18892 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18893 CSM))
18894 continue;
18896 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18897 if (!OtherConstraints)
18898 continue;
18899 if (!Constraints) {
18900 AnotherMethodIsMoreConstrained = true;
18901 break;
18903 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18904 {Constraints},
18905 AnotherMethodIsMoreConstrained)) {
18906 // There was an error with the constraints comparison. Exit the loop
18907 // and don't consider this function eligible.
18908 AnotherMethodIsMoreConstrained = true;
18910 if (AnotherMethodIsMoreConstrained)
18911 break;
18913 // FIXME: Do not consider deleted methods as eligible after implementing
18914 // DR1734 and DR1496.
18915 if (!AnotherMethodIsMoreConstrained) {
18916 Method->setIneligibleOrNotSelected(false);
18917 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18922 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18923 CXXRecordDecl *Record) {
18924 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18925 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18926 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18927 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18928 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18930 for (auto *Decl : Record->decls()) {
18931 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18932 if (!MD) {
18933 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18934 if (FTD)
18935 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18937 if (!MD)
18938 continue;
18939 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18940 if (CD->isInvalidDecl())
18941 continue;
18942 if (CD->isDefaultConstructor())
18943 DefaultConstructors.push_back(MD);
18944 else if (CD->isCopyConstructor())
18945 CopyConstructors.push_back(MD);
18946 else if (CD->isMoveConstructor())
18947 MoveConstructors.push_back(MD);
18948 } else if (MD->isCopyAssignmentOperator()) {
18949 CopyAssignmentOperators.push_back(MD);
18950 } else if (MD->isMoveAssignmentOperator()) {
18951 MoveAssignmentOperators.push_back(MD);
18955 SetEligibleMethods(S, Record, DefaultConstructors,
18956 Sema::CXXDefaultConstructor);
18957 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18958 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18959 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18960 Sema::CXXCopyAssignment);
18961 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18962 Sema::CXXMoveAssignment);
18965 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18966 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18967 SourceLocation RBrac,
18968 const ParsedAttributesView &Attrs) {
18969 assert(EnclosingDecl && "missing record or interface decl");
18971 // If this is an Objective-C @implementation or category and we have
18972 // new fields here we should reset the layout of the interface since
18973 // it will now change.
18974 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18975 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18976 switch (DC->getKind()) {
18977 default: break;
18978 case Decl::ObjCCategory:
18979 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18980 break;
18981 case Decl::ObjCImplementation:
18982 Context.
18983 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18984 break;
18988 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18989 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18991 // Start counting up the number of named members; make sure to include
18992 // members of anonymous structs and unions in the total.
18993 unsigned NumNamedMembers = 0;
18994 if (Record) {
18995 for (const auto *I : Record->decls()) {
18996 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18997 if (IFD->getDeclName())
18998 ++NumNamedMembers;
19002 // Verify that all the fields are okay.
19003 SmallVector<FieldDecl*, 32> RecFields;
19005 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19006 i != end; ++i) {
19007 FieldDecl *FD = cast<FieldDecl>(*i);
19009 // Get the type for the field.
19010 const Type *FDTy = FD->getType().getTypePtr();
19012 if (!FD->isAnonymousStructOrUnion()) {
19013 // Remember all fields written by the user.
19014 RecFields.push_back(FD);
19017 // If the field is already invalid for some reason, don't emit more
19018 // diagnostics about it.
19019 if (FD->isInvalidDecl()) {
19020 EnclosingDecl->setInvalidDecl();
19021 continue;
19024 // C99 6.7.2.1p2:
19025 // A structure or union shall not contain a member with
19026 // incomplete or function type (hence, a structure shall not
19027 // contain an instance of itself, but may contain a pointer to
19028 // an instance of itself), except that the last member of a
19029 // structure with more than one named member may have incomplete
19030 // array type; such a structure (and any union containing,
19031 // possibly recursively, a member that is such a structure)
19032 // shall not be a member of a structure or an element of an
19033 // array.
19034 bool IsLastField = (i + 1 == Fields.end());
19035 if (FDTy->isFunctionType()) {
19036 // Field declared as a function.
19037 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19038 << FD->getDeclName();
19039 FD->setInvalidDecl();
19040 EnclosingDecl->setInvalidDecl();
19041 continue;
19042 } else if (FDTy->isIncompleteArrayType() &&
19043 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19044 if (Record) {
19045 // Flexible array member.
19046 // Microsoft and g++ is more permissive regarding flexible array.
19047 // It will accept flexible array in union and also
19048 // as the sole element of a struct/class.
19049 unsigned DiagID = 0;
19050 if (!Record->isUnion() && !IsLastField) {
19051 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19052 << FD->getDeclName() << FD->getType()
19053 << llvm::to_underlying(Record->getTagKind());
19054 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19055 FD->setInvalidDecl();
19056 EnclosingDecl->setInvalidDecl();
19057 continue;
19058 } else if (Record->isUnion())
19059 DiagID = getLangOpts().MicrosoftExt
19060 ? diag::ext_flexible_array_union_ms
19061 : getLangOpts().CPlusPlus
19062 ? diag::ext_flexible_array_union_gnu
19063 : diag::err_flexible_array_union;
19064 else if (NumNamedMembers < 1)
19065 DiagID = getLangOpts().MicrosoftExt
19066 ? diag::ext_flexible_array_empty_aggregate_ms
19067 : getLangOpts().CPlusPlus
19068 ? diag::ext_flexible_array_empty_aggregate_gnu
19069 : diag::err_flexible_array_empty_aggregate;
19071 if (DiagID)
19072 Diag(FD->getLocation(), DiagID)
19073 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19074 // While the layout of types that contain virtual bases is not specified
19075 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19076 // virtual bases after the derived members. This would make a flexible
19077 // array member declared at the end of an object not adjacent to the end
19078 // of the type.
19079 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19080 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19081 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19082 if (!getLangOpts().C99)
19083 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19084 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19086 // If the element type has a non-trivial destructor, we would not
19087 // implicitly destroy the elements, so disallow it for now.
19089 // FIXME: GCC allows this. We should probably either implicitly delete
19090 // the destructor of the containing class, or just allow this.
19091 QualType BaseElem = Context.getBaseElementType(FD->getType());
19092 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19093 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19094 << FD->getDeclName() << FD->getType();
19095 FD->setInvalidDecl();
19096 EnclosingDecl->setInvalidDecl();
19097 continue;
19099 // Okay, we have a legal flexible array member at the end of the struct.
19100 Record->setHasFlexibleArrayMember(true);
19101 } else {
19102 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19103 // unless they are followed by another ivar. That check is done
19104 // elsewhere, after synthesized ivars are known.
19106 } else if (!FDTy->isDependentType() &&
19107 RequireCompleteSizedType(
19108 FD->getLocation(), FD->getType(),
19109 diag::err_field_incomplete_or_sizeless)) {
19110 // Incomplete type
19111 FD->setInvalidDecl();
19112 EnclosingDecl->setInvalidDecl();
19113 continue;
19114 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19115 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19116 // A type which contains a flexible array member is considered to be a
19117 // flexible array member.
19118 Record->setHasFlexibleArrayMember(true);
19119 if (!Record->isUnion()) {
19120 // If this is a struct/class and this is not the last element, reject
19121 // it. Note that GCC supports variable sized arrays in the middle of
19122 // structures.
19123 if (!IsLastField)
19124 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19125 << FD->getDeclName() << FD->getType();
19126 else {
19127 // We support flexible arrays at the end of structs in
19128 // other structs as an extension.
19129 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19130 << FD->getDeclName();
19134 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19135 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19136 diag::err_abstract_type_in_decl,
19137 AbstractIvarType)) {
19138 // Ivars can not have abstract class types
19139 FD->setInvalidDecl();
19141 if (Record && FDTTy->getDecl()->hasObjectMember())
19142 Record->setHasObjectMember(true);
19143 if (Record && FDTTy->getDecl()->hasVolatileMember())
19144 Record->setHasVolatileMember(true);
19145 } else if (FDTy->isObjCObjectType()) {
19146 /// A field cannot be an Objective-c object
19147 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19148 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19149 QualType T = Context.getObjCObjectPointerType(FD->getType());
19150 FD->setType(T);
19151 } else if (Record && Record->isUnion() &&
19152 FD->getType().hasNonTrivialObjCLifetime() &&
19153 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19154 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19155 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19156 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19157 // For backward compatibility, fields of C unions declared in system
19158 // headers that have non-trivial ObjC ownership qualifications are marked
19159 // as unavailable unless the qualifier is explicit and __strong. This can
19160 // break ABI compatibility between programs compiled with ARC and MRR, but
19161 // is a better option than rejecting programs using those unions under
19162 // ARC.
19163 FD->addAttr(UnavailableAttr::CreateImplicit(
19164 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19165 FD->getLocation()));
19166 } else if (getLangOpts().ObjC &&
19167 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19168 !Record->hasObjectMember()) {
19169 if (FD->getType()->isObjCObjectPointerType() ||
19170 FD->getType().isObjCGCStrong())
19171 Record->setHasObjectMember(true);
19172 else if (Context.getAsArrayType(FD->getType())) {
19173 QualType BaseType = Context.getBaseElementType(FD->getType());
19174 if (BaseType->isRecordType() &&
19175 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19176 Record->setHasObjectMember(true);
19177 else if (BaseType->isObjCObjectPointerType() ||
19178 BaseType.isObjCGCStrong())
19179 Record->setHasObjectMember(true);
19183 if (Record && !getLangOpts().CPlusPlus &&
19184 !shouldIgnoreForRecordTriviality(FD)) {
19185 QualType FT = FD->getType();
19186 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19187 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19188 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19189 Record->isUnion())
19190 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19192 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19193 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19194 Record->setNonTrivialToPrimitiveCopy(true);
19195 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19196 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19198 if (FT.isDestructedType()) {
19199 Record->setNonTrivialToPrimitiveDestroy(true);
19200 Record->setParamDestroyedInCallee(true);
19201 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19202 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19205 if (const auto *RT = FT->getAs<RecordType>()) {
19206 if (RT->getDecl()->getArgPassingRestrictions() ==
19207 RecordArgPassingKind::CanNeverPassInRegs)
19208 Record->setArgPassingRestrictions(
19209 RecordArgPassingKind::CanNeverPassInRegs);
19210 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19211 Record->setArgPassingRestrictions(
19212 RecordArgPassingKind::CanNeverPassInRegs);
19215 if (Record && FD->getType().isVolatileQualified())
19216 Record->setHasVolatileMember(true);
19217 // Keep track of the number of named members.
19218 if (FD->getIdentifier())
19219 ++NumNamedMembers;
19222 // Okay, we successfully defined 'Record'.
19223 if (Record) {
19224 bool Completed = false;
19225 if (CXXRecord) {
19226 if (!CXXRecord->isInvalidDecl()) {
19227 // Set access bits correctly on the directly-declared conversions.
19228 for (CXXRecordDecl::conversion_iterator
19229 I = CXXRecord->conversion_begin(),
19230 E = CXXRecord->conversion_end(); I != E; ++I)
19231 I.setAccess((*I)->getAccess());
19234 // Add any implicitly-declared members to this class.
19235 AddImplicitlyDeclaredMembersToClass(CXXRecord);
19237 if (!CXXRecord->isDependentType()) {
19238 if (!CXXRecord->isInvalidDecl()) {
19239 // If we have virtual base classes, we may end up finding multiple
19240 // final overriders for a given virtual function. Check for this
19241 // problem now.
19242 if (CXXRecord->getNumVBases()) {
19243 CXXFinalOverriderMap FinalOverriders;
19244 CXXRecord->getFinalOverriders(FinalOverriders);
19246 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19247 MEnd = FinalOverriders.end();
19248 M != MEnd; ++M) {
19249 for (OverridingMethods::iterator SO = M->second.begin(),
19250 SOEnd = M->second.end();
19251 SO != SOEnd; ++SO) {
19252 assert(SO->second.size() > 0 &&
19253 "Virtual function without overriding functions?");
19254 if (SO->second.size() == 1)
19255 continue;
19257 // C++ [class.virtual]p2:
19258 // In a derived class, if a virtual member function of a base
19259 // class subobject has more than one final overrider the
19260 // program is ill-formed.
19261 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19262 << (const NamedDecl *)M->first << Record;
19263 Diag(M->first->getLocation(),
19264 diag::note_overridden_virtual_function);
19265 for (OverridingMethods::overriding_iterator
19266 OM = SO->second.begin(),
19267 OMEnd = SO->second.end();
19268 OM != OMEnd; ++OM)
19269 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19270 << (const NamedDecl *)M->first << OM->Method->getParent();
19272 Record->setInvalidDecl();
19275 CXXRecord->completeDefinition(&FinalOverriders);
19276 Completed = true;
19279 ComputeSelectedDestructor(*this, CXXRecord);
19280 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19284 if (!Completed)
19285 Record->completeDefinition();
19287 // Handle attributes before checking the layout.
19288 ProcessDeclAttributeList(S, Record, Attrs);
19290 // Check to see if a FieldDecl is a pointer to a function.
19291 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19292 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19293 if (!FD) {
19294 // Check whether this is a forward declaration that was inserted by
19295 // Clang. This happens when a non-forward declared / defined type is
19296 // used, e.g.:
19298 // struct foo {
19299 // struct bar *(*f)();
19300 // struct bar *(*g)();
19301 // };
19303 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19304 // incomplete definition.
19305 if (const auto *TD = dyn_cast<TagDecl>(D))
19306 return !TD->isCompleteDefinition();
19307 return false;
19309 QualType FieldType = FD->getType().getDesugaredType(Context);
19310 if (isa<PointerType>(FieldType)) {
19311 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19312 return PointeeType.getDesugaredType(Context)->isFunctionType();
19314 return false;
19317 // Maybe randomize the record's decls. We automatically randomize a record
19318 // of function pointers, unless it has the "no_randomize_layout" attribute.
19319 if (!getLangOpts().CPlusPlus &&
19320 (Record->hasAttr<RandomizeLayoutAttr>() ||
19321 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19322 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19323 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19324 !Record->isRandomized()) {
19325 SmallVector<Decl *, 32> NewDeclOrdering;
19326 if (randstruct::randomizeStructureLayout(Context, Record,
19327 NewDeclOrdering))
19328 Record->reorderDecls(NewDeclOrdering);
19331 // We may have deferred checking for a deleted destructor. Check now.
19332 if (CXXRecord) {
19333 auto *Dtor = CXXRecord->getDestructor();
19334 if (Dtor && Dtor->isImplicit() &&
19335 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19336 CXXRecord->setImplicitDestructorIsDeleted();
19337 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19341 if (Record->hasAttrs()) {
19342 CheckAlignasUnderalignment(Record);
19344 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19345 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19346 IA->getRange(), IA->getBestCase(),
19347 IA->getInheritanceModel());
19350 // Check if the structure/union declaration is a type that can have zero
19351 // size in C. For C this is a language extension, for C++ it may cause
19352 // compatibility problems.
19353 bool CheckForZeroSize;
19354 if (!getLangOpts().CPlusPlus) {
19355 CheckForZeroSize = true;
19356 } else {
19357 // For C++ filter out types that cannot be referenced in C code.
19358 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19359 CheckForZeroSize =
19360 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19361 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19362 CXXRecord->isCLike();
19364 if (CheckForZeroSize) {
19365 bool ZeroSize = true;
19366 bool IsEmpty = true;
19367 unsigned NonBitFields = 0;
19368 for (RecordDecl::field_iterator I = Record->field_begin(),
19369 E = Record->field_end();
19370 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19371 IsEmpty = false;
19372 if (I->isUnnamedBitfield()) {
19373 if (!I->isZeroLengthBitField(Context))
19374 ZeroSize = false;
19375 } else {
19376 ++NonBitFields;
19377 QualType FieldType = I->getType();
19378 if (FieldType->isIncompleteType() ||
19379 !Context.getTypeSizeInChars(FieldType).isZero())
19380 ZeroSize = false;
19384 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19385 // allowed in C++, but warn if its declaration is inside
19386 // extern "C" block.
19387 if (ZeroSize) {
19388 Diag(RecLoc, getLangOpts().CPlusPlus ?
19389 diag::warn_zero_size_struct_union_in_extern_c :
19390 diag::warn_zero_size_struct_union_compat)
19391 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19394 // Structs without named members are extension in C (C99 6.7.2.1p7),
19395 // but are accepted by GCC.
19396 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19397 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19398 diag::ext_no_named_members_in_struct_union)
19399 << Record->isUnion();
19402 } else {
19403 ObjCIvarDecl **ClsFields =
19404 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19405 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19406 ID->setEndOfDefinitionLoc(RBrac);
19407 // Add ivar's to class's DeclContext.
19408 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19409 ClsFields[i]->setLexicalDeclContext(ID);
19410 ID->addDecl(ClsFields[i]);
19412 // Must enforce the rule that ivars in the base classes may not be
19413 // duplicates.
19414 if (ID->getSuperClass())
19415 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19416 } else if (ObjCImplementationDecl *IMPDecl =
19417 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19418 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19419 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19420 // Ivar declared in @implementation never belongs to the implementation.
19421 // Only it is in implementation's lexical context.
19422 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19423 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19424 IMPDecl->setIvarLBraceLoc(LBrac);
19425 IMPDecl->setIvarRBraceLoc(RBrac);
19426 } else if (ObjCCategoryDecl *CDecl =
19427 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19428 // case of ivars in class extension; all other cases have been
19429 // reported as errors elsewhere.
19430 // FIXME. Class extension does not have a LocEnd field.
19431 // CDecl->setLocEnd(RBrac);
19432 // Add ivar's to class extension's DeclContext.
19433 // Diagnose redeclaration of private ivars.
19434 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19435 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19436 if (IDecl) {
19437 if (const ObjCIvarDecl *ClsIvar =
19438 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19439 Diag(ClsFields[i]->getLocation(),
19440 diag::err_duplicate_ivar_declaration);
19441 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19442 continue;
19444 for (const auto *Ext : IDecl->known_extensions()) {
19445 if (const ObjCIvarDecl *ClsExtIvar
19446 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19447 Diag(ClsFields[i]->getLocation(),
19448 diag::err_duplicate_ivar_declaration);
19449 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19450 continue;
19454 ClsFields[i]->setLexicalDeclContext(CDecl);
19455 CDecl->addDecl(ClsFields[i]);
19457 CDecl->setIvarLBraceLoc(LBrac);
19458 CDecl->setIvarRBraceLoc(RBrac);
19462 // Check the "counted_by" attribute to ensure that the count field exists in
19463 // the struct. Make sure we're performing this check on the outer-most
19464 // record. This is a C-only feature.
19465 if (!getLangOpts().CPlusPlus && Record &&
19466 !isa<RecordDecl>(Record->getParent())) {
19467 auto Pred = [](const Decl *D) {
19468 if (const auto *FD = dyn_cast_if_present<FieldDecl>(D))
19469 return FD->hasAttr<CountedByAttr>();
19470 return false;
19472 if (const FieldDecl *FD = Record->findFieldIf(Pred))
19473 CheckCountedByAttr(S, FD);
19477 /// Determine whether the given integral value is representable within
19478 /// the given type T.
19479 static bool isRepresentableIntegerValue(ASTContext &Context,
19480 llvm::APSInt &Value,
19481 QualType T) {
19482 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19483 "Integral type required!");
19484 unsigned BitWidth = Context.getIntWidth(T);
19486 if (Value.isUnsigned() || Value.isNonNegative()) {
19487 if (T->isSignedIntegerOrEnumerationType())
19488 --BitWidth;
19489 return Value.getActiveBits() <= BitWidth;
19491 return Value.getSignificantBits() <= BitWidth;
19494 // Given an integral type, return the next larger integral type
19495 // (or a NULL type of no such type exists).
19496 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19497 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19498 // enum checking below.
19499 assert((T->isIntegralType(Context) ||
19500 T->isEnumeralType()) && "Integral type required!");
19501 const unsigned NumTypes = 4;
19502 QualType SignedIntegralTypes[NumTypes] = {
19503 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19505 QualType UnsignedIntegralTypes[NumTypes] = {
19506 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19507 Context.UnsignedLongLongTy
19510 unsigned BitWidth = Context.getTypeSize(T);
19511 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19512 : UnsignedIntegralTypes;
19513 for (unsigned I = 0; I != NumTypes; ++I)
19514 if (Context.getTypeSize(Types[I]) > BitWidth)
19515 return Types[I];
19517 return QualType();
19520 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19521 EnumConstantDecl *LastEnumConst,
19522 SourceLocation IdLoc,
19523 IdentifierInfo *Id,
19524 Expr *Val) {
19525 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19526 llvm::APSInt EnumVal(IntWidth);
19527 QualType EltTy;
19529 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19530 Val = nullptr;
19532 if (Val)
19533 Val = DefaultLvalueConversion(Val).get();
19535 if (Val) {
19536 if (Enum->isDependentType() || Val->isTypeDependent() ||
19537 Val->containsErrors())
19538 EltTy = Context.DependentTy;
19539 else {
19540 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19541 // underlying type, but do allow it in all other contexts.
19542 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19543 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19544 // constant-expression in the enumerator-definition shall be a converted
19545 // constant expression of the underlying type.
19546 EltTy = Enum->getIntegerType();
19547 ExprResult Converted =
19548 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19549 CCEK_Enumerator);
19550 if (Converted.isInvalid())
19551 Val = nullptr;
19552 else
19553 Val = Converted.get();
19554 } else if (!Val->isValueDependent() &&
19555 !(Val =
19556 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19557 .get())) {
19558 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19559 } else {
19560 if (Enum->isComplete()) {
19561 EltTy = Enum->getIntegerType();
19563 // In Obj-C and Microsoft mode, require the enumeration value to be
19564 // representable in the underlying type of the enumeration. In C++11,
19565 // we perform a non-narrowing conversion as part of converted constant
19566 // expression checking.
19567 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19568 if (Context.getTargetInfo()
19569 .getTriple()
19570 .isWindowsMSVCEnvironment()) {
19571 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19572 } else {
19573 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19577 // Cast to the underlying type.
19578 Val = ImpCastExprToType(Val, EltTy,
19579 EltTy->isBooleanType() ? CK_IntegralToBoolean
19580 : CK_IntegralCast)
19581 .get();
19582 } else if (getLangOpts().CPlusPlus) {
19583 // C++11 [dcl.enum]p5:
19584 // If the underlying type is not fixed, the type of each enumerator
19585 // is the type of its initializing value:
19586 // - If an initializer is specified for an enumerator, the
19587 // initializing value has the same type as the expression.
19588 EltTy = Val->getType();
19589 } else {
19590 // C99 6.7.2.2p2:
19591 // The expression that defines the value of an enumeration constant
19592 // shall be an integer constant expression that has a value
19593 // representable as an int.
19595 // Complain if the value is not representable in an int.
19596 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19597 Diag(IdLoc, diag::ext_enum_value_not_int)
19598 << toString(EnumVal, 10) << Val->getSourceRange()
19599 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19600 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19601 // Force the type of the expression to 'int'.
19602 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19604 EltTy = Val->getType();
19610 if (!Val) {
19611 if (Enum->isDependentType())
19612 EltTy = Context.DependentTy;
19613 else if (!LastEnumConst) {
19614 // C++0x [dcl.enum]p5:
19615 // If the underlying type is not fixed, the type of each enumerator
19616 // is the type of its initializing value:
19617 // - If no initializer is specified for the first enumerator, the
19618 // initializing value has an unspecified integral type.
19620 // GCC uses 'int' for its unspecified integral type, as does
19621 // C99 6.7.2.2p3.
19622 if (Enum->isFixed()) {
19623 EltTy = Enum->getIntegerType();
19625 else {
19626 EltTy = Context.IntTy;
19628 } else {
19629 // Assign the last value + 1.
19630 EnumVal = LastEnumConst->getInitVal();
19631 ++EnumVal;
19632 EltTy = LastEnumConst->getType();
19634 // Check for overflow on increment.
19635 if (EnumVal < LastEnumConst->getInitVal()) {
19636 // C++0x [dcl.enum]p5:
19637 // If the underlying type is not fixed, the type of each enumerator
19638 // is the type of its initializing value:
19640 // - Otherwise the type of the initializing value is the same as
19641 // the type of the initializing value of the preceding enumerator
19642 // unless the incremented value is not representable in that type,
19643 // in which case the type is an unspecified integral type
19644 // sufficient to contain the incremented value. If no such type
19645 // exists, the program is ill-formed.
19646 QualType T = getNextLargerIntegralType(Context, EltTy);
19647 if (T.isNull() || Enum->isFixed()) {
19648 // There is no integral type larger enough to represent this
19649 // value. Complain, then allow the value to wrap around.
19650 EnumVal = LastEnumConst->getInitVal();
19651 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19652 ++EnumVal;
19653 if (Enum->isFixed())
19654 // When the underlying type is fixed, this is ill-formed.
19655 Diag(IdLoc, diag::err_enumerator_wrapped)
19656 << toString(EnumVal, 10)
19657 << EltTy;
19658 else
19659 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19660 << toString(EnumVal, 10);
19661 } else {
19662 EltTy = T;
19665 // Retrieve the last enumerator's value, extent that type to the
19666 // type that is supposed to be large enough to represent the incremented
19667 // value, then increment.
19668 EnumVal = LastEnumConst->getInitVal();
19669 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19670 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19671 ++EnumVal;
19673 // If we're not in C++, diagnose the overflow of enumerator values,
19674 // which in C99 means that the enumerator value is not representable in
19675 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19676 // permits enumerator values that are representable in some larger
19677 // integral type.
19678 if (!getLangOpts().CPlusPlus && !T.isNull())
19679 Diag(IdLoc, diag::warn_enum_value_overflow);
19680 } else if (!getLangOpts().CPlusPlus &&
19681 !EltTy->isDependentType() &&
19682 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19683 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19684 Diag(IdLoc, diag::ext_enum_value_not_int)
19685 << toString(EnumVal, 10) << 1;
19690 if (!EltTy->isDependentType()) {
19691 // Make the enumerator value match the signedness and size of the
19692 // enumerator's type.
19693 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19694 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19697 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19698 Val, EnumVal);
19701 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19702 SourceLocation IILoc) {
19703 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19704 !getLangOpts().CPlusPlus)
19705 return SkipBodyInfo();
19707 // We have an anonymous enum definition. Look up the first enumerator to
19708 // determine if we should merge the definition with an existing one and
19709 // skip the body.
19710 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19711 forRedeclarationInCurContext());
19712 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19713 if (!PrevECD)
19714 return SkipBodyInfo();
19716 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19717 NamedDecl *Hidden;
19718 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19719 SkipBodyInfo Skip;
19720 Skip.Previous = Hidden;
19721 return Skip;
19724 return SkipBodyInfo();
19727 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19728 SourceLocation IdLoc, IdentifierInfo *Id,
19729 const ParsedAttributesView &Attrs,
19730 SourceLocation EqualLoc, Expr *Val) {
19731 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19732 EnumConstantDecl *LastEnumConst =
19733 cast_or_null<EnumConstantDecl>(lastEnumConst);
19735 // The scope passed in may not be a decl scope. Zip up the scope tree until
19736 // we find one that is.
19737 S = getNonFieldDeclScope(S);
19739 // Verify that there isn't already something declared with this name in this
19740 // scope.
19741 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19742 LookupName(R, S);
19743 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19745 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19746 // Maybe we will complain about the shadowed template parameter.
19747 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19748 // Just pretend that we didn't see the previous declaration.
19749 PrevDecl = nullptr;
19752 // C++ [class.mem]p15:
19753 // If T is the name of a class, then each of the following shall have a name
19754 // different from T:
19755 // - every enumerator of every member of class T that is an unscoped
19756 // enumerated type
19757 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19758 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19759 DeclarationNameInfo(Id, IdLoc));
19761 EnumConstantDecl *New =
19762 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19763 if (!New)
19764 return nullptr;
19766 if (PrevDecl) {
19767 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19768 // Check for other kinds of shadowing not already handled.
19769 CheckShadow(New, PrevDecl, R);
19772 // When in C++, we may get a TagDecl with the same name; in this case the
19773 // enum constant will 'hide' the tag.
19774 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19775 "Received TagDecl when not in C++!");
19776 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19777 if (isa<EnumConstantDecl>(PrevDecl))
19778 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19779 else
19780 Diag(IdLoc, diag::err_redefinition) << Id;
19781 notePreviousDefinition(PrevDecl, IdLoc);
19782 return nullptr;
19786 // Process attributes.
19787 ProcessDeclAttributeList(S, New, Attrs);
19788 AddPragmaAttributes(S, New);
19790 // Register this decl in the current scope stack.
19791 New->setAccess(TheEnumDecl->getAccess());
19792 PushOnScopeChains(New, S);
19794 ActOnDocumentableDecl(New);
19796 return New;
19799 // Returns true when the enum initial expression does not trigger the
19800 // duplicate enum warning. A few common cases are exempted as follows:
19801 // Element2 = Element1
19802 // Element2 = Element1 + 1
19803 // Element2 = Element1 - 1
19804 // Where Element2 and Element1 are from the same enum.
19805 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19806 Expr *InitExpr = ECD->getInitExpr();
19807 if (!InitExpr)
19808 return true;
19809 InitExpr = InitExpr->IgnoreImpCasts();
19811 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19812 if (!BO->isAdditiveOp())
19813 return true;
19814 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19815 if (!IL)
19816 return true;
19817 if (IL->getValue() != 1)
19818 return true;
19820 InitExpr = BO->getLHS();
19823 // This checks if the elements are from the same enum.
19824 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19825 if (!DRE)
19826 return true;
19828 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19829 if (!EnumConstant)
19830 return true;
19832 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19833 Enum)
19834 return true;
19836 return false;
19839 // Emits a warning when an element is implicitly set a value that
19840 // a previous element has already been set to.
19841 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19842 EnumDecl *Enum, QualType EnumType) {
19843 // Avoid anonymous enums
19844 if (!Enum->getIdentifier())
19845 return;
19847 // Only check for small enums.
19848 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19849 return;
19851 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19852 return;
19854 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19855 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19857 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19859 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19860 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19862 // Use int64_t as a key to avoid needing special handling for map keys.
19863 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19864 llvm::APSInt Val = D->getInitVal();
19865 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19868 DuplicatesVector DupVector;
19869 ValueToVectorMap EnumMap;
19871 // Populate the EnumMap with all values represented by enum constants without
19872 // an initializer.
19873 for (auto *Element : Elements) {
19874 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19876 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19877 // this constant. Skip this enum since it may be ill-formed.
19878 if (!ECD) {
19879 return;
19882 // Constants with initializers are handled in the next loop.
19883 if (ECD->getInitExpr())
19884 continue;
19886 // Duplicate values are handled in the next loop.
19887 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19890 if (EnumMap.size() == 0)
19891 return;
19893 // Create vectors for any values that has duplicates.
19894 for (auto *Element : Elements) {
19895 // The last loop returned if any constant was null.
19896 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19897 if (!ValidDuplicateEnum(ECD, Enum))
19898 continue;
19900 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19901 if (Iter == EnumMap.end())
19902 continue;
19904 DeclOrVector& Entry = Iter->second;
19905 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19906 // Ensure constants are different.
19907 if (D == ECD)
19908 continue;
19910 // Create new vector and push values onto it.
19911 auto Vec = std::make_unique<ECDVector>();
19912 Vec->push_back(D);
19913 Vec->push_back(ECD);
19915 // Update entry to point to the duplicates vector.
19916 Entry = Vec.get();
19918 // Store the vector somewhere we can consult later for quick emission of
19919 // diagnostics.
19920 DupVector.emplace_back(std::move(Vec));
19921 continue;
19924 ECDVector *Vec = Entry.get<ECDVector*>();
19925 // Make sure constants are not added more than once.
19926 if (*Vec->begin() == ECD)
19927 continue;
19929 Vec->push_back(ECD);
19932 // Emit diagnostics.
19933 for (const auto &Vec : DupVector) {
19934 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19936 // Emit warning for one enum constant.
19937 auto *FirstECD = Vec->front();
19938 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19939 << FirstECD << toString(FirstECD->getInitVal(), 10)
19940 << FirstECD->getSourceRange();
19942 // Emit one note for each of the remaining enum constants with
19943 // the same value.
19944 for (auto *ECD : llvm::drop_begin(*Vec))
19945 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19946 << ECD << toString(ECD->getInitVal(), 10)
19947 << ECD->getSourceRange();
19951 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19952 bool AllowMask) const {
19953 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19954 assert(ED->isCompleteDefinition() && "expected enum definition");
19956 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19957 llvm::APInt &FlagBits = R.first->second;
19959 if (R.second) {
19960 for (auto *E : ED->enumerators()) {
19961 const auto &EVal = E->getInitVal();
19962 // Only single-bit enumerators introduce new flag values.
19963 if (EVal.isPowerOf2())
19964 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19968 // A value is in a flag enum if either its bits are a subset of the enum's
19969 // flag bits (the first condition) or we are allowing masks and the same is
19970 // true of its complement (the second condition). When masks are allowed, we
19971 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19973 // While it's true that any value could be used as a mask, the assumption is
19974 // that a mask will have all of the insignificant bits set. Anything else is
19975 // likely a logic error.
19976 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19977 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19980 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19981 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19982 const ParsedAttributesView &Attrs) {
19983 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19984 QualType EnumType = Context.getTypeDeclType(Enum);
19986 ProcessDeclAttributeList(S, Enum, Attrs);
19988 if (Enum->isDependentType()) {
19989 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19990 EnumConstantDecl *ECD =
19991 cast_or_null<EnumConstantDecl>(Elements[i]);
19992 if (!ECD) continue;
19994 ECD->setType(EnumType);
19997 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19998 return;
20001 // TODO: If the result value doesn't fit in an int, it must be a long or long
20002 // long value. ISO C does not support this, but GCC does as an extension,
20003 // emit a warning.
20004 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20005 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20006 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20008 // Verify that all the values are okay, compute the size of the values, and
20009 // reverse the list.
20010 unsigned NumNegativeBits = 0;
20011 unsigned NumPositiveBits = 0;
20013 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20014 EnumConstantDecl *ECD =
20015 cast_or_null<EnumConstantDecl>(Elements[i]);
20016 if (!ECD) continue; // Already issued a diagnostic.
20018 const llvm::APSInt &InitVal = ECD->getInitVal();
20020 // Keep track of the size of positive and negative values.
20021 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20022 // If the enumerator is zero that should still be counted as a positive
20023 // bit since we need a bit to store the value zero.
20024 unsigned ActiveBits = InitVal.getActiveBits();
20025 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20026 } else {
20027 NumNegativeBits =
20028 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20032 // If we have an empty set of enumerators we still need one bit.
20033 // From [dcl.enum]p8
20034 // If the enumerator-list is empty, the values of the enumeration are as if
20035 // the enumeration had a single enumerator with value 0
20036 if (!NumPositiveBits && !NumNegativeBits)
20037 NumPositiveBits = 1;
20039 // Figure out the type that should be used for this enum.
20040 QualType BestType;
20041 unsigned BestWidth;
20043 // C++0x N3000 [conv.prom]p3:
20044 // An rvalue of an unscoped enumeration type whose underlying
20045 // type is not fixed can be converted to an rvalue of the first
20046 // of the following types that can represent all the values of
20047 // the enumeration: int, unsigned int, long int, unsigned long
20048 // int, long long int, or unsigned long long int.
20049 // C99 6.4.4.3p2:
20050 // An identifier declared as an enumeration constant has type int.
20051 // The C99 rule is modified by a gcc extension
20052 QualType BestPromotionType;
20054 bool Packed = Enum->hasAttr<PackedAttr>();
20055 // -fshort-enums is the equivalent to specifying the packed attribute on all
20056 // enum definitions.
20057 if (LangOpts.ShortEnums)
20058 Packed = true;
20060 // If the enum already has a type because it is fixed or dictated by the
20061 // target, promote that type instead of analyzing the enumerators.
20062 if (Enum->isComplete()) {
20063 BestType = Enum->getIntegerType();
20064 if (Context.isPromotableIntegerType(BestType))
20065 BestPromotionType = Context.getPromotedIntegerType(BestType);
20066 else
20067 BestPromotionType = BestType;
20069 BestWidth = Context.getIntWidth(BestType);
20071 else if (NumNegativeBits) {
20072 // If there is a negative value, figure out the smallest integer type (of
20073 // int/long/longlong) that fits.
20074 // If it's packed, check also if it fits a char or a short.
20075 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20076 BestType = Context.SignedCharTy;
20077 BestWidth = CharWidth;
20078 } else if (Packed && NumNegativeBits <= ShortWidth &&
20079 NumPositiveBits < ShortWidth) {
20080 BestType = Context.ShortTy;
20081 BestWidth = ShortWidth;
20082 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20083 BestType = Context.IntTy;
20084 BestWidth = IntWidth;
20085 } else {
20086 BestWidth = Context.getTargetInfo().getLongWidth();
20088 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20089 BestType = Context.LongTy;
20090 } else {
20091 BestWidth = Context.getTargetInfo().getLongLongWidth();
20093 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20094 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20095 BestType = Context.LongLongTy;
20098 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20099 } else {
20100 // If there is no negative value, figure out the smallest type that fits
20101 // all of the enumerator values.
20102 // If it's packed, check also if it fits a char or a short.
20103 if (Packed && NumPositiveBits <= CharWidth) {
20104 BestType = Context.UnsignedCharTy;
20105 BestPromotionType = Context.IntTy;
20106 BestWidth = CharWidth;
20107 } else if (Packed && NumPositiveBits <= ShortWidth) {
20108 BestType = Context.UnsignedShortTy;
20109 BestPromotionType = Context.IntTy;
20110 BestWidth = ShortWidth;
20111 } else if (NumPositiveBits <= IntWidth) {
20112 BestType = Context.UnsignedIntTy;
20113 BestWidth = IntWidth;
20114 BestPromotionType
20115 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20116 ? Context.UnsignedIntTy : Context.IntTy;
20117 } else if (NumPositiveBits <=
20118 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20119 BestType = Context.UnsignedLongTy;
20120 BestPromotionType
20121 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20122 ? Context.UnsignedLongTy : Context.LongTy;
20123 } else {
20124 BestWidth = Context.getTargetInfo().getLongLongWidth();
20125 assert(NumPositiveBits <= BestWidth &&
20126 "How could an initializer get larger than ULL?");
20127 BestType = Context.UnsignedLongLongTy;
20128 BestPromotionType
20129 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20130 ? Context.UnsignedLongLongTy : Context.LongLongTy;
20134 // Loop over all of the enumerator constants, changing their types to match
20135 // the type of the enum if needed.
20136 for (auto *D : Elements) {
20137 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20138 if (!ECD) continue; // Already issued a diagnostic.
20140 // Standard C says the enumerators have int type, but we allow, as an
20141 // extension, the enumerators to be larger than int size. If each
20142 // enumerator value fits in an int, type it as an int, otherwise type it the
20143 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20144 // that X has type 'int', not 'unsigned'.
20146 // Determine whether the value fits into an int.
20147 llvm::APSInt InitVal = ECD->getInitVal();
20149 // If it fits into an integer type, force it. Otherwise force it to match
20150 // the enum decl type.
20151 QualType NewTy;
20152 unsigned NewWidth;
20153 bool NewSign;
20154 if (!getLangOpts().CPlusPlus &&
20155 !Enum->isFixed() &&
20156 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20157 NewTy = Context.IntTy;
20158 NewWidth = IntWidth;
20159 NewSign = true;
20160 } else if (ECD->getType() == BestType) {
20161 // Already the right type!
20162 if (getLangOpts().CPlusPlus)
20163 // C++ [dcl.enum]p4: Following the closing brace of an
20164 // enum-specifier, each enumerator has the type of its
20165 // enumeration.
20166 ECD->setType(EnumType);
20167 continue;
20168 } else {
20169 NewTy = BestType;
20170 NewWidth = BestWidth;
20171 NewSign = BestType->isSignedIntegerOrEnumerationType();
20174 // Adjust the APSInt value.
20175 InitVal = InitVal.extOrTrunc(NewWidth);
20176 InitVal.setIsSigned(NewSign);
20177 ECD->setInitVal(InitVal);
20179 // Adjust the Expr initializer and type.
20180 if (ECD->getInitExpr() &&
20181 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20182 ECD->setInitExpr(ImplicitCastExpr::Create(
20183 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20184 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20185 if (getLangOpts().CPlusPlus)
20186 // C++ [dcl.enum]p4: Following the closing brace of an
20187 // enum-specifier, each enumerator has the type of its
20188 // enumeration.
20189 ECD->setType(EnumType);
20190 else
20191 ECD->setType(NewTy);
20194 Enum->completeDefinition(BestType, BestPromotionType,
20195 NumPositiveBits, NumNegativeBits);
20197 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20199 if (Enum->isClosedFlag()) {
20200 for (Decl *D : Elements) {
20201 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20202 if (!ECD) continue; // Already issued a diagnostic.
20204 llvm::APSInt InitVal = ECD->getInitVal();
20205 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20206 !IsValueInFlagEnum(Enum, InitVal, true))
20207 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20208 << ECD << Enum;
20212 // Now that the enum type is defined, ensure it's not been underaligned.
20213 if (Enum->hasAttrs())
20214 CheckAlignasUnderalignment(Enum);
20217 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20218 SourceLocation StartLoc,
20219 SourceLocation EndLoc) {
20220 StringLiteral *AsmString = cast<StringLiteral>(expr);
20222 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20223 AsmString, StartLoc,
20224 EndLoc);
20225 CurContext->addDecl(New);
20226 return New;
20229 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20230 auto *New = TopLevelStmtDecl::Create(Context, Statement);
20231 Context.getTranslationUnitDecl()->addDecl(New);
20232 return New;
20235 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20236 IdentifierInfo* AliasName,
20237 SourceLocation PragmaLoc,
20238 SourceLocation NameLoc,
20239 SourceLocation AliasNameLoc) {
20240 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20241 LookupOrdinaryName);
20242 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20243 AttributeCommonInfo::Form::Pragma());
20244 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20245 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20247 // If a declaration that:
20248 // 1) declares a function or a variable
20249 // 2) has external linkage
20250 // already exists, add a label attribute to it.
20251 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20252 if (isDeclExternC(PrevDecl))
20253 PrevDecl->addAttr(Attr);
20254 else
20255 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20256 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20257 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20258 } else
20259 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20262 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20263 SourceLocation PragmaLoc,
20264 SourceLocation NameLoc) {
20265 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20267 if (PrevDecl) {
20268 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20269 } else {
20270 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20274 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20275 IdentifierInfo* AliasName,
20276 SourceLocation PragmaLoc,
20277 SourceLocation NameLoc,
20278 SourceLocation AliasNameLoc) {
20279 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20280 LookupOrdinaryName);
20281 WeakInfo W = WeakInfo(Name, NameLoc);
20283 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20284 if (!PrevDecl->hasAttr<AliasAttr>())
20285 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20286 DeclApplyPragmaWeak(TUScope, ND, W);
20287 } else {
20288 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20292 ObjCContainerDecl *Sema::getObjCDeclContext() const {
20293 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20296 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20297 bool Final) {
20298 assert(FD && "Expected non-null FunctionDecl");
20300 // SYCL functions can be template, so we check if they have appropriate
20301 // attribute prior to checking if it is a template.
20302 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20303 return FunctionEmissionStatus::Emitted;
20305 // Templates are emitted when they're instantiated.
20306 if (FD->isDependentContext())
20307 return FunctionEmissionStatus::TemplateDiscarded;
20309 // Check whether this function is an externally visible definition.
20310 auto IsEmittedForExternalSymbol = [this, FD]() {
20311 // We have to check the GVA linkage of the function's *definition* -- if we
20312 // only have a declaration, we don't know whether or not the function will
20313 // be emitted, because (say) the definition could include "inline".
20314 const FunctionDecl *Def = FD->getDefinition();
20316 return Def && !isDiscardableGVALinkage(
20317 getASTContext().GetGVALinkageForFunction(Def));
20320 if (LangOpts.OpenMPIsTargetDevice) {
20321 // In OpenMP device mode we will not emit host only functions, or functions
20322 // we don't need due to their linkage.
20323 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20324 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20325 // DevTy may be changed later by
20326 // #pragma omp declare target to(*) device_type(*).
20327 // Therefore DevTy having no value does not imply host. The emission status
20328 // will be checked again at the end of compilation unit with Final = true.
20329 if (DevTy)
20330 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20331 return FunctionEmissionStatus::OMPDiscarded;
20332 // If we have an explicit value for the device type, or we are in a target
20333 // declare context, we need to emit all extern and used symbols.
20334 if (isInOpenMPDeclareTargetContext() || DevTy)
20335 if (IsEmittedForExternalSymbol())
20336 return FunctionEmissionStatus::Emitted;
20337 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20338 // we'll omit it.
20339 if (Final)
20340 return FunctionEmissionStatus::OMPDiscarded;
20341 } else if (LangOpts.OpenMP > 45) {
20342 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20343 // function. In 5.0, no_host was introduced which might cause a function to
20344 // be ommitted.
20345 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20346 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20347 if (DevTy)
20348 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20349 return FunctionEmissionStatus::OMPDiscarded;
20352 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20353 return FunctionEmissionStatus::Emitted;
20355 if (LangOpts.CUDA) {
20356 // When compiling for device, host functions are never emitted. Similarly,
20357 // when compiling for host, device and global functions are never emitted.
20358 // (Technically, we do emit a host-side stub for global functions, but this
20359 // doesn't count for our purposes here.)
20360 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20361 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20362 return FunctionEmissionStatus::CUDADiscarded;
20363 if (!LangOpts.CUDAIsDevice &&
20364 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20365 return FunctionEmissionStatus::CUDADiscarded;
20367 if (IsEmittedForExternalSymbol())
20368 return FunctionEmissionStatus::Emitted;
20371 // Otherwise, the function is known-emitted if it's in our set of
20372 // known-emitted functions.
20373 return FunctionEmissionStatus::Unknown;
20376 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20377 // Host-side references to a __global__ function refer to the stub, so the
20378 // function itself is never emitted and therefore should not be marked.
20379 // If we have host fn calls kernel fn calls host+device, the HD function
20380 // does not get instantiated on the host. We model this by omitting at the
20381 // call to the kernel from the callgraph. This ensures that, when compiling
20382 // for host, only HD functions actually called from the host get marked as
20383 // known-emitted.
20384 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20385 IdentifyCUDATarget(Callee) == CFT_Global;