Lines Matching +full:local +full:- +full:bd +full:- +full:address +full:- +full:broken

1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 //===----------------------------------------------------------------------===//
96 if (!AllowInvalidDecl && ND->isInvalidDecl())
109 // An injected-class-name of a class template (specialization) is valid
110 // as a template or as a non-template.
113 if (!RD || !RD->isInjectedClassName())
115 RD = cast<CXXRecordDecl>(RD->getDeclContext());
116 return RD->getDescribedClassTemplate() ||
155 if (!RD->hasDefinition())
160 for (const auto &Base : RD->bases()) {
162 if (auto *BaseTT = Base.getType()->getAs<TagType>())
163 BaseRD = BaseTT->getAsCXXRecordDecl();
164 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
167 if (!TST || !TST->isDependentType())
169 auto *TD = TST->getTemplateName().getAsTemplateDecl();
173 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
174 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
178 CTD->findPartialSpecialization(Base.getType()))
179 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
185 for (NamedDecl *ND : BaseRD->lookup(&II)) {
216 DC = DC->getParent()) {
220 if (RD && RD->getDescribedClassTemplate())
248 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
252 switch (T->getTypeClass()) {
271 if (!SS || SS->isEmpty())
283 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
304 if (ObjectType->isRecordType())
306 } else if (SS && SS->isNotEmpty()) {
312 // A qualified-id that refers to a type and in which the
313 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // qualified-id denotes a type, forming an
316 // elaborated-type-specifier (7.1.5.3).
327 SourceLocation QualifiedLoc = SS->getRange().getBegin();
332 << SS->getScopeRep() << II.getName()
343 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
354 if (!LookupCtx->isDependentContext() &&
360 // lookup for class-names.
368 // nested-name-specifier.
373 // If the unqualified-id is ~type-name, the type-name is looked up
374 // in the context of the entire postfix-expression. If the type T of
375 // the object expression is of a class type C, the type-name is also
377 // find a name that refers to (possibly cv-qualified) T.
386 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
414 // Ignore a correction to a template type as the to-be-corrected
430 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
441 SS->getScopeRep(), &II);
445 TL.setQualifierLoc(SS->getWithLocInContext(Context));
456 // Recover from type-hiding ambiguities by hiding the type. We'll
469 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
475 RealRes->getLocation() < IIDecl->getLocation()) {
509 // C++ [class.qual]p2: A lookup that would find the injected-class-name
511 // This is ill-formed when we're not actually forming a ctor or dtor name.
515 FoundRD->isInjectedClassName() &&
516 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
523 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
535 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
537 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
561 for (;; DC = DC->getLookupParent()) {
562 DC = DC->getPrimaryContext();
564 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
567 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
568 RD->getTypeForDecl());
577 /// up allowing unqualified dependent type names at class-level, which MSVC
581 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
582 DC = DC->getPrimaryContext();
584 if (MD->getParent()->hasAnyDependentBases())
585 return MD->getParent();
593 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
596 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
598 // until instantiation time by making a non-dependent DependentTypeName. We
610 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
611 RD->getTypeForDecl());
646 switch (TD->getTagKind()) {
664 if (CurContext->isRecord()) {
665 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
668 const Type *Ty = SS->getScopeRep()->getAsType();
671 for (const auto &Base : RD->bases())
674 return S->isFunctionPrototypeScope();
676 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
686 if (II->isEditorPlaceholder())
699 // FIXME: Support error recovery for the template-name case.
709 // We found a similarly-named type or interface; suggest that.
710 if (!SS || !SS->isSet()) {
718 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
723 << II << DC << DroppedSpecifier << SS->getRange(),
764 if (!SS || (!SS->isSet() && !SS->isInvalid()))
771 << II << DC << SS->getRange();
772 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
780 Diag(SS->getRange().getBegin(), DiagID)
781 << SS->getScopeRep() << II->getName()
782 << SourceRange(SS->getRange().getBegin(), IILoc)
783 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
787 assert(SS && SS->isInvalid() &&
817 switch (Tag->getTagKind()) {
846 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
871 // injected-class-name. We don't have a classification for that.
892 // Perform lookup for Objective-C instance variables (including automatically
893 // synthesized instance variables), if we're in an Objective-C method.
914 // If an unqualified-id is followed by a '(', then we have a function
917 // In C++, this is an ADL-only call.
943 // In C++20 onwards, this could be an ADL-only call to a function
989 Name->getName() == CorrectedStr;
1009 // If we found an Objective-C instance variable, let
1015 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1033 // dependent nested-name-specifier.
1037 // dependent on a template-parameter is assumed not to name a type
1043 // template-argument-list, which would indicate a missing 'template'
1057 // C++ [temp.local]p3:
1058 // A lookup that finds an injected-class-name (10.2) can result in an
1060 // one base class). If all of the injected-class-names that are found
1062 // is followed by a template-argument-list, the reference refers to the
1087 // After name lookup (3.4) finds that a name is a template-name or that
1088 // an operator-function-id or a literal- operator-id refers to a set of
1091 // template-argument-list and never as the less-than operator.
1094 // unqualified-id followed by a < and name lookup finds either one
1102 if (Result.end() - Result.begin() > 1) {
1116 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1122 // All results were non-template functions. This is a function template
1148 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1151 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1160 Class = Alias->getClassInterface();
1168 // Just return "unknown" as a fall-through for now.
1196 // Check for a tag type hidden by a non-type decl in a few cases where it
1197 // seems likely a type is wanted instead of the non-type that was found.
1201 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1209 // that declaration directly. Defer resolving even non-overloaded class
1214 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1228 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1250 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1254 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1266 if ((*ULE->decls_begin())->isCXXClassMember()) {
1268 SS.Adopt(ULE->getQualifierLoc());
1271 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1273 Result.setNamingClass(ULE->getNamingClass());
1274 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1307 assert(DC->getLexicalParent() == CurContext &&
1310 S->setEntity(DC);
1316 CurContext = CurContext->getLexicalParent();
1323 // the containing DC of TD, because the new context will be some pre-existing
1326 CurContext = cast<TagDecl>(D)->getDefinition();
1329 // into the pre-existing complete definition.
1330 S->setEntity(CurContext->getLookupParent());
1341 // X (after the qualified-id of the static member) is looked up as
1346 // the variable member (after the declarator-id) is looked up as
1355 assert(!S->getEntity() && "scope already has entity");
1358 Scope *Ancestor = S->getParent();
1359 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1364 S->setEntity(DC);
1366 if (S->getParent()->isTemplateParamScope()) {
1367 // Also set the corresponding entities for all immediately-enclosing
1369 EnterTemplatedContext(S->getParent(), DC);
1374 assert(S->getEntity() == CurContext && "Context imbalance!");
1378 Scope *Ancestor = S->getParent();
1379 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1380 CurContext = Ancestor->getEntity();
1387 assert(S->isTemplateParamScope() &&
1390 // C++20 [temp.local]p7:
1393 // template hides the name of a template-parameter of any enclosing class
1394 // templates (but not a template-parameter of the member if the member is a
1396 // C++20 [temp.local]p9:
1399 // each non-dependent base class (13.8.2.1), if the name of the base class
1401 // template-parameter, the base class name or member name hides the
1402 // template-parameter name (6.4.10).
1412 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1414 for (; DC; DC = DC->getLookupParent()) {
1416 cast<Decl>(DC)->getDescribedTemplateParams()) {
1417 unsigned DCDepth = TPL->getDepth() + 1;
1421 SearchDCAfterScope = DC = DC->getLookupParent();
1425 S->setLookupEntity(SearchDCAfterScope);
1432 FunctionDecl *FD = D->getAsFunction();
1437 // from the lexical parent, rather than the top-level class.
1438 assert(CurContext == FD->getLexicalParent() &&
1441 S->setEntity(CurContext);
1443 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1444 ParmVarDecl *Param = FD->getParamDecl(P);
1446 if (Param->getIdentifier()) {
1447 S->AddDecl(Param);
1455 // rather than the top-level class.
1457 CurContext = CurContext->getLexicalParent();
1472 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1487 return ND->hasAttr<OverloadableAttr>();
1490 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1497 // non-transparent context. The declaration will be introduced into this
1499 while (S->getEntity() && S->getEntity()->isTransparentContext())
1500 S = S->getParent();
1506 CurContext->addDecl(D);
1508 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1509 // are function-local declarations.
1510 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1515 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1518 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1519 S->AddDecl(D);
1523 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1526 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1527 S->RemoveDecl(*I);
1535 S->AddDecl(D);
1537 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1538 // Implicitly-generated labels may end up getting generated in an order that
1541 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1542 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1544 if (!S->isDeclScope(*I))
1546 } else if (IDC->Encloses(CurContext))
1563 DeclContext *TargetDC = DC->getPrimaryContext();
1565 if (DeclContext *ScopeDC = S->getEntity())
1566 if (ScopeDC->getPrimaryContext() == TargetDC)
1568 } while ((S = S->getParent()));
1599 // - If the declaration is a non-dependent friend declaration that nominates a
1600 // function with a declarator-id that is a qualified-id or template-id or that
1601 // nominates a class other than with an elaborated-type-specifier with neither
1602 // a nested-name-specifier nor a simple-template-id, it is attached to the
1604 if (New->getFriendObjectKind() &&
1605 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1606 New->setLocalOwningModule(Old->getOwningModule());
1611 Module *NewM = New->getOwningModule();
1612 Module *OldM = Old->getOwningModule();
1614 if (NewM && NewM->isPrivateModule())
1615 NewM = NewM->Parent;
1616 if (OldM && OldM->isPrivateModule())
1617 OldM = OldM->Parent;
1625 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1630 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1635 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1636 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1641 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1644 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1646 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1647 Diag(Old->getLocation(), diag::note_previous_declaration);
1648 New->setInvalidDecl();
1657 // An export-declaration shall inhabit a namespace scope.
1661 if (!New->getLexicalDeclContext()
1662 ->getNonTransparentContext()
1663 ->isFileContext() ||
1664 !Old->getLexicalDeclContext()
1665 ->getNonTransparentContext()
1666 ->isFileContext())
1669 bool IsNewExported = New->isInExportDeclContext();
1670 bool IsOldExported = Old->isInExportDeclContext();
1683 // https://github.com/llvm/llvm-project/issues/98583 for details.
1684 if (!Old->isInNamedModule() && New->getOwningModule() &&
1685 New->getOwningModule()->isImplicitGlobalModule())
1690 auto Lk = Old->getFormalLinkage();
1696 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1697 Diag(Old->getLocation(), diag::note_previous_declaration);
1716 assert(const_cast<Sema *>(this)->isReachable(New) &&
1717 const_cast<Sema *>(this)->isReachable(Old) &&
1720 Module *NewM = New->getOwningModule();
1721 Module *OldM = Old->getOwningModule();
1729 // //--- M.cppm
1734 // //--- Use.cpp
1747 if (NewM && NewM->isHeaderLikeModule())
1749 if (OldM && OldM->isHeaderLikeModule())
1758 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1763 NewM = NewM->getTopLevelModule();
1765 OldM = OldM->getTopLevelModule();
1770 if (D->getDeclContext()->isFileContext())
1799 if (D->doesThisDeclarationHaveABody())
1803 return CD->isCopyConstructor();
1804 return D->isCopyAssignmentOperator();
1808 const DeclContext *DC = D->getDeclContext();
1809 while (!DC->isTranslationUnit()) {
1811 if (!RD->hasNameForLinkage())
1814 DC = DC->getParent();
1817 return !D->isExternallyVisible();
1831 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1834 // Ignore all entities declared within templates, and out-of-line definitions
1836 if (D->getDeclContext()->isDependentContext() ||
1837 D->getLexicalDeclContext()->isDependentContext())
1841 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1843 // A non-out-of-line declaration of a member specialization was implicitly
1844 // instantiated; it's the out-of-line declaration that we're interested in.
1845 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1846 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1850 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1854 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1858 if (FD->doesThisDeclarationHaveABody() &&
1865 if (!isMainFileLoc(*this, VD->getLocation()))
1871 if (VD->isStaticDataMember() &&
1872 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1874 if (VD->isStaticDataMember() &&
1875 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1876 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1879 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1886 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1896 const FunctionDecl *First = FD->getFirstDecl();
1902 const VarDecl *First = VD->getFirstDecl();
1913 if (D->isInvalidDecl())
1921 for (const auto *BD : DD->bindings()) {
1922 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1924 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1928 } else if (!D->getDeclName()) {
1930 } else if (D->isReferenced() || D->isUsed()) {
1934 if (D->isPlaceholderVar(LangOpts))
1937 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1938 D->hasAttr<CleanupAttr>())
1944 // Except for labels, we only care about unused decls that are local to
1946 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1947 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1950 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1957 // White-list anything that isn't a local variable.
1961 // Types of valid local variables should be complete, so this should succeed.
1964 const Expr *Init = VD->getInit();
1966 Init = Cleanups->getSubExpr();
1968 const auto *Ty = VD->getType().getTypePtr();
1971 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1973 if (TT->getDecl()->hasAttr<UnusedAttr>())
1980 MTE && MTE->getExtendingDecl()) {
1981 Ty = VD->getType().getNonReferenceType().getTypePtr();
1982 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1987 if (Ty->isIncompleteType() || Ty->isDependentType())
1992 Ty = Ty->getBaseElementTypeUnsafe();
1994 if (const TagType *TT = Ty->getAs<TagType>()) {
1995 const TagDecl *Tag = TT->getDecl();
1996 if (Tag->hasAttr<UnusedAttr>())
2000 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2005 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2006 if (Construct && !Construct->isElidable()) {
2007 const CXXConstructorDecl *CD = Construct->getConstructor();
2008 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2009 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2014 // it could possibly be non-trivial constructor.
2015 if (Init->isTypeDependent()) {
2016 for (const CXXConstructorDecl *Ctor : RD->ctors())
2017 if (!Ctor->isTrivial())
2039 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2044 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2055 if (D->getTypeForDecl()->isDependentType())
2058 for (auto *TmpD : D->decls()) {
2077 // at end-of-translation-unit.
2086 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2093 SourceLocation DiagLoc = D->getLocation();
2101 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2105 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2108 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2110 if (Ty->isReferenceType() || Ty->isDependentType())
2113 if (const TagType *TT = Ty->getAs<TagType>()) {
2114 const TagDecl *Tag = TT->getDecl();
2115 if (Tag->hasAttr<UnusedAttr>())
2120 RD && !RD->hasAttr<WarnUnusedAttr>())
2124 // Don't warn about __block Objective-C pointer variables, as they might
2127 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2130 // Don't warn about Objective-C pointer variables with precise lifetime
2133 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2140 assert(iter->getSecond() >= 0 &&
2142 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2152 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2159 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2165 // or address of a label taken, but no definition of it. Label fwd
2169 if (L->isMSAsmLabel())
2170 Diagnose = !L->isResolvedMSAsmLabel();
2172 Diagnose = L->getStmt() == nullptr;
2174 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2179 S->applyNRVO();
2181 if (S->decl_empty()) return;
2182 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2185 /// We visit the decls in non-deterministic order, but we want diagnostics
2203 for (auto *TmpD : S->decls()) {
2210 if (!S->hasUnrecoverableErrorOccurred()) {
2220 if (!D->getDeclName()) continue;
2236 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2237 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2239 << D << FD << FD->getParent());
2246 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2261 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2262 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2263 (S->isClassScope() && !getLangOpts().CPlusPlus))
2264 S = S->getParent();
2292 CLinkageDecl->setImplicit();
2293 Parent->addDecl(CLinkageDecl);
2307 Type->isFunctionProtoType(), ConstexprKind);
2308 New->setImplicit();
2309 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2315 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2318 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2319 parm->setScopeInfo(0, i);
2322 New->setParams(Params);
2379 // TUScope is the translation-unit scope to insert this function into.
2384 CurContext = New->getDeclContext();
2409 // Non-hidden declarations are never ignored.
2416 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2417 Decl->getUnderlyingType()))
2422 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2423 Decl->getAnonDeclWithTypedefName())
2436 OldType = OldTypedef->getUnderlyingType();
2439 QualType NewType = New->getUnderlyingType();
2441 if (NewType->isVariablyModifiedType()) {
2442 // Must not redefine a typedef with a variably-modified type.
2444 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2446 if (Old->getLocation().isValid())
2447 notePreviousDefinition(Old, New->getLocation());
2448 New->setInvalidDecl();
2453 !OldType->isDependentType() &&
2454 !NewType->isDependentType() &&
2457 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2459 if (Old->getLocation().isValid())
2460 notePreviousDefinition(Old, New->getLocation());
2461 New->setInvalidDecl();
2471 if (New->isInvalidDecl()) return;
2473 // Allow multiple definitions for ObjC built-in typedefs.
2476 const IdentifierInfo *TypeID = New->getIdentifier();
2477 switch (TypeID->getLength()) {
2481 if (!TypeID->isStr("id"))
2483 QualType T = New->getUnderlyingType();
2484 if (!T->isPointerType())
2486 if (!T->isVoidPointerType()) {
2487 QualType PT = T->castAs<PointerType>()->getPointeeType();
2488 if (!PT->isStructureType())
2492 // Install the built-in type for 'id', ignoring the current definition.
2493 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2497 if (!TypeID->isStr("Class"))
2499 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2500 // Install the built-in type for 'Class', ignoring the current definition.
2501 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2504 if (!TypeID->isStr("SEL"))
2506 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2507 // Install the built-in type for 'SEL', ignoring the current definition.
2508 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2511 // Fall through - the typedef name was not a builtin type.
2517 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2518 << New->getDeclName();
2521 if (OldD->getLocation().isValid())
2522 notePreviousDefinition(OldD, New->getLocation());
2524 return New->setInvalidDecl();
2528 if (Old->isInvalidDecl())
2529 return New->setInvalidDecl();
2532 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2533 auto *NewTag = New->getAnonDeclWithTypedefName();
2536 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2540 New->setTypeForDecl(OldTD->getTypeForDecl());
2541 if (OldTD->isModed())
2542 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2543 OldTD->getUnderlyingType());
2545 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2554 for (auto *D : NewTag->decls()) {
2556 assert(EnumScope->isDeclScope(ED));
2557 EnumScope->RemoveDecl(ED);
2559 ED->getLexicalDeclContext()->removeDecl(ED);
2573 New->setPreviousDecl(Typedef);
2582 // In a given non-class scope, a typedef specifier can be used to
2590 // any class-name declared in that scope that is not also a typedef-name
2612 Diag(New->getLocation(), diag::err_redefinition)
2613 << New->getDeclName();
2614 notePreviousDefinition(Old, New->getLocation());
2615 return New->setInvalidDecl();
2624 // -Wtypedef-redefinition. If either the original or the redefinition is
2628 (Old->isImplicit() ||
2629 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2630 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2633 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2634 << New->getDeclName();
2635 notePreviousDefinition(Old, New->getLocation());
2638 /// DeclhasAttr - returns true if decl Declaration already has the target
2643 for (const auto *i : D->attrs())
2644 if (i->getKind() == A->getKind()) {
2646 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2652 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2661 return VD->isThisDeclarationADefinition();
2663 return TD->isCompleteDefinition() || TD->isBeingDefined();
2677 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2684 if (I->isAlignmentDependent())
2687 if (I->isAlignas())
2690 unsigned Align = I->getAlignment(S.Context);
2700 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2701 if (I->isAlignmentDependent())
2704 if (I->isAlignas())
2707 unsigned Align = I->getAlignment(S.Context);
2723 Ty = VD->getType();
2734 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2737 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2743 // if any declaration of an entity has an alignment-specifier,
2750 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2752 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2760 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2761 Clone->setInherited(true);
2762 New->addAttr(Clone);
2768 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2769 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2770 Clone->setInherited(true);
2771 New->addAttr(Clone);
2800 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2801 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2802 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2803 AA->getPriority(), AA->getEnvironment());
2805 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2807 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2813 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2815 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2816 FA->getFirstArg());
2818 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2820 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2822 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2823 IA->getInheritanceModel());
2826 &S.Context.Idents.get(AA->getSpelling()));
2836 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2851 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2863 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2864 NT->getZ());
2866 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2870 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2871 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2874 NewAttr->setInherited(true);
2875 D->addAttr(NewAttr);
2886 return TD->getDefinition();
2888 const VarDecl *Def = VD->getDefinition();
2891 return VD->getActingDefinition();
2895 if (FD->isDefined(Def, true))
2902 for (const auto *Attribute : D->attrs())
2903 if (Attribute->getKind() == Kind)
2908 /// checkNewAttributesAfterDef - If we already have a definition, check that
2911 if (!New->hasAttrs())
2918 AttrVec &NewAttributes = New->getAttrs();
2930 --E;
2935 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2939 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2941 S.notePreviousDefinition(Def, VD->getLocation());
2943 S.Diag(Def->getLocation(), diag::note_previous_definition);
2944 VD->setInvalidDecl();
2952 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2958 if (hasAttribute(Def, NewAttribute->getKind())) {
2972 if (AA->isAlignas()) {
2974 // if any declaration of an entity has an alignment-specifier,
2981 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2983 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2986 --E;
2994 S.Diag(NewAttribute->getLocation(),
2996 S.Diag(Def->getLocation(), diag::note_previous_definition);
2998 --E;
3002 cast<VarDecl>(New)->isInline() &&
3003 !cast<VarDecl>(New)->isInlineSpecified()) {
3017 S.Diag(NewAttribute->getLocation(),
3019 S.Diag(Def->getLocation(), diag::note_previous_definition);
3021 --E;
3028 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3060 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3061 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3063 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3067 S.Diag(CIAttr->getLocation(),
3068 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3070 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3071 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3072 << CIAttr->isConstinit()
3079 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3080 UsedAttr *NewAttr = OldAttr->clone(Context);
3081 NewAttr->setInherited(true);
3082 New->addAttr(NewAttr);
3084 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3085 RetainAttr *NewAttr = OldAttr->clone(Context);
3086 NewAttr->setInherited(true);
3087 New->addAttr(NewAttr);
3090 if (!Old->hasAttrs() && !New->hasAttrs())
3096 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3097 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3104 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3106 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3111 // that's ill-formed. (Note that we do not apply this to the attribute
3113 if (OldConstInit && OldConstInit->isConstinit())
3123 NewVD->dropAttr<ConstInitAttr>();
3128 // Attributes declared post-definition are currently ignored.
3131 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3132 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3133 if (!OldA->isEquivalent(NewA)) {
3135 Diag(New->getLocation(), diag::err_different_asm_label);
3136 Diag(OldA->getLocation(), diag::note_previous_declaration);
3138 } else if (Old->isUsed()) {
3140 // already been ODR-used.
3141 Diag(New->getLocation(), diag::err_late_asm_label_name)
3142 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3146 // Re-declaration cannot add abi_tag's.
3147 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3148 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3149 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3150 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3151 Diag(NewAbiTagAttr->getLocation(),
3154 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3158 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3159 Diag(Old->getLocation(), diag::note_previous_declaration);
3164 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3166 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3167 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3168 Diag(Old->getLocation(), diag::note_previous_declaration);
3173 // Redeclaration adds code-seg attribute.
3174 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3175 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3176 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3177 Diag(New->getLocation(), diag::warn_mismatched_section)
3179 Diag(Old->getLocation(), diag::note_previous_declaration);
3182 if (!Old->hasAttrs())
3185 bool foundAny = New->hasAttrs();
3189 if (!foundAny) New->setAttrs(AttrVec());
3191 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3221 if (!foundAny) New->dropAttrs();
3224 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3231 // carries_dependency attribute for its declarator-id if any declaration
3233 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3234 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3235 S.Diag(CDA->getLocation(),
3240 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3242 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3243 S.Diag(FirstVD->getLocation(),
3252 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3253 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3259 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3260 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3262 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3267 if (!oldDecl->hasAttrs())
3270 bool foundAny = newDecl->hasAttrs();
3274 if (!foundAny) newDecl->setAttrs(AttrVec());
3276 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3279 cast<InheritableParamAttr>(I->clone(S.Context));
3280 newAttr->setInherited(true);
3281 newDecl->addAttr(newAttr);
3286 if (!foundAny) newDecl->dropAttrs();
3293 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3296 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3305 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3308 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3309 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3315 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3316 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3317 Ctx.getAsConstantArrayType(New)->getSize();
3321 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3331 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3332 if (auto Newnullability = NewParam->getType()->getNullability()) {
3334 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3337 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3341 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3343 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3346 QualType NewT = NewParam->getType();
3350 NewParam->setType(NewT);
3353 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3354 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3356 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3357 QualType OldParamOT = OldParamDT->getOriginalType();
3358 QualType NewParamOT = NewParamDT->getOriginalType();
3360 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3362 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3386 SourceLocation OldLocation = Old->getLocation();
3387 if (Old->isThisDeclarationADefinition())
3389 else if (Old->isImplicit()) {
3392 if (FD->getBuiltinID())
3396 OldLocation = New->getLocation();
3402 /// canRedefineFunction - checks if a function can be redefined. Currently,
3407 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3409 FD->isInlineSpecified() &&
3410 FD->getStorageClass() == SC_Extern);
3414 const AttributedType *AT = T->getAs<AttributedType>();
3415 while (AT && !AT->isCallingConv())
3416 AT = AT->getModifiedType()->getAs<AttributedType>();
3422 const DeclContext *DC = Old->getDeclContext();
3423 if (DC->isRecord())
3426 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3427 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3429 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3434 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3439 /// using-declaration is valid, given that we know it's not an overload
3447 // -- they shall all refer to the same entity, or all refer to functions
3449 // -- exactly one declaration shall declare a class name or enumeration
3457 // same name and the same parameter-type-list as a function introduced
3458 // by a using-declaration, and the declarations do not declare the same
3459 // function, the program is ill-formed.
3461 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3463 !Old->getDeclContext()->getRedeclContext()->Equals(
3464 New->getDeclContext()->getRedeclContext()) &&
3469 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3470 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3471 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3479 assert(A->getNumParams() == B->getNumParams());
3482 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3483 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3486 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3487 AttrA->isDynamic() == AttrB->isDynamic();
3490 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3505 // along the redeclaration chain (for local extern declarations,
3507 if (!NewD->getQualifier())
3511 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3512 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3513 if (NamedDC->Equals(SemaDC))
3516 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3517 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3520 auto *LexDC = NewD->getLexicalDeclContext();
3524 D->setDeclContext(SemaDC);
3525 D->setLexicalDeclContext(LexDC);
3530 FixSemaDC(FD->getDescribedFunctionTemplate());
3532 FixSemaDC(VD->getDescribedVarTemplate());
3538 FunctionDecl *Old = OldD->getAsFunction();
3541 if (New->getFriendObjectKind()) {
3542 Diag(New->getLocation(), diag::err_using_decl_friend);
3543 Diag(Shadow->getTargetDecl()->getLocation(),
3545 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3553 New->getDescribedFunctionTemplate()) {
3557 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3558 ->getAsFunction();
3562 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3565 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3566 << New->getDeclName();
3567 notePreviousDefinition(OldD, New->getLocation());
3577 if (Old->isInvalidDecl())
3582 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3583 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3584 << Old << Old->getType();
3598 New->getStorageClass() == SC_Static &&
3599 Old->hasExternalFormalLinkage() &&
3600 !New->getTemplateSpecializationInfo() &&
3603 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3604 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3606 Diag(New->getLocation(), diag::err_static_non_static) << New;
3607 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3612 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3613 if (!Old->hasAttr<InternalLinkageAttr>()) {
3614 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3616 Diag(Old->getLocation(), diag::note_previous_declaration);
3617 New->dropAttr<InternalLinkageAttr>();
3620 if (auto *EA = New->getAttr<ErrorAttr>()) {
3621 if (!Old->hasAttr<ErrorAttr>()) {
3622 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3623 Diag(Old->getLocation(), diag::note_previous_declaration);
3624 New->dropAttr<ErrorAttr>();
3632 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3633 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3634 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3639 // broken declaration/definition), this won't matter.
3645 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3646 const auto *A = D->getAttr<OverloadableAttr>();
3647 return A && !A->isImplicit();
3651 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3655 Diag(DiagOld->getLocation(),
3660 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3662 New->dropAttr<OverloadableAttr>();
3668 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3669 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3670 << New->getType() << Old->getType();
3688 QualType OldQType = Context.getCanonicalType(Old->getType());
3689 QualType NewQType = Context.getCanonicalType(New->getType());
3692 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3693 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3697 FunctionDecl *First = Old->getFirstDecl();
3699 First->getType().getCanonicalType()->castAs<FunctionType>();
3700 FunctionType::ExtInfo FI = FT->getExtInfo();
3701 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3707 } else if (Old->getBuiltinID()) {
3714 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3721 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3722 Diag(New->getLocation(), diag::err_cconv_change)
3729 Diag(First->getLocation(), diag::note_previous_declaration);
3744 Diag(New->getLocation(), diag::err_regparm_mismatch)
3745 << NewType->getRegParmType()
3746 << OldType->getRegParmType();
3758 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3772 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3773 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3783 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3785 New->setType(QualType(AdjustedType, 0));
3786 NewQType = Context.getCanonicalType(New->getType());
3791 if (!Old->isInlined() && New->isInlined() &&
3792 !New->hasAttr<GNUInlineAttr>() &&
3794 Old->isUsed(false) &&
3795 !Old->isDefined() && !New->isThisDeclarationADefinition())
3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3801 if (New->hasAttr<GNUInlineAttr>() &&
3802 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3803 UndefinedButUsed.erase(Old->getCanonicalDecl());
3808 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3810 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3811 << New->getDeclName();
3812 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3818 const auto OldFX = Old->getFunctionEffects();
3819 const auto NewFX = New->getFunctionEffects();
3824 Diag(New->getLocation(),
3827 Diag(Old->getLocation(), diag::note_previous_declaration);
3833 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3838 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3839 Old->getLocation());
3841 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3843 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3844 NewFPT->getParamTypes(), EPI);
3846 New->setType(ModQT);
3847 NewQType = New->getType();
3851 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3852 EPI = OldFPT->getExtProtoInfo();
3855 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3862 OldQType = Context.getCanonicalType(Old->getType());
3863 NewQType = Context.getCanonicalType(New->getType());
3870 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3871 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3876 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3877 OldDeclaredReturnType->isObjCObjectPointerType())
3881 if (New->isCXXClassMember() && New->isOutOfLine())
3882 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3883 << New << New->getReturnTypeSourceRange();
3885 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3886 << New->getReturnTypeSourceRange();
3887 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3888 << Old->getReturnTypeSourceRange();
3895 QualType OldReturnType = OldType->getReturnType();
3896 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3900 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3901 if (OldAT && OldAT->isDeduced()) {
3902 QualType DT = OldAT->getDeducedType();
3904 New->setType(SubstAutoTypeDependent(New->getType()));
3907 New->setType(SubstAutoType(New->getType(), DT));
3917 NewMethod->setTrivial(OldMethod->isTrivial());
3923 OldMethod->isFunctionTemplateSpecialization() &&
3924 NewMethod->isFunctionTemplateSpecialization();
3925 bool isFriend = NewMethod->getFriendObjectKind();
3927 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3929 // -- Member function declarations with the same name and the
3932 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3933 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3934 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3940 // member-specification, except that a nested class or member
3953 Diag(New->getLocation(), NewDiag);
3955 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3956 << New << New->getType();
3958 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3966 } else if (OldMethod->isImplicit()) {
3968 NewMethod->setImplicit();
3970 Diag(NewMethod->getLocation(),
3975 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3976 Diag(NewMethod->getLocation(),
3985 // -- Function declarations that differ only in the return type,
4000 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4001 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4002 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4004 Diag(Old->getLocation(), diag::note_previous_declaration);
4009 // carries_dependency attribute for its declarator-id if any declaration
4011 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4012 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4013 Diag(CDA->getLocation(),
4015 Diag(Old->getFirstDecl()->getLocation(),
4021 // return type and the parameter-type-list.
4026 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4042 if (New->getFriendObjectKind() != Decl::FOK_None) {
4043 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4046 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4054 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4055 // about incompatible types under -fms-compatibility.
4061 // local extern declarations), it's OK if they differ. We'll check again
4084 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4085 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4086 if (Old->hasInheritedPrototype())
4087 Old = Old->getCanonicalDecl();
4088 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4089 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4103 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4104 !New->isImplicit() && !Old->isImplicit()) {
4106 if (New->hasWrittenPrototype()) {
4114 if (WithProto->getNumParams() != 0) {
4115 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4117 // warn about that one so long as it's a user-visible declaration.
4123 Diag(WithoutProto->getLocation(),
4125 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4130 // it's a user-visible declaration. There is one exception to this:
4135 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4137 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4143 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4144 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4150 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4151 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4152 OldProto->getParamTypes(),
4153 OldProto->getExtProtoInfo());
4154 New->setType(NewQType);
4155 New->setHasInheritedPrototype();
4159 for (const auto &ParamType : OldProto->param_types()) {
4163 Param->setScopeInfo(0, Params.size());
4164 Param->setImplicit();
4168 New->setParams(Params);
4175 // Check if the function types are compatible when pointer size address
4187 // If a variadic prototype is followed by a non-variadic K&R definition,
4192 Old->hasPrototype() && !New->hasPrototype() &&
4193 New->getType()->getAs<FunctionProtoType>() &&
4194 Old->getNumParams() == New->getNumParams()) {
4198 = Old->getType()->getAs<FunctionProtoType>();
4200 = New->getType()->getAs<FunctionProtoType>();
4203 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4204 NewProto->getReturnType());
4206 for (unsigned Idx = 0, End = Old->getNumParams();
4208 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4209 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4210 if (Context.typesAreCompatible(OldParm->getType(),
4211 NewProto->getParamType(Idx))) {
4212 ArgTypes.push_back(NewParm->getType());
4213 } else if (Context.typesAreCompatible(OldParm->getType(),
4214 NewParm->getType(),
4217 NewProto->getParamType(Idx) };
4219 ArgTypes.push_back(NewParm->getType());
4226 Diag(Warnings[Warn].NewParm->getLocation(),
4229 << Warnings[Warn].OldParm->getType();
4230 if (Warnings[Warn].OldParm->getLocation().isValid())
4231 Diag(Warnings[Warn].OldParm->getLocation(),
4236 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4237 OldProto->getExtProtoInfo()));
4247 // If the previous declaration was an implicitly-generated builtin
4250 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4251 // If it's actually a library-defined builtin function like 'malloc'
4254 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4256 << Old << Old->getType();
4263 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4264 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4274 if (Old->isPureVirtual())
4275 New->setIsPureVirtual();
4278 if (Old->getMostRecentDecl()->isUsed(false))
4279 New->setIsUsed();
4283 if (New->getNumParams() == Old->getNumParams())
4284 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4285 ParmVarDecl *NewParam = New->getParamDecl(i);
4286 ParmVarDecl *OldParam = Old->getParamDecl(i);
4297 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4299 New->setType(Merged);
4308 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4309 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4311 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4317 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4318 oe = oldMethod->param_end();
4320 ni = newMethod->param_begin(), ne = newMethod->param_end();
4328 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4330 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4333 << New->getDeclName() << New->getType() << Old->getType();
4339 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4340 New->setInvalidDecl();
4345 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4350 if (New->getType()->isUndeducedType()) {
4353 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4362 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4363 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4364 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4369 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4370 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4371 PrevVD = PrevVD->getPreviousDecl()) {
4372 QualType PrevVDTy = PrevVD->getType();
4373 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4376 if (!Context.hasSameType(New->getType(), PrevVDTy))
4381 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4382 if (Context.hasSameType(OldArray->getElementType(),
4383 NewArray->getElementType()))
4384 MergedT = New->getType();
4389 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4390 if (Context.hasSameType(OldArray->getElementType(),
4391 NewArray->getElementType()))
4392 MergedT = Old->getType();
4395 else if (New->getType()->isObjCObjectPointerType() &&
4396 Old->getType()->isObjCObjectPointerType()) {
4397 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4398 Old->getType());
4404 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4408 // block-scope variable. In other cases (static data members of class
4412 if ((New->getType()->isDependentType() ||
4413 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4417 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4418 New->setType(Context.DependentTy);
4427 New->setType(MergedT);
4448 return NewVD->isPreviousDeclInSameBlockScope() ||
4449 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4450 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4452 // If the old declaration was function-local, don't merge with its
4454 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4455 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4461 if (New->isInvalidDecl())
4467 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4475 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4480 return New->setInvalidDecl();
4487 return New->setInvalidDecl();
4491 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4492 << New->getDeclName();
4494 New->getLocation());
4495 return New->setInvalidDecl();
4504 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4505 OldTemplate->getTemplateParameters(),
4507 return New->setInvalidDecl();
4510 // A member shall not be declared twice in the member-specification [...]
4513 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4514 Diag(New->getLocation(), diag::err_duplicate_member)
4515 << New->getIdentifier();
4516 Diag(Old->getLocation(), diag::note_previous_declaration);
4517 New->setInvalidDecl();
4521 // Warn if an already-defined variable is made a weak_import in a subsequent
4523 if (New->hasAttr<WeakImportAttr>())
4524 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4525 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4526 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4527 Diag(D->getLocation(), diag::note_previous_definition);
4529 New->dropAttr<WeakImportAttr>();
4534 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4535 if (!Old->hasAttr<InternalLinkageAttr>()) {
4536 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4538 Diag(Old->getLocation(), diag::note_previous_declaration);
4539 New->dropAttr<InternalLinkageAttr>();
4543 VarDecl *MostRecent = Old->getMostRecentDecl();
4547 if (New->isInvalidDecl())
4552 if (New->isInvalidDecl())
4560 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4561 if (New->getStorageClass() == SC_Static &&
4562 !New->isStaticDataMember() &&
4563 Old->hasExternalFormalLinkage()) {
4565 Diag(New->getLocation(), diag::ext_static_non_static)
4566 << New->getDeclName();
4569 Diag(New->getLocation(), diag::err_static_non_static)
4570 << New->getDeclName();
4572 return New->setInvalidDecl();
4576 // For an identifier declared with the storage-class specifier
4584 if (New->hasExternalStorage() && Old->hasLinkage())
4586 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4587 !New->isStaticDataMember() &&
4588 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4589 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4591 return New->setInvalidDecl();
4594 // Check if extern is followed by non-extern and vice-versa.
4595 if (New->hasExternalStorage() &&
4596 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4597 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4599 return New->setInvalidDecl();
4601 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4602 !New->hasExternalStorage()) {
4603 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4605 return New->setInvalidDecl();
4615 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4616 // Don't complain about out-of-line definitions of static members.
4617 !(Old->getLexicalDeclContext()->isRecord() &&
4618 !New->getLexicalDeclContext()->isRecord())) {
4619 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4621 return New->setInvalidDecl();
4624 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4625 if (VarDecl *Def = Old->getDefinition()) {
4628 // its first declaration as inline, the program is ill-formed.
4629 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4630 Diag(Def->getLocation(), diag::note_previous_definition);
4636 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4637 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4638 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4641 if (New->getTLSKind() != Old->getTLSKind()) {
4642 if (!Old->getTLSKind()) {
4643 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4645 } else if (!New->getTLSKind()) {
4646 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4653 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4654 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4661 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4662 Old->getCanonicalDecl()->isConstexpr()) {
4664 Diag(New->getLocation(),
4666 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4667 VarDecl *Def = Old->getDefinition();
4674 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4676 New->setInvalidDecl();
4681 if (Old->getMostRecentDecl()->isUsed(false))
4682 New->setIsUsed();
4685 New->setPreviousDecl(Old);
4687 NewTemplate->setPreviousDecl(OldTemplate);
4690 New->setAccess(Old->getAccess());
4692 NewTemplate->setAccess(New->getAccess());
4694 if (Old->isInline())
4695 New->setImplicitlyInline();
4701 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4706 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4709 SourceLocation IncLoc) -> bool {
4711 // headers, example: a non-modular header H in module A that also gets
4717 << HdrFilename.str() << Mod->getFullModuleName();
4718 if (!Mod->DefinitionLoc.isInvalid())
4719 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4720 << Mod->getFullModuleName();
4737 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4742 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4749 if (Old->getLocation().isValid())
4750 Diag(Old->getLocation(), diag::note_previous_definition);
4755 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4757 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4758 New->getDeclContext()->isDependentContext())) {
4761 New->demoteThisDefinitionToDeclaration();
4764 if (auto *OldTD = Old->getDescribedVarTemplate())
4769 Diag(New->getLocation(), diag::err_redefinition) << New;
4770 notePreviousDefinition(Old, New->getLocation());
4771 New->setInvalidDecl();
4792 ? S->getMSCurManglingNumber()
4793 : S->getMSLastManglingNumber();
4800 if (isa<CXXRecordDecl>(Tag->getParent())) {
4803 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4806 Context.getManglingNumberContext(Tag->getParent());
4813 // If this tag isn't a direct child of a class, number it if it is local.
4817 getCurrentMangleNumberContext(Tag->getDeclContext());
4820 Tag, MCtx->getManglingNumber(
4842 /// Determine whether a class is C-like, according to the rules of C++
4845 if (RD->isInvalidDecl())
4851 // -- have any base classes
4852 if (RD->getNumBases())
4854 SourceRange(RD->bases_begin()->getBeginLoc(),
4855 RD->bases_end()[-1].getEndLoc())};
4857 for (Decl *D : RD->decls()) {
4859 if (D->isInvalidDecl()) {
4864 // -- have any [...] default member initializers
4866 if (FD->hasInClassInitializer()) {
4867 auto *Init = FD->getInClassInitializer();
4869 Init ? Init->getSourceRange() : D->getSourceRange()};
4877 return {NonCLikeKind::Friend, D->getSourceRange()};
4879 // -- declare any members other than non-static data members, member
4886 if (D->isImplicit())
4888 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4891 // -- contain a lambda-expression,
4892 if (MemberRD->isLambda())
4893 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4897 if (MemberRD->isThisDeclarationADefinition()) {
4908 if (TagFromDeclSpec->isInvalidDecl())
4912 if (TagFromDeclSpec->hasNameForLinkage())
4915 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4916 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4919 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4928 // C-like].
4936 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4951 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4954 TextToInsert += NewTD->getIdentifier()->getName();
4961 << NonCLike.Kind - 1 << NonCLike.Range;
4963 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4970 // Otherwise, set this as the anon-decl typedef for the tag.
4971 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4987 if (ED->isScopedUsingClassTag())
4989 if (ED->isScoped())
5022 Tag = CTD->getTemplatedDecl();
5027 Tag->setFreeStanding();
5028 if (Tag->isInvalidDecl())
5034 // or incomplete types shall not be restrict-qualified."
5073 // Track whether this decl-specifier declares anything.
5078 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5081 Record->getDeclContext()->isRecord()) {
5089 if (CurContext->isFunctionOrMethod())
5100 // A struct-declaration that does not declare an anonymous structure or
5101 // anonymous union shall contain a struct-declarator-list.
5103 // This rule also existed in C89 and C99; the grammar for struct-declaration
5104 // did not permit a struct-declaration without a struct-declarator-list.
5105 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5112 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5113 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5114 if ((Tag && Tag->getDeclName()) ||
5120 DS.getRepAsType().get()->getAsStructureType())
5121 Record = RT->getDecl();
5122 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5123 Record = UT->getDecl();
5127 << Record->isUnion() << DS.getSourceRange();
5137 (TagD && TagD->isInvalidDecl()))
5143 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5144 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5157 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5159 << llvm::to_underlying(Tag->getTagKind())
5169 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5183 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5184 // init-declarator-list of the declaration shall not be empty.
5186 // If a cv-qualifier appears in a decl-specifier-seq, the
5187 // init-declarator-list of the declaration shall not be empty.
5194 // Note that a linkage-specification sets a storage class, but
5263 Owner->isRecord() ? Sema::LookupMemberName
5269 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5270 assert(PrevDecl && "Expected a non-null Decl");
5276 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5277 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5278 if (!Owner->isRecord())
5285 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5301 if (Record->isAnonymousStructOrUnion())
5305 for (const Decl *D : Record->decls()) {
5307 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5312 DiagPlaceholderVariableDefinition(ND->getLocation());
5316 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5340 for (auto *D : AnonRecord->decls()) {
5342 cast<NamedDecl>(D)->getDeclName()) {
5344 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5345 VD->getLocation(), AnonRecord->isUnion(),
5360 Chaining.append(IF->chain_begin(), IF->chain_end());
5371 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5372 VD->getType(), {NamedChain, Chaining.size()});
5374 for (const auto *Attr : VD->attrs())
5375 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5377 IndirectField->setAccess(AS);
5378 IndirectField->setImplicit();
5382 if (AS != AS_none) IndirectField->setAccess(AS);
5392 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5418 assert(Record->hasInClassInitializer());
5420 for (const auto *I : Record->decls()) {
5423 FD = IFD->getAnonField();
5424 if (FD && FD->hasInClassInitializer())
5425 return FD->getLocation();
5428 llvm_unreachable("couldn't find in-class initializer");
5433 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5442 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5452 DeclContext *Owner = Record->getDeclContext();
5455 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5456 Diag(Record->getLocation(), diag::ext_anonymous_union);
5457 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5458 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5459 else if (!Record->isUnion() && !getLangOpts().C11)
5460 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5467 if (Record->isUnion()) {
5473 DeclContext *OwnerScope = Owner->getRedeclContext();
5475 (OwnerScope->isTranslationUnit() ||
5476 (OwnerScope->isNamespace() &&
5477 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5478 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5479 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5505 << Record->isUnion() << "const"
5510 << Record->isUnion() << "volatile"
5515 << Record->isUnion() << "restrict"
5520 << Record->isUnion() << "_Atomic"
5525 << Record->isUnion() << "__unaligned"
5532 // The member-specification of an anonymous union shall only
5533 // define non-static data members. [Note: nested types and
5535 for (auto *Mem : Record->decls()) {
5537 if (Mem->isInvalidDecl())
5544 assert(FD->getAccess() != AS_none);
5545 if (FD->getAccess() != AS_public) {
5546 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5547 << Record->isUnion() << (FD->getAccess() == AS_protected);
5552 // An object of a class with a non-trivial constructor, a non-trivial
5553 // copy constructor, a non-trivial destructor, or a non-trivial copy
5558 } else if (Mem->isImplicit()) {
5560 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5562 // elaborated-type-specifier inside the anonymous struct or
5566 if (!MemRecord->isAnonymousStructOrUnion() &&
5567 MemRecord->getDeclName()) {
5570 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5571 << Record->isUnion();
5574 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5575 << Record->isUnion();
5582 Diag(MemRecord->getLocation(),
5584 << Record->isUnion();
5591 // We have something that isn't a non-static data
5604 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5605 << Record->isUnion();
5607 Diag(Mem->getLocation(), DK) << Record->isUnion();
5615 // brace-or-equal-initializer.
5616 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5617 Owner->isRecord())
5622 if (!Record->isUnion() && !Owner->isRecord()) {
5623 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5630 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5633 // each such member-declaration shall either declare at least one member
5634 // name of the class or declare at least one unnamed bit-field
5637 if (getLangOpts().CPlusPlus && Record->field_empty())
5650 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5654 Anon->setAccess(AS);
5658 FieldCollector->Add(cast<FieldDecl>(Anon));
5662 // mutable can only appear on non-static class members, so it's always
5664 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5670 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5673 Anon->setInvalidDecl();
5677 // Default-initialize the implicit variable. This initialization will be
5678 // trivial in almost all cases, except if a union member has an in-class
5683 Anon->setImplicit();
5686 Record->setAnonymousStructOrUnion(true);
5691 Owner->addDecl(Anon);
5704 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5708 getCurrentMangleNumberContext(NewVD->getDeclContext());
5711 NewVD, MCtx->getManglingNumber(
5713 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5719 Anon->setInvalidDecl();
5742 Anon->setImplicit();
5745 CurContext->addDecl(Anon);
5753 RecordDecl *RecordDef = Record->getDefinition();
5754 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5759 Anon->setInvalidDecl();
5760 ParentDecl->setInvalidDecl();
5784 // The simple-template-id shall name a class template specialization.
5785 // The template-name shall be the same identifier as the template-name
5786 // of the simple-template-id.
5787 // These together intend to imply that the template-name shall name a
5791 // Y(int) -> Y<int>;
5845 // In well-formed code, we can only have a constructor
5846 // template-id that refers to the current context, so go there
5849 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5855 // FIXME: Check two things: that the template-id names the same type as
5856 // CurClassType, and that the template-id does not occur when the name
5878 TemplateName TName = Name.TemplateId->Template.get();
5879 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5890 if (Ty->isPointerType() || Ty->isReferenceType())
5891 Ty = Ty->getPointeeType();
5892 else if (Ty->isArrayType())
5893 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5899 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5901 /// used to improve diagnostics in the case where an out-of-line function
5911 if (Declaration->param_size() != Definition->param_size())
5913 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5914 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5915 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5936 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5940 /// and the base type in any member-pointer chunks.
5944 // - typenames, typeofs, and decltypes
5945 // - types which will become injected class names
5961 if (T.isNull() || !T->isInstantiationDependentType()) break;
5974 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6004 // Rebuild the scope specifier in-place.
6016 return SM.isInSystemHeader(D->getLocation()) ||
6017 SM.isInSystemMacro(D->getLocation());
6023 if (D->getPreviousDecl() || D->isImplicit())
6025 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6028 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6040 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6048 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6049 Dcl && Dcl->getDeclContext()->isFileContext())
6050 Dcl->setTopLevelDeclInObjCContainer();
6064 while (Record && Record->isAnonymousStructOrUnion())
6065 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6066 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6080 "without nested-name-specifier");
6083 Cur = Cur->getParent();
6092 // Note, it was once ill-formed to give redundant qualification in all
6094 if (Cur->Equals(DC)) {
6095 if (Cur->isRecord()) {
6107 // declaration. For a template-id, we perform the checks in
6109 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6110 if (Cur->isRecord())
6137 if (Cur->isRecord()) {
6157 // nested-name-specifier.
6159 // First check the template-id (if any), and then check each component of the
6160 // nested-name-specifier in reverse order.
6162 // FIXME: nested-name-specifiers in friend declarations are declarative,
6164 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6166 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6170 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6176 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6177 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6179 // [...] If a nested-name-specifier N is declarative and has a
6180 // simple-template-id with a template argument list A that involves a
6183 if (TST->isDependentType() && TST->isTypeAlias())
6186 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6188 // [...] A declarative nested-name-specifier shall not have a
6189 // computed-type-specifier.
6191 // CWG2858 changed this from 'decltype-specifier' to
6192 // 'computed-type-specifier'.
6194 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6241 bool IsDependentContext = DC->isDependentContext();
6248 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6262 if (DC->isRecord())
6280 QualType R = TInfo->getType();
6296 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6303 else if (CurContext->isFunctionOrMethod() &&
6305 R->isFunctionType())) {
6308 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6309 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6324 // When the declarator-id is qualified, the declaration shall refer to a
6339 // void X::f(int) { } // ill-formed
6349 TPD && TPD->isTemplateParameter()) {
6352 // purposes we detect such cases and issue a default-to-error warning that
6353 // can be disabled with -Wno-strict-primary-template-shadow.
6356 if (Scope *DeclParent = S->getDeclParent();
6357 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6358 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6359 TemplateParamParent->isDeclScope(TPD);
6369 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6370 // Forget that the previous declaration is the injected-class-name.
6379 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6388 S = S->getDeclParent();
6400 } else if (R->isFunctionType()) {
6414 if (New->getDeclName() && AddToScope)
6437 if (T->isDependentType())
6444 QualType Pointee = PTy->getPointeeType();
6453 QualType Inner = PTy->getInnerType();
6466 QualType ElemTy = VLATy->getElementType();
6467 if (ElemTy->isVariablyModifiedType()) {
6475 if (!VLATy->getSizeExpr() ||
6476 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6489 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6490 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6499 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6547 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6552 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6553 FixedTInfo->getTypeLoc());
6567 T = FixedTInfo->getType();
6583 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6587 // Note that we have a locally-scoped external with this name.
6588 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6593 auto Result = Context.getExternCContextDecl()->lookup(Name);
6646 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6666 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6667 QualType T = TInfo->getType();
6668 if (T->isVariablyModifiedType()) {
6671 if (S->getFnParent() == nullptr) {
6679 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6680 NewTD->setTypeSourceInfo(FixedTInfo);
6683 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6684 else if (T->isVariableArrayType())
6685 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6687 Diag(NewTD->getLocation(), diag::err_array_too_large)
6690 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6691 NewTD->setInvalidDecl();
6720 if (IdentifierInfo *II = NewTD->getIdentifier())
6721 if (!NewTD->isInvalidDecl() &&
6722 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6723 switch (II->getNotableIdentifierID()) {
6738 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6748 /// Determines whether the given declaration is an out-of-scope
6754 /// declaration occurs in a local scope, previous declarations with
6756 /// 6.2.2p4-5, C++ [basic.link]p6).
6764 /// \returns true if PrevDecl is an out-of-scope previous declaration
6772 if (!PrevDecl->hasLinkage())
6782 DeclContext *OuterContext = DC->getRedeclContext();
6783 if (!OuterContext->isFunctionOrMethod())
6784 // This rule only applies to block-scope declarations.
6787 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6788 if (PrevOuterContext->isRecord())
6794 OuterContext = OuterContext->getEnclosingNamespaceContext();
6795 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6799 if (!OuterContext->Equals(PrevOuterContext))
6809 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6813 if (Decl->getType().hasAddressSpace())
6815 if (Decl->getType()->isDependentType())
6818 QualType Type = Var->getType();
6819 if (Type->isSamplerT() || Type->isVoidType())
6822 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6823 // __opencl_c_program_scope_global_variables feature, the address space
6827 Var->hasGlobalStorage())
6830 // type has no address space yet, deduce it now.
6832 auto OrigTy = DT->getOriginalType();
6833 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6834 // Add the address space to the original array type and then propagate
6838 // Re-generate the decayed type.
6843 // Apply any qualifiers (including address space) from the array type to
6847 if (Type->isArrayType())
6849 Decl->setType(Type);
6861 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6867 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6873 if (VD->hasInit()) {
6874 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6875 assert(VD->isThisDeclarationADefinition() &&
6876 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6877 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6878 VD->dropAttr<AliasAttr>();
6887 S.Diag(Attr->getLocation(),
6895 S.Diag(Attr->getLocation(),
6903 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6905 IsAnonymousNS = NS->isAnonymousNamespace();
6906 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6916 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6925 // Don't declare this variable in the second operand of the for-statement;
6929 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6933 // parameter of a non-static member function (other than a ctor or dtor)
6937 if (!MD || MD->isStatic()) {
6938 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6939 << !MD << A->getRange();
6941 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6942 << isa<CXXDestructorDecl>(MD) << A->getRange();
6953 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6958 OldDecl = OldTD->getTemplatedDecl();
6964 NewDecl = NewTD->getTemplatedDecl();
6971 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6972 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6973 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6974 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6978 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6979 (NewExportAttr && !NewExportAttr->isInherited());
6987 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6990 if (!OldDecl->isCXXClassMember()) {
6992 if (VD && !VD->getDescribedVarTemplate())
6995 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7001 // address equality) as they can use the thunk.
7002 if (OldDecl->isUsed())
7008 S.Diag(NewDecl->getLocation(), DiagID)
7011 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7013 NewDecl->setInvalidDecl();
7020 // templates), local extern declarations, qualified friend declarations or
7026 // Ignore static data because out-of-line definitions are diagnosed
7028 IsStaticDataMember = VD->isStaticDataMember();
7029 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7032 IsInline = FD->isInlined();
7033 IsQualifiedFriend = FD->getQualifier() &&
7034 FD->getFriendObjectKind() == Decl::FOK_Declared;
7039 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7043 NewDecl->getLocation(),
7045 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7046 NewDecl->dropAttr<DLLImportAttr>();
7048 S.Diag(NewDecl->getLocation(),
7051 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7052 NewDecl->dropAttr<DLLImportAttr>();
7053 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7054 S.Context, NewImportAttr->getRange()));
7060 S.Diag(NewDecl->getLocation(),
7063 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7064 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7065 OldDecl->dropAttr<DLLImportAttr>();
7066 NewDecl->dropAttr<DLLImportAttr>();
7071 OldDecl->dropAttr<DLLImportAttr>();
7072 NewDecl->dropAttr<DLLImportAttr>();
7073 S.Diag(NewDecl->getLocation(),
7083 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7086 MD->getParent()->getAttr<DLLExportAttr>()) {
7087 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7088 NewAttr->setInherited(true);
7089 NewDecl->addAttr(NewAttr);
7102 if (!FD->isInlined()) return false;
7105 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7108 // Okay, go ahead and call the relatively-more-expensive function.
7132 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7136 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7137 D->template hasAttr<CUDAHostAttr>()))
7140 return D->isExternC();
7144 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7145 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7147 return VD->hasExternalStorage();
7148 if (DC->isFileContext())
7150 if (DC->isRecord())
7152 if (DC->getDeclKind() == Decl::HLSLBuffer)
7161 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7162 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7165 if (DC->isRecord())
7189 if (!DC->isFunctionOrMethod())
7192 // If this is a local extern function or variable declared within a function
7195 if (DC->isDependentContext())
7204 // semantically-enclosing namespace, not a lexically-enclosing one.
7205 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7206 DC = DC->getParent();
7213 return FD->isExternC();
7215 return VD->isExternC();
7222 DeclContext *DC = NewVD->getDeclContext();
7223 QualType R = NewVD->getType();
7225 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7226 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7228 if (R->isImageType() || R->isPipeType()) {
7229 Se.Diag(NewVD->getLocation(),
7232 NewVD->setInvalidDecl();
7241 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7242 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7243 Se.Diag(NewVD->getLocation(),
7246 NewVD->setInvalidDecl();
7255 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7256 NR->isReferenceType()) {
7257 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7258 NR->isFunctionReferenceType()) {
7259 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7260 << NR->isReferenceType();
7261 NewVD->setInvalidDecl();
7264 NR = NR->getPointeeType();
7272 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7273 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7274 NewVD->setInvalidDecl();
7281 // address space qualifiers.
7282 if (R->isEventT()) {
7284 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7285 NewVD->setInvalidDecl();
7290 if (R->isSamplerT()) {
7292 // The sampler type cannot be used with the __local and __global address
7296 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7297 NewVD->setInvalidDecl();
7301 // A global sampler must be declared with either the constant address
7303 if (DC->isTranslationUnit() &&
7306 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7307 NewVD->setInvalidDecl();
7309 if (NewVD->isInvalidDecl())
7318 const TypedefNameDecl *TND = TT->getDecl();
7319 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7320 AttrTy *Clone = Attribute->clone(S.Context);
7321 Clone->setInherited(true);
7322 D->addAttr(Clone);
7330 QualType VarType = VD->getType().getCanonicalType();
7332 // Ignore local declarations (for now) and those with const qualification.
7333 // TODO: Local variables should not be allowed if their type declaration has
7334 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7335 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7338 if (VarType->isArrayType()) {
7343 const RecordDecl *RD = VarType->getAsRecordDecl();
7349 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7350 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7351 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7360 QualType R = TInfo->getType();
7383 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7384 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7388 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7389 DC->getRedeclContext());
7397 if (SC == SC_None && !DC->isRecord() &&
7407 // mutable can only appear on non-static class members, so it's always
7428 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7429 // C99 6.9p2: The storage-class specifiers auto and register shall not
7439 // fold to a constant-sized type. This is otherwise invalid.
7440 if (D.hasInitializer() && R->isVariableArrayType())
7444 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7460 if (R->getContainedDeducedType())
7464 NewVD->setInvalidDecl();
7466 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7467 NewVD->hasLocalStorage())
7468 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7484 if (!TemplateParams->size() &&
7488 Diag(TemplateParams->getTemplateLoc(),
7491 << SourceRange(TemplateParams->getTemplateLoc(),
7492 TemplateParams->getRAngleLoc());
7502 IsPartialSpecialization = TemplateParams->size() > 0;
7503 } else { // if (TemplateParams->size() > 0)
7528 // The declaration in an explicit-specialization shall not be an
7529 // export-declaration. An explicit specialization shall not use a
7530 // storage-class-specifier other than thread_local.
7532 // We use the storage-class-specifier from DeclSpec because we may have
7541 if (CurContext->isRecord()) {
7548 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7549 if (Ctxt->isFunctionOrMethod()) {
7554 if (ParentDecl && !ParentDecl->getDeclName()) {
7560 // C++ [class.static.data]p5: A local class shall not have static
7564 << Name << RD->getDeclName()
7565 << llvm::to_underlying(RD->getTagKind());
7572 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7574 } else if (RD->isUnion()) {
7576 // the program is ill-formed. C++11 drops this restriction.
7587 << II << TemplateParams->getSourceRange();
7591 } else if (DC->isRecord()) {
7592 // This is an out-of-line definition of a static data member.
7623 ? TemplateParamLists[0]->getTemplateLoc()
7645 NewVD->setDescribedVarTemplate(NewTemplate);
7650 if (R->getContainedDeducedType())
7654 NewVD->setInvalidDecl();
7656 NewTemplate->setInvalidDecl();
7668 NewVD->setTemplateParameterListsInfo(
7676 } else if (CurContext->isFunctionOrMethod()) {
7685 NewVD->setInlineSpecified();
7691 NewVD->setLexicalDeclContext(CurContext);
7693 NewTemplate->setLexicalDeclContext(CurContext);
7698 B->setLocalExternDecl();
7700 NewVD->setLocalExternDecl();
7707 // storage-class-specifier static is implied if it does not appear
7711 if (NewVD->hasLocalStorage() &&
7714 !DC->isFunctionOrMethod()))
7728 NewVD->setTSCSpec(TSCS);
7733 NewVD->setTSCSpec(TSCS);
7747 NewVD->setConstexpr(true);
7751 if (NewVD->isStaticDataMember() &&
7754 NewVD->setImplicitlyInline();
7758 if (!NewVD->hasGlobalStorage())
7762 NewVD->addAttr(
7774 // that a local variable with thread storage duration still has to
7777 if (SC == SC_Static && S->getFnParent() != nullptr &&
7778 !NewVD->getType().isConstQualified()) {
7789 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7794 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7797 else if (NewVD->hasLocalStorage())
7798 Diag(NewVD->getLocation(), diag::err_module_private_local)
7804 NewVD->setModulePrivate();
7806 NewTemplate->setModulePrivate();
7808 B->setModulePrivate();
7821 NewVD->setInvalidDecl();
7825 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7826 // address space if the table has local storage (semantic checks elsewhere
7828 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7829 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7830 !NewVD->hasLocalStorage()) {
7832 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7833 NewVD->setType(Type);
7844 if (R->isFunctionPointerType())
7845 if (const auto *TT = R->getAs<TypedefType>())
7863 if (SC == SC_None && S->getFnParent() != nullptr &&
7864 (NewVD->hasAttr<CUDASharedAttr>() ||
7865 NewVD->hasAttr<CUDAConstantAttr>())) {
7866 NewVD->setStorageClass(SC_Static);
7873 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7874 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7875 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7877 // In auto-retain/release, infer strong retension for variables of
7880 NewVD->setInvalidDecl();
7882 // Handle GNU asm-label extension (encoded as an attribute).
7886 StringRef Label = SE->getString();
7887 if (S->getFnParent() != nullptr) {
7891 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7894 // Local Named register
7897 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7911 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7915 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7917 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7920 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7922 NewVD->setInvalidDecl(true);
7926 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7928 SE->getStrTokenLoc(0)));
7931 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7934 NewVD->addAttr(I->second);
7937 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7948 // scope and are out-of-semantic-context declarations (if the new
7958 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7959 NewVD->setPreviousDeclInSameBlockScope(
7968 !NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))
7969 NewVD->setInvalidDecl();
7976 // The user tried to define a non-static data member
7977 // out-of-line (C++ [dcl.meaning]p1).
7978 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7981 NewVD->setInvalidDecl();
7989 NewVD->setInvalidDecl();
7996 // error like WebAssembly tables being declared as arrays with a non-zero
7999 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8004 NewVD->getPreviousDecl()
8005 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8013 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8015 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8016 DC->isDependentContext())
8019 NewVD->setInvalidDecl();
8024 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8025 PrevVarTemplate->setMemberSpecialization();
8037 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8041 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8045 getCurrentMangleNumberContext(NewVD->getDeclContext());
8048 NewVD, MCtx->getManglingNumber(
8050 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8055 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8056 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8057 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8060 // A program that declares a variable main at global scope is ill-formed.
8064 // In C, and external-linkage variable named main results in undefined
8066 else if (NewVD->hasExternalFormalLinkage())
8077 if (NewVD->isInvalidDecl())
8078 NewTemplate->setInvalidDecl();
8083 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8114 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8121 for (const Capture &Capture : LSI->Captures) {
8144 if (D->hasGlobalStorage() && !D->isStaticLocal())
8155 if (D->getDeclContext()->isRecord())
8177 DeclContext *NewDC = D->getDeclContext();
8182 if (MD->isStatic())
8191 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8197 if (shadowedVar->isExternC()) {
8200 for (auto *I : shadowedVar->redecls())
8201 if (I->isFileVarDecl()) {
8207 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8212 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8213 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8216 if (RD->getLambdaCaptureDefault() == LCD_None) {
8228 ->ShadowingDecls.push_back({D, VD});
8239 ->ShadowingDecls.push_back({D, ShadowedDecl});
8244 VD && VD->hasLocalStorage()) {
8245 // A variable can't shadow a local variable in an enclosing scope, if
8246 // they are separated by a non-capturing declaration context.
8248 ParentDC && !ParentDC->Equals(OldDC);
8262 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8266 if (NewDC && NewDC->isRecord()) {
8267 // In particular, don't warn about shadowing non-class members.
8268 if (!OldDC->isRecord())
8288 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8292 for (const auto &Shadow : LSI->ShadowingDecls) {
8295 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8298 Diag(Shadow.VD->getLocation(),
8301 << Shadow.VD->getDeclName()
8305 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8306 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8308 Diag(Shadow.VD->getLocation(),
8309 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8311 << Shadow.VD->getDeclName()
8313 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8319 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8322 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8336 E = E->IgnoreParenImpCasts();
8340 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8344 const NamedDecl *ShadowedDecl = I->second;
8345 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8347 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8348 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8360 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8377 // This is a global, non-extern "C" declaration, and there is a previous
8378 // non-global extern "C" declaration. Diagnose if this is a variable
8397 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8405 // the declaration is ill-formed, but that is a defect: it breaks the
8417 // is lexically inside an extern "C" linkage-spec.
8420 Prev = FD->getFirstDecl();
8422 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8424 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8426 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8445 // we find local extern decls in the surrounding file-scope DeclContext.
8446 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8447 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8458 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8474 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8477 if (CanonT->isVariablyModifiedType()) {
8483 // works on non-arrays as well).
8486 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8492 if (CanonT->isRecordType()) {
8493 const RecordDecl *RD = CanonT->getAsRecordDecl();
8494 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8495 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8505 if (NewVD->isInvalidDecl())
8508 QualType T = NewVD->getType();
8511 if (T->isUndeducedType())
8514 if (NewVD->hasAttrs())
8517 if (T->isObjCObjectType()) {
8518 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8519 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8521 NewVD->setType(T);
8524 // Emit an error if an address space was applied to decl with local storage.
8525 // This includes arrays of objects with address space qualifiers, but not
8526 // automatic variables that point to other address spaces.
8528 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8530 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8531 NewVD->setInvalidDecl();
8535 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8540 NewVD->isStaticLocal()) {
8541 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8542 NewVD->setInvalidDecl();
8550 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8551 if (NewVD->hasAttr<BlocksAttr>()) {
8552 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8556 if (T->isBlockPointerType()) {
8557 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8560 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8562 NewVD->setInvalidDecl();
8565 if (NewVD->hasExternalStorage()) {
8566 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8567 NewVD->setInvalidDecl();
8572 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8573 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8574 NewVD->hasExternalStorage()) {
8575 if (!T->isSamplerT() && !T->isDependentType() &&
8580 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8582 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8585 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8587 NewVD->setInvalidDecl();
8592 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8594 NewVD->setInvalidDecl();
8600 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8602 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8604 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8605 << 0 /*non-kernel only*/ << "constant";
8607 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8608 << 0 /*non-kernel only*/ << "local";
8609 NewVD->setInvalidDecl();
8612 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8614 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8615 if (!getCurScope()->isFunctionScope()) {
8617 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8620 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8621 << "local";
8622 NewVD->setInvalidDecl();
8630 // Do not allow other address spaces on automatic variable.
8631 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8632 NewVD->setInvalidDecl();
8638 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8639 && !NewVD->hasAttr<BlocksAttr>()) {
8641 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8644 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8650 if (T->isWebAssemblyTableType()) {
8651 if (getCurScope()->getParent()) { // Parent is null at top-level
8652 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8653 NewVD->setInvalidDecl();
8656 if (NewVD->getStorageClass() != SC_Static) {
8657 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8658 NewVD->setInvalidDecl();
8662 if (!ATy || ATy->getZExtSize() != 0) {
8663 Diag(NewVD->getLocation(),
8665 NewVD->setInvalidDecl();
8670 bool isVM = T->isVariablyModifiedType();
8671 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8672 NewVD->hasAttr<BlocksAttr>())
8675 if ((isVM && NewVD->hasLinkage()) ||
8676 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8680 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8682 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8683 FixedT = FixedTInfo->getType();
8685 // Type and type-as-written are canonically different. We need to fix up
8690 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8694 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8696 if (NewVD->isFileVarDecl())
8697 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8699 else if (NewVD->isStaticLocal())
8700 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8703 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8705 NewVD->setInvalidDecl();
8710 if (NewVD->isFileVarDecl())
8711 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8713 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8714 NewVD->setInvalidDecl();
8718 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8719 NewVD->setType(FixedT);
8720 NewVD->setTypeSourceInfo(FixedTInfo);
8723 if (T->isVoidType()) {
8726 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8727 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8729 NewVD->setInvalidDecl();
8734 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8735 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8736 NewVD->setInvalidDecl();
8740 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8742 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8743 NewVD->setInvalidDecl();
8747 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8748 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8749 NewVD->setInvalidDecl();
8753 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8754 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8755 NewVD->setInvalidDecl();
8759 if (NewVD->isConstexpr() && !T->isDependentType() &&
8760 RequireLiteralType(NewVD->getLocation(), T,
8762 NewVD->setInvalidDecl();
8766 // PPC MMA non-pointer types are not allowed as non-local variable types.
8768 !NewVD->isLocalVarDecl() &&
8769 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8770 NewVD->setInvalidDecl();
8775 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8782 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8783 NewVD->setInvalidDecl();
8787 Diag(NewVD->getLocation(),
8790 NewVD->setInvalidDecl();
8796 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8800 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8809 if (NewVD->isInvalidDecl())
8812 // If we did not find anything by this name, look for a non-visible
8832 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8833 DeclarationName Name = MD->getDeclName();
8842 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8844 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8845 if (!BaseMD || !BaseMD->isVirtual() ||
8852 MD->addOverriddenMethod(BaseMD);
8867 DC->lookupInBases(VisitBase, Paths);
8884 // Callback to only accept typo corrections that have a non-zero edit distance.
8891 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8903 if (FD && !FD->hasBody() &&
8906 CXXRecordDecl *Parent = MD->getParent();
8907 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8946 DeclarationName Name = NewFD->getDeclName();
8947 DeclContext *NewDC = NewFD->getDeclContext();
8954 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8956 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8961 NewFD->setInvalidDecl();
8967 "Cannot have an ambiguity in previous-declaration lookup");
8970 MD ? MD->getParent() : nullptr);
8998 if (FD && !FD->hasBody() &&
9013 // pieces need to verify the typo-corrected C++ declaration and hopefully
9017 Correction.getCorrectionDecl()->getDeclContext(),
9018 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9027 Decl *Canonical = Result->getCanonicalDecl();
9030 if ((*I)->getCanonicalDecl() == Canonical)
9052 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9053 << Name << NewDC << IsDefinition << NewFD->getLocation();
9057 NewFDisConst = NewMD->isConst();
9062 FunctionDecl *FD = NearMatch->first;
9064 bool FDisConst = MD && MD->isConst();
9067 // FIXME: These notes are poorly worded for the local friend case.
9068 if (unsigned Idx = NearMatch->second) {
9069 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9070 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9071 if (Loc.isInvalid()) Loc = FD->getLocation();
9074 << Idx << FDParam->getType()
9075 << NewFD->getParamDecl(Idx - 1)->getType();
9077 auto DB = SemaRef.Diag(FD->getLocation(),
9079 << NewFDisConst << FD->getSourceRange().getEnd();
9087 SemaRef.Diag(FD->getLocation(),
9112 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9115 // block scope shall have no explicit storage-class specifier
9161 // - there is a prototype in the declarator, or
9162 // - the type R of the function is some kind of typedef or other non-
9165 // check this case because attributes may cause a non-function
9173 ->isFunctionProtoType()) ||
9174 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9185 NewFD->setInvalidDecl();
9197 assert(DC->isRecord() &&
9209 if (DC->isRecord()) {
9219 if (Record->isBeingDefined())
9220 NewDD->setIneligibleOrNotSelected(true);
9244 if (!DC->isRecord()) {
9263 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9265 << TrailingRequiresClause->getSourceRange();
9271 } else if (DC->isRecord()) {
9277 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9289 IsVirtualOkay = !Ret->isStatic();
9294 if (!isFriend && SemaRef.CurContext->isRecord())
9299 // - we're in C++ (where every function has a prototype),
9339 if (PT->isDependentType())
9342 if (PT->isPointerType() || PT->isReferenceType()) {
9343 QualType PointeeType = PT->getPointeeType();
9349 if (PointeeType->isPointerType()) {
9373 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9376 // If template type is not ODR-used its definition is only available
9380 if (!CXXRec->hasDefinition())
9381 CXXRec = CXXRec->getTemplateInstantiationPattern();
9382 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9385 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9400 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9402 // of these built-in scalar types.
9406 if (PT->isImageType())
9409 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9413 // This extension adds support for half scalar and vector types as built-in
9416 PT->isHalfType())
9420 if (PT->isArrayType()) {
9421 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9430 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9435 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9438 if (PT->isRecordType())
9449 QualType PT = Param->getType();
9461 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9468 // to one of the following address spaces only : __global, __local or
9470 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9476 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9478 // one of these built-in scalar types.
9486 if (!PT->isHalfType()) {
9487 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9491 while ((Typedef = PT->getAs<TypedefType>())) {
9492 SourceLocation Loc = Typedef->getDecl()->getLocation();
9493 // SourceLocation may be invalid for a built-in type.
9496 PT = Typedef->desugar();
9522 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9524 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9525 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9527 VisitStack.push_back(RecTy->getDecl());
9536 ValidTypes.insert(Hist->getType().getTypePtr());
9547 QualType FieldTy = Field->getType();
9550 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9552 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9554 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9562 for (const auto *FD : RD->fields()) {
9563 QualType QT = FD->getType();
9584 S.Diag(Param->getLocation(),
9586 << PT->isUnionType()
9589 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9592 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9593 << OrigRecDecl->getDeclName();
9602 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9603 << OuterField->getType();
9606 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9607 << QT->isPointerType()
9619 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9620 DC = DC->getParent();
9628 while (S->isClassScope() ||
9630 S->isFunctionPrototypeScope()) ||
9631 ((S->getFlags() & Scope::DeclScope) == 0) ||
9632 (S->getEntity() && S->getEntity()->isTransparentContext()))
9633 S = S->getParent();
9655 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9656 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9669 QualType R = TInfo->getType();
9671 assert(R->isFunctionType());
9672 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9678 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9679 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9717 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9718 NewFD->setTopLevelDeclInObjCContainer();
9720 // Set the lexical context. If this is a function-scope declaration, or has a
9723 NewFD->setLexicalDeclContext(CurContext);
9726 NewFD->setLocalExternDecl();
9730 // with an in-class definition (when such a definition is not attached to
9731 // the global module). User-specified 'inline' overrides this (set when
9735 NewFD->isConstexpr() || NewFD->isConsteval() ||
9736 !NewFD->getOwningModule() ||
9737 NewFD->isFromGlobalModule() ||
9738 NewFD->getOwningModule()->isHeaderLikeModule();
9744 // Pre-C++20 [class.friend]p5
9750 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9757 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9758 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9759 NewFD->setIsPureVirtual(true);
9763 if (isVirtual && Parent->isUnion()) {
9765 NewFD->setInvalidDecl();
9767 if ((Parent->isClass() || Parent->isStruct()) &&
9768 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9769 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9770 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9771 if (auto *Def = Parent->getDefinition())
9772 Def->setInitMethod(true);
9780 NewFD->setInvalidDecl();
9797 NewFD->setInvalidDecl();
9799 if (TemplateParams->size() > 0) {
9804 Diag(NewFD->getLocation(), diag::err_destructor_template);
9805 NewFD->setInvalidDecl();
9809 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9810 NewFD->setInvalidDecl();
9816 if (DC->isDependentContext()) {
9823 NewFD->getLocation(),
9826 FunctionTemplate->setLexicalDeclContext(CurContext);
9827 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9831 NewFD->setTemplateParameterListsInfo(Context,
9840 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9845 SourceRange RemoveRange = TemplateParams->getSourceRange();
9848 // template-id, we're actually silently creating a problem:
9874 NewFD->setInvalidDecl();
9880 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9887 // If this is a function template specialization and the unqualified-id of
9888 // the declarator-id is a template-id, convert the template argument list
9893 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9894 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9895 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9896 TemplateId->NumArgs);
9906 NewFD->setInvalidDecl();
9911 NewFD->setInvalidDecl();
9913 FunctionTemplate->setInvalidDecl();
9919 // member-specification of a class declaration; see 10.3.
9921 if (isVirtual && !NewFD->isInvalidDecl()) {
9925 } else if (!CurContext->isRecord()) {
9930 } else if (NewFD->getDescribedFunctionTemplate()) {
9938 NewFD->setVirtualAsWritten(true);
9942 NewFD->getReturnType()->isUndeducedType())
9949 if (isInline && !NewFD->isInvalidDecl()) {
9950 if (CurContext->isFunctionOrMethod()) {
9962 if (hasExplicit && !NewFD->isInvalidDecl() &&
9964 if (!CurContext->isRecord()) {
9983 NewFD->setImplicitlyInline();
9993 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10001 (NewFD->getOverloadedOperator() == OO_New ||
10002 NewFD->getOverloadedOperator() == OO_Array_New ||
10003 NewFD->getOverloadedOperator() == OO_Delete ||
10004 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10008 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10021 NewFD->setModulePrivate();
10023 FunctionTemplate->setModulePrivate();
10029 FunctionTemplate->setObjectOfFriendDecl();
10030 FunctionTemplate->setAccess(AS_public);
10032 NewFD->setObjectOfFriendDecl();
10033 NewFD->setAccess(AS_public);
10044 NewFD->setDefaulted();
10048 NewFD->setDeletedAsWritten();
10060 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10065 // The declaration in an explicit-specialization shall not be an
10066 // export-declaration. An explicit specialization shall not use a
10067 // storage-class-specifier other than thread_local.
10069 // We diagnose friend declarations with storage-class-specifiers
10078 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10080 "Out-of-line member function should be a CXXMethodDecl");
10086 // Complain about the 'static' specifier if it's on an out-of-line
10090 // out-of-line member function template declaration and class member
10094 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10096 NewFD->getDescribedFunctionTemplate()))
10105 // A deallocation function with no exception-specification is treated
10107 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10110 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10111 NewFD->setType(Context.getFunctionType(
10112 FPT->getReturnType(), FPT->getParamTypes(),
10113 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10123 NewFD->isInNamedModule()) {
10134 // Handle GNU asm-label extension (encoded as an attribute).
10138 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10140 SE->getStrTokenLoc(0)));
10143 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10146 NewFD->addAttr(I->second);
10149 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10161 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10169 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10170 Param->setDeclContext(NewFD);
10173 if (Param->isInvalidDecl())
10174 NewFD->setInvalidDecl();
10184 getTagInjectionContext(NewFD->getLexicalDeclContext());
10192 TD = cast<EnumDecl>(ECD->getDeclContext());
10196 DeclContext *TagDC = TD->getLexicalDeclContext();
10197 if (!TagDC->containsDecl(TD))
10199 TagDC->removeDecl(TD);
10200 TD->setDeclContext(NewFD);
10201 NewFD->addDecl(TD);
10209 TD->setLexicalDeclContext(TagDC);
10212 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10223 for (const auto &AI : FT->param_types()) {
10226 Param->setScopeInfo(0, Params.size());
10230 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10231 "Should not need args for typedef of non-prototype fn");
10235 NewFD->setParams(Params);
10238 NewFD->addAttr(
10243 if (!NewFD->isInvalidDecl() &&
10244 NewFD->getReturnType()->isVariablyModifiedType()) {
10245 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10246 NewFD->setInvalidDecl();
10251 !NewFD->hasAttr<SectionAttr>())
10252 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10258 !NewFD->hasAttr<SectionAttr>()) {
10259 NewFD->addAttr(SectionAttr::CreateImplicit(
10260 Context, CodeSegStack.CurrentValue->getString(),
10262 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10266 NewFD->dropAttr<SectionAttr>();
10272 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10273 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10278 if (!NewFD->hasAttr<CodeSegAttr>()) {
10281 NewFD->addAttr(SAttr);
10287 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10288 if (NewTVA && !NewTVA->isDefaultVersion() &&
10296 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10299 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10301 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10303 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10304 NewFD->setInvalidDecl();
10310 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10313 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10316 if (!NewFD->isInvalidDecl())
10323 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10327 // Diagnose no-prototype function declarations with calling conventions that
10330 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10332 CallingConv CC = FT->getExtInfo().getCC();
10338 Diag(NewFD->getLocation(), DiagID)
10343 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10344 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10345 checkNonTrivialCUnion(NewFD->getReturnType(),
10346 NewFD->getReturnTypeSourceRange().getBegin(),
10357 NewFD->isReplaceableGlobalAllocationFunction() &&
10358 !NewFD->hasAttr<UsedAttr>())
10361 << NewFD->getDeclName();
10363 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10365 // The optional requires-clause in an init-declarator or
10366 // member-declarator shall be present only if the declarator declares a
10371 // - a template,
10372 // - an entity defined or created in a templated entity,
10373 // - a member of a templated entity,
10374 // - an enumerator for an enumeration that is a templated entity, or
10375 // - the closure type of a lambda-expression appearing in the
10378 // [Note 6: A local class, a local or block variable, or a friend
10390 // requires-clause unless it declares a function template.
10393 // definition, and since a non-template friend declaration with a
10394 // trailing requires-clause must be a definition, we diagnose
10396 // requires-clauses on the same path as explicit specializations
10399 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10401 } else if (isFriend && NewFD->isTemplated() &&
10404 // A non-template friend declaration with a requires-clause shall be
10406 Diag(NewFD->getBeginLoc(),
10408 NewFD->setInvalidDecl();
10409 } else if (!NewFD->isTemplated() ||
10411 Diag(TRC->getBeginLoc(),
10418 // they may have different constexpr-ness compared to their
10434 // type is dependent, or if its template-id is dependent.
10436 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10446 // For class-scope explicit specializations of function templates,
10450 CurContext->isRecord() && CurContext->isDependentContext();
10463 NewFD->setInvalidDecl();
10464 } else if (!NewFD->isInvalidDecl()) {
10467 NewFD->setInvalidDecl();
10471 NewFD->setInvalidDecl();
10475 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10478 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10481 if (!NewFD->isInvalidDecl())
10489 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10498 if (isFriend && NewFD->getPreviousDecl()) {
10500 if (!NewFD->isInvalidDecl())
10501 Access = NewFD->getPreviousDecl()->getAccess();
10503 NewFD->setAccess(Access);
10504 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10507 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10508 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10509 PrincipalDecl->setNonMemberOperator();
10515 FunctionTemplate->getPreviousDecl();
10516 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10517 PrevTemplate ? PrevTemplate->getTemplateParameters()
10524 DC && DC->isRecord() &&
10525 DC->isDependentContext())
10530 if (NewFD->isInvalidDecl()) {
10536 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10537 NewFD->setAccess(AS_public);
10541 // ...with the major exception of templated-scope or
10542 // dependent-scope friend declarations.
10555 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10556 (!Previous.empty() && CurContext->isDependentContext()))) {
10558 } else if (NewFD->isCPUDispatchMultiVersion() ||
10559 NewFD->isCPUSpecificMultiVersion()) {
10563 // The user tried to provide an out-of-line definition for a
10572 // void X::f() { } // ill-formed
10575 // matches (e.g., those that differ only in cv-qualifiers and
10585 // Unqualified local friend declarations are required to resolve
10587 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10595 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10598 // An out-of-line member function declaration must also be a
10605 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10612 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10615 if (NewFD->hasAttr<HLSLShaderAttr>())
10623 if (unsigned BuiltinID = II->getBuiltinID()) {
10626 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10627 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10631 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10639 NewFD->getType(), BuiltinType))
10640 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10643 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10645 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10656 if (NewFD->hasAttr<OverloadableAttr>() &&
10657 !NewFD->getType()->getAs<FunctionProtoType>()) {
10658 Diag(NewFD->getLocation(),
10661 NewFD->dropAttr<OverloadableAttr>();
10666 if (!DC->isRecord() && NewFD->isExternallyVisible())
10684 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10689 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10700 IdentifierInfo *II = NewFD->getIdentifier();
10701 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10702 !NewFD->isInvalidDecl() &&
10703 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10704 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10705 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10711 // in device-side CUDA code, unless someone passed
10712 // -fcuda-allow-variadic-functions.
10713 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10714 (NewFD->hasAttr<CUDADeviceAttr>() ||
10715 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10716 !(II && II->isStr("printf") && NewFD->isExternC() &&
10718 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10726 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10733 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10734 if (!NewFD->getReturnType()->isVoidType()) {
10735 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10743 for (auto *Param : NewFD->parameters())
10747 if (DC->isRecord()) {
10763 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10769 Diag(NewFD->getBeginLoc(),
10771 NewFD->setInvalidDecl();
10776 if (NewFD->isInvalidDecl())
10777 FunctionTemplate->setInvalidDecl();
10781 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10785 for (const ParmVarDecl *Param : NewFD->parameters()) {
10786 QualType PT = Param->getType();
10788 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10791 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10792 QualType ElemTy = PipeTy->getElementType();
10793 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10794 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10801 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10802 Diag(Param->getTypeSpecStartLoc(),
10811 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10812 if (NewFD->hasAttr<ConstructorAttr>()) {
10813 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10815 NewFD->dropAttr<AvailabilityAttr>();
10817 if (NewFD->hasAttr<DestructorAttr>()) {
10818 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10820 NewFD->dropAttr<AvailabilityAttr>();
10831 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10835 Diag(NBA->getLocation(),
10837 << NBA->getSpelling();
10840 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10841 << NBA->getSpelling();
10851 !NewFD->isInvalidDecl() &&
10860 /// the class and nested classes -- this includes compiler-generated special
10861 /// member functions -- are put in the specified segment."
10872 const CXXRecordDecl *Parent = Method->getParent();
10873 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10874 Attr *NewAttr = SAttr->clone(S.getASTContext());
10875 NewAttr->setImplicit(true);
10884 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10885 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10886 Attr *NewAttr = SAttr->clone(S.getASTContext());
10887 NewAttr->setImplicit(true);
10898 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10901 getASTContext(), CodeSegStack.CurrentValue->getString(),
10908 if (!NewD->getLexicalDeclContext()->isDependentContext())
10911 // For dependently-typed local extern declarations and friends, we can't
10918 if (NewT->isDependentType() &&
10919 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10922 // Similarly, if the previous declaration was a dependent local extern
10924 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10931 if (!D->getLexicalDeclContext()->isDependentContext())
10944 // this by checking for a file-scope function. We do not want this to apply
10947 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10953 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10954 PrevVD->getType());
10962 const auto *TA = FD->getAttr<TargetAttr>();
10963 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10972 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10974 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10980 if (Feat[0] == '-') {
10981 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10982 << Feature << ("no-" + BareFeat).str();
10988 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10997 TVA->getFeatures(Feats);
11000 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11009 // Provide a white-list of attributes that are allowed to be combined with
11034 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11037 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11041 for (const Attr *A : FD->attrs()) {
11042 switch (A->getKind()) {
11064 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11101 !OldFD->getType()->getAs<FunctionProtoType>()) {
11102 Diag(OldFD->getLocation(), NoProtoDiagID);
11108 !NewFD->getType()->getAs<FunctionProtoType>())
11109 return Diag(NewFD->getLocation(), NoProtoDiagID);
11112 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11117 if (NewCXXFD->isVirtual())
11130 if (NewFD->isDeleted())
11134 if (NewFD->isDefaulted())
11138 if (!ConstexprSupported && NewFD->isConstexpr())
11140 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11142 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11144 QualType NewReturnType = NewType->getReturnType();
11146 if (NewReturnType->isUndeducedType())
11152 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11154 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11155 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11157 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11158 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11163 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11164 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11174 QualType OldReturnType = OldType->getReturnType();
11179 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11182 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11185 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11188 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11191 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11192 NewFD->getLocation()))
11203 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11205 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11221 if (OldFD && CausesMV && OldFD->isUsed(false))
11222 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11226 PartialDiagnosticAt(NewFD->getLocation(),
11228 PartialDiagnosticAt(NewFD->getLocation(),
11231 PartialDiagnosticAt(NewFD->getLocation(),
11241 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11245 MultiVersionKind MVKind = FD->getMultiVersionKind();
11248 const auto *TA = FD->getAttr<TargetAttr>();
11249 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11252 if (TA && !TA->isDefaultVersion())
11256 if (TVA && TVA->isDefaultVersion())
11260 FD->setInvalidDecl();
11265 FD->setInvalidDecl();
11269 FD->setIsMultiVersion();
11274 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11275 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11283 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11286 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11287 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11292 To->addAttr(TargetVersionAttr::CreateImplicit(
11293 To->getASTContext(), "default", To->getSourceRange()));
11301 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11308 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11309 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11310 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11314 if (NewTA && !NewTA->isDefaultVersion() &&
11315 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11320 if (NewTVA && NewTVA->isDefaultVersion())
11327 NewFD->setInvalidDecl();
11332 NewFD->setInvalidDecl();
11337 if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
11340 OldFD->setIsMultiVersion();
11341 NewFD->setIsMultiVersion();
11346 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11347 NewFD->setInvalidDecl();
11354 OldTA->getFeaturesStr());
11358 NewTA->getFeaturesStr());
11362 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11363 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11364 NewFD->setInvalidDecl();
11369 for (const auto *FD : OldFD->redecls()) {
11370 const auto *CurTA = FD->getAttr<TargetAttr>();
11371 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11375 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11376 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11377 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11379 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11380 NewFD->setInvalidDecl();
11385 OldFD->setIsMultiVersion();
11386 NewFD->setIsMultiVersion();
11394 MultiVersionKind OldKind = Old->getMultiVersionKind();
11395 MultiVersionKind NewKind = New->getMultiVersionKind();
11401 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11432 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11433 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11434 NewFD->setInvalidDecl();
11442 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11443 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11444 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11445 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11450 NewTA->getFeaturesStr());
11455 NewTVA->getFeatures(NewFeats);
11460 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11465 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11468 FunctionDecl *CurFD = ND->getAsFunction();
11469 if (!CurFD || CurFD->isInvalidDecl())
11481 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11482 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11483 NewFD->setIsMultiVersion();
11491 CurTA->getFeaturesStr());
11494 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11495 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11496 NewFD->setInvalidDecl();
11502 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11503 if (CurTVA->getName() == NewTVA->getName()) {
11504 NewFD->setIsMultiVersion();
11510 CurTVA->getFeatures(CurFeats);
11514 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11515 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11516 NewFD->setInvalidDecl();
11519 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11524 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11526 CurClones->getFeatures(CurFeats, I);
11530 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11531 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11532 NewFD->setInvalidDecl();
11541 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11542 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11543 !std::equal(CurClones->featuresStrs_begin(),
11544 CurClones->featuresStrs_end(),
11545 NewClones->featuresStrs_begin())) {
11546 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11547 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11548 NewFD->setInvalidDecl();
11551 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11553 CurTVA->getFeatures(CurFeats);
11560 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11562 NewClones->getFeatures(NewFeats, I);
11566 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11567 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11568 NewFD->setInvalidDecl();
11576 NewFD->setIsMultiVersion();
11581 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11582 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11587 CurFD->hasAttr<CPUDispatchAttr>()) {
11588 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11590 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11591 NewCPUDisp->cpus_begin(),
11593 return Cur->getName() == New->getName();
11595 NewFD->setIsMultiVersion();
11602 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11603 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11604 NewFD->setInvalidDecl();
11608 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11610 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11611 NewCPUSpec->cpus_begin(),
11613 return Cur->getName() == New->getName();
11615 NewFD->setIsMultiVersion();
11622 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11623 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11625 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11627 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11628 NewFD->setInvalidDecl();
11639 // Else, this is simply a non-redecl case. Checking the 'value' is only
11645 NewFD->setInvalidDecl();
11650 !OldFD->isMultiVersion(), NewMVKind)) {
11651 NewFD->setInvalidDecl();
11656 if (!OldFD->isMultiVersion()) {
11657 OldFD->setIsMultiVersion();
11658 NewFD->setIsMultiVersion();
11664 NewFD->setIsMultiVersion();
11674 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11680 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11681 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11682 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11683 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11684 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11685 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11690 if (NewFD->isMain()) {
11692 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11694 NewTVA->isDefaultVersion())) {
11695 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11696 NewFD->setInvalidDecl();
11712 if (!OldDecl || !OldDecl->getAsFunction() ||
11713 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11714 NewFD->getDeclContext()->getRedeclContext())) {
11722 FunctionDecl *OldFD = OldDecl->getAsFunction();
11724 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11729 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11730 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11731 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11732 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11733 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11734 NewFD->setInvalidDecl();
11738 if (!OldFD->isMultiVersion()) {
11745 if (OldFD->isUsed(false)) {
11746 NewFD->setInvalidDecl();
11747 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11749 OldFD->setIsMultiVersion();
11768 bool IsPure = NewFD->hasAttr<PureAttr>();
11769 bool IsConst = NewFD->hasAttr<ConstAttr>();
11780 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11781 NewFD->dropAttrs<PureAttr>();
11786 if (NewFD->getReturnType()->isVoidType()) {
11787 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11789 NewFD->dropAttrs<PureAttr, ConstAttr>();
11797 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11853 if (OldDecl->hasAttr<OverloadableAttr>() ||
11854 NewFD->hasAttr<OverloadableAttr>()) {
11867 // PPC MMA non-pointer types are not allowed as function return types.
11869 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11870 NewFD->setInvalidDecl();
11878 // function body contains a return statement with a non-type-dependent
11882 // An id-expression is type-dependent if it is a template-id that is not a
11883 // concept-id and is dependent; or if its terminal name is:
11884 // - [...]
11885 // - associated by name lookup with one or more declarations of member
11888 // - [...]
11895 (NewFD->isDependentContext() &&
11896 NewFD->getReturnType()->isUndeducedType())) {
11898 NewFD->getType()->castAs<FunctionProtoType>();
11899 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
11900 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
11901 FPT->getExtProtoInfo()));
11905 // A constexpr specifier for a non-static member function that is not
11908 // This needs to be delayed until we know whether this is an out-of-line
11914 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11915 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11916 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11919 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11920 if (!OldMD || !OldMD->isStatic()) {
11922 MD->getType()->castAs<FunctionProtoType>();
11923 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11925 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11926 FPT->getParamTypes(), EPI));
11932 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11936 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11947 NewFD->setInvalidDecl();
11956 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11958 = NewFD->getDescribedFunctionTemplate();
11959 assert(NewTemplateDecl && "Template/non-template mismatch");
11964 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11966 NewFD->setPreviousDeclaration(OldFD);
11967 if (NewFD->isCXXClassMember()) {
11968 NewFD->setAccess(OldTemplateDecl->getAccess());
11969 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11975 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11976 NewTemplateDecl->setMemberSpecialization();
11977 assert(OldTemplateDecl->isMemberSpecialization());
11980 if (OldFD->isDeleted()) {
11982 assert(OldFD->getCanonicalDecl() == OldFD);
11984 OldFD->setDeletedAsWritten(false);
11992 NewFD->setPreviousDeclaration(OldFD);
11993 if (NewFD->isCXXClassMember())
11994 NewFD->setAccess(OldFD->getAccess());
11998 !NewFD->getAttr<OverloadableAttr>()) {
12002 return ND->hasAttr<OverloadableAttr>();
12004 "Non-redecls shouldn't happen without overloadable present");
12008 return FD && !FD->hasAttr<OverloadableAttr>();
12012 Diag(NewFD->getLocation(),
12014 Diag((*OtherUnmarkedIter)->getLocation(),
12018 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12028 // C++-specific checks.
12039 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12040 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12041 CXXRecordDecl *Record = Destructor->getParent();
12046 if (NewFD->getDeclName() != Name) {
12047 Diag(NewFD->getLocation(), diag::err_destructor_name);
12048 NewFD->setInvalidDecl();
12053 if (auto *TD = Guide->getDescribedFunctionTemplate())
12058 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12059 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12065 if (!Method->isFunctionTemplateSpecialization() &&
12066 !Method->getDescribedFunctionTemplate() &&
12067 Method->isCanonicalDecl()) {
12068 AddOverriddenMethods(Method->getParent(), Method);
12070 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12072 // A virtual method shall not have a requires-clause.
12073 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12076 if (Method->isStatic())
12084 if (NewFD->isOverloadedOperator() &&
12086 NewFD->setInvalidDecl();
12091 if (NewFD->getLiteralIdentifier() &&
12093 NewFD->setInvalidDecl();
12100 if (!CurContext->isRecord())
12107 if (Previous.empty() && NewFD->isExternC()) {
12108 QualType R = NewFD->getReturnType();
12109 if (R->isIncompleteType() && !R->isVoidType())
12110 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12112 else if (!R.isPODType(Context) && !R->isVoidType() &&
12113 !R->isObjCObjectPointerType())
12114 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12118 // [...] whether the function has a non-throwing exception-specification
12122 // declared type includes an exception-specification in a parameter or
12126 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12127 auto HasNoexcept = [&](QualType T) -> bool {
12131 if (auto *RT = T->getAs<ReferenceType>())
12132 T = RT->getPointeeType();
12133 else if (T->isAnyPointerType())
12134 T = T->getPointeeType();
12135 else if (auto *MPT = T->getAs<MemberPointerType>())
12136 T = MPT->getPointeeType();
12137 if (auto *FPT = T->getAs<FunctionProtoType>())
12138 if (FPT->isNothrow())
12143 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12144 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12145 for (QualType T : FPT->param_types())
12148 Diag(NewFD->getLocation(),
12159 // function returns or uses arguments with VL-based types.
12161 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12162 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12163 bool UsesZA = Attr && Attr->isNewZA();
12164 bool UsesZT0 = Attr && Attr->isNewZT0();
12166 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12167 if (NewFD->getReturnType()->isSizelessVectorType())
12168 Diag(NewFD->getLocation(),
12171 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12172 return P->getOriginalType()->isSizelessVectorType();
12174 Diag(NewFD->getLocation(),
12178 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12179 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12193 Diag(NewFD->getLocation(),
12196 Diag(NewFD->getLocation(),
12204 Diag(NewFD->getLocation(),
12216 // constexpr is ill-formed.
12221 if (FD->getStorageClass() == SC_Static)
12225 if (FD->isInlineSpecified())
12235 if (FD->isConstexpr()) {
12237 << FD->isConsteval()
12239 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12243 Diag(FD->getLocation(), diag::err_opencl_no_main)
12244 << FD->hasAttr<OpenCLKernelAttr>();
12245 FD->setInvalidDecl();
12254 QualType T = FD->getType();
12255 assert(T->isFunctionType() && "function decl is not of function type");
12256 const FunctionType* FT = T->castAs<FunctionType>();
12259 if (FT->getCallConv() != CC_C) {
12260 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12261 FD->setType(QualType(FT, 0));
12262 T = Context.getCanonicalType(FD->getType());
12266 // In C with GNU extensions we allow main() to have non-integer return
12268 // implicit-return-zero rule.
12271 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12272 FD->setHasImplicitReturnZero(true);
12274 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12275 SourceRange RTRange = FD->getReturnTypeSourceRange();
12286 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12287 FD->setHasImplicitReturnZero(true);
12289 // Otherwise, this is just a flat-out error.
12290 SourceRange RTRange = FD->getReturnTypeSourceRange();
12291 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12294 FD->setInvalidDecl(true);
12302 unsigned nparams = FTP->getNumParams();
12303 assert(FD->getNumParams() == nparams);
12307 if (FTP->isVariadic()) {
12308 Diag(FD->getLocation(), diag::ext_variadic_main);
12320 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12321 FD->setInvalidDecl(true);
12333 QualType AT = FTP->getParamType(i);
12347 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12348 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12349 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12357 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12359 FD->setInvalidDecl(true);
12363 if (nparams == 1 && !FD->isInvalidDecl()) {
12364 Diag(FD->getLocation(), diag::warn_main_one_arg);
12367 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12368 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12369 FD->setInvalidDecl();
12376 if (FD->getName() == "main" || FD->getName() == "wmain")
12393 QualType T = FD->getType();
12394 assert(T->isFunctionType() && "function decl is not of function type");
12395 const FunctionType *FT = T->castAs<FunctionType>();
12399 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12400 FT->getReturnType()->isAnyPointerType() ||
12401 FT->getReturnType()->isNullPtrType())
12403 if (FD->getName() != "DllMain")
12404 FD->setHasImplicitReturnZero(true);
12409 if (FT->getCallConv() != CC_X86StdCall) {
12411 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12412 FD->setType(QualType(FT, 0));
12414 } else if (FT->getCallConv() != CC_C) {
12416 FT->getExtInfo().withCallingConv(CC_C));
12417 FD->setType(QualType(FT, 0));
12421 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12422 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12423 FD->setInvalidDecl();
12429 // any assignment, increment, decrement, function-calls, or
12437 if (Init->isValueDependent()) {
12438 assert(Init->containsErrors() &&
12439 "Dependent code should only occur in error-recovery path.");
12443 if (Init->isConstantInitializer(Context, false, &Culprit))
12445 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12473 isPODType = VD->getType().isPODType(S.Context);
12474 isRecordType = VD->getType()->isRecordType();
12475 isReferenceType = VD->getType()->isReferenceType();
12492 for (auto *Child : InitList->children()) {
12508 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12512 if (FD->getType()->isReferenceType())
12514 Base = ME->getBase()->IgnoreParenImpCasts();
12519 if (!DRE || DRE->getDecl() != OrigDecl)
12529 UsedFieldIndex.push_back(I->getFieldIndex());
12554 E = E->IgnoreParens();
12561 Visit(CO->getCond());
12562 HandleValue(CO->getTrueExpr());
12563 HandleValue(CO->getFalseExpr());
12569 Visit(BCO->getCond());
12570 HandleValue(BCO->getFalseExpr());
12575 if (Expr *SE = OVE->getSourceExpr())
12581 if (BO->getOpcode() == BO_Comma) {
12582 Visit(BO->getLHS());
12583 HandleValue(BO->getRHS());
12595 Expr *Base = E->IgnoreParenImpCasts();
12598 if (!isa<FieldDecl>(ME->getMemberDecl()))
12600 Base = ME->getBase()->IgnoreParenImpCasts();
12611 // uses of references are bad, not just r-value uses.
12618 if (E->getCastKind() == CK_LValueToRValue) {
12619 HandleValue(E->getSubExpr());
12633 if (E->getType()->canDecayToPointerType()) return;
12635 // Warn when a non-static method call is followed by non-static member
12637 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12638 bool Warn = (MD && !MD->isStatic());
12639 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12641 if (!isa<FieldDecl>(ME->getMemberDecl()))
12643 Base = ME->getBase()->IgnoreParenImpCasts();
12658 Expr *Callee = E->getCallee();
12664 for (auto Arg: E->arguments())
12665 HandleValue(Arg->IgnoreParenImpCasts());
12669 // For POD record types, addresses of its own members are well-defined.
12670 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12671 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12673 HandleValue(E->getSubExpr());
12677 if (E->isIncrementDecrementOp()) {
12678 HandleValue(E->getSubExpr());
12688 if (E->getConstructor()->isCopyConstructor()) {
12689 Expr *ArgExpr = E->getArg(0);
12691 if (ILE->getNumInits() == 1)
12692 ArgExpr = ILE->getInit(0);
12694 if (ICE->getCastKind() == CK_NoOp)
12695 ArgExpr = ICE->getSubExpr();
12704 if (E->isCallToStdMove()) {
12705 HandleValue(E->getArg(0));
12713 if (E->isCompoundAssignmentOp()) {
12714 HandleValue(E->getLHS());
12715 Visit(E->getRHS());
12726 Visit(E->getCond());
12727 Visit(E->getFalseExpr());
12731 Decl* ReferenceDecl = DRE->getDecl();
12736 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12738 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12739 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12740 DRE->getDecl()->getType()->isRecordType()) {
12743 // Local variables will be handled by the CFG analysis.
12747 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12749 << DRE->getDecl() << OrigDecl->getLocation()
12750 << DRE->getSourceRange());
12754 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12762 E = E->IgnoreParens();
12766 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12768 if (ICE->getCastKind() == CK_LValueToRValue)
12769 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12770 if (DRE->getDecl() == OrigDecl)
12797 assert((!VDecl || !VDecl->isInitCapture()) &&
12802 DeducedType *Deduced = Type->getContainedDeducedType();
12803 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12806 if (getLangOpts().C23 && Type->isArrayType() &&
12809 << (int)Deduced->getContainedAutoType()->getKeyword()
12821 VDecl->hasExternalStorage() ||
12822 VDecl->isStaticDataMember()) {
12823 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12824 << VDecl->getDeclName() << Type;
12835 DeduceInits = PL->exprs();
12838 assert(VDecl && "non-auto type for init capture deduction?");
12841 VDecl->getLocation(), DirectInit, Init);
12850 DeduceInits = IL->inits();
12857 Diag(Init->getBeginLoc(), IsInitCapture
12865 Diag(DeduceInits[1]->getBeginLoc(),
12874 Diag(Init->getBeginLoc(), IsInitCapture
12884 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12894 // If the assignment-expression [...] has array type A and no ref-qualifier
12898 DeduceInit->getType()->isConstantArrayType())
12899 return Context.getQualifiedType(DeduceInit->getType(),
12903 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12905 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12914 << (DeduceInit->getType().isNull() ? TSI->getType()
12915 : DeduceInit->getType())
12916 << DeduceInit->getSourceRange();
12919 << VN << TSI->getType()
12920 << (DeduceInit->getType().isNull() ? TSI->getType()
12921 : DeduceInit->getType())
12922 << DeduceInit->getSourceRange();
12925 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12931 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12932 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12941 assert(!Init || !Init->containsErrors());
12943 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12944 VDecl->getSourceRange(), DirectInit, Init);
12946 VDecl->setInvalidDecl();
12950 VDecl->setType(DeducedType);
12951 assert(VDecl->isLinkageValid());
12955 VDecl->setInvalidDecl();
12962 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12970 return VDecl->isInvalidDecl();
12976 Init = EWC->getSubExpr();
12979 Init = CE->getSubExpr();
12981 QualType InitType = Init->getType();
12984 "shouldn't be called if type doesn't have a non-trivial C struct");
12986 for (auto *I : ILE->inits()) {
12987 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12988 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12990 SourceLocation SL = I->getExprLoc();
13004 // copy-elision.
13015 // defined in a system header and has non-trivial ObjC ownership
13017 // whether the containing union is non-trivial.
13018 return FD->hasAttr<UnavailableAttr>();
13036 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13044 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13045 << 1 << 0 << QT << FD->getName();
13050 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13051 << 1 << 0 << QT << FD->getName();
13055 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13056 if (RD->isUnion()) {
13059 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13060 IsUnion = OrigRD->isUnion();
13070 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13073 for (const FieldDecl *FD : RD->fields())
13075 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13080 // The non-trivial C union type or the struct/union type that contains a
13081 // non-trivial C union.
13101 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13109 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13110 << 1 << 1 << QT << FD->getName();
13115 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13116 << 1 << 1 << QT << FD->getName();
13120 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13121 if (RD->isUnion()) {
13124 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13125 IsUnion = OrigRD->isUnion();
13135 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13138 for (const FieldDecl *FD : RD->fields())
13140 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13147 // The non-trivial C union type or the struct/union type that contains a
13148 // non-trivial C union.
13167 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13175 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13176 << 1 << 2 << QT << FD->getName();
13181 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13182 << 1 << 2 << QT << FD->getName();
13186 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13187 if (RD->isUnion()) {
13190 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13191 IsUnion = OrigRD->isUnion();
13201 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13204 for (const FieldDecl *FD : RD->fields())
13206 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13215 // The non-trivial C union type or the struct/union type that contains a
13216 // non-trivial C union.
13231 "shouldn't be called if type doesn't have a non-trivial C union");
13255 if (!Method->isInvalidDecl()) {
13256 // Pure-specifiers are handled in ActOnPureSpecifier.
13257 Diag(Method->getLocation(), diag::err_member_function_initialization)
13258 << Method->getDeclName() << Init->getSourceRange();
13259 Method->setInvalidDecl();
13267 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13268 RealDecl->setInvalidDecl();
13272 if (VDecl->isInvalidDecl()) {
13278 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13280 VDecl->setInit(E);
13285 if (Init && !Init->getType().isNull() &&
13286 Init->getType()->isWebAssemblyTableType()) {
13287 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13288 VDecl->setInvalidDecl();
13293 if (VDecl->getType()->isUndeducedType()) {
13301 RealDecl->setInvalidDecl();
13304 if (Res.get()->containsErrors()) {
13305 // Invalidate the decl as we don't know the type for recovery-expr yet.
13306 RealDecl->setInvalidDecl();
13307 VDecl->setInit(Res.get());
13317 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13318 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13319 VDecl->setInvalidDecl();
13327 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13328 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13329 VDecl->setInvalidDecl();
13333 if (!VDecl->getType()->isDependentType()) {
13337 QualType BaseDeclType = VDecl->getType();
13339 BaseDeclType = Array->getElementType();
13340 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13342 RealDecl->setInvalidDecl();
13347 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13350 VDecl->setInvalidDecl();
13356 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13357 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13358 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13359 !VDecl->getInstantiatedFromStaticDataMember()) {
13360 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13361 VDecl->setInvalidDecl();
13367 if (VarDecl *Def = VDecl->getDefinition())
13369 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13370 !VDecl->isThisDeclarationADemotedDefinition() &&
13378 // specify a constant-initializer which shall be an integral
13385 // data members we also need to check whether there was an in-class
13387 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13388 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13389 << VDecl->getDeclName();
13390 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13396 if (VDecl->hasLocalStorage())
13400 VDecl->setInvalidDecl();
13405 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13407 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13408 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13409 VDecl->setInvalidDecl();
13414 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13415 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13416 VDecl->setInvalidDecl();
13422 QualType DclT = VDecl->getType(), SavT = DclT;
13425 // and we are assigning it to a variable of Objective-C pointer type.
13426 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13427 Init->getType() == Context.UnknownAnyTy) {
13430 VDecl->setInvalidDecl();
13439 if (!VDecl->isInvalidDecl()) {
13442 VDecl->getLocation(), DirectInit, Init);
13446 Args = MultiExprArg(CXXDirectInit->getExprs(),
13447 CXXDirectInit->getNumExprs());
13458 VDecl->setInvalidDecl();
13463 if (VDecl->isInvalidDecl())
13474 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13476 VDecl->setInit(RecoveryExpr.get());
13481 // 2) if the var decl is a decomposition decl with a non-deduced type,
13485 VDecl->setInvalidDecl();
13491 InitSeq.step_begin()->Kind ==
13493 QualType VDeclType = VDecl->getType();
13494 if (Init && !Init->getType().isNull() &&
13495 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13497 Context.getAsIncompleteArrayType(Init->getType())) {
13500 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13502 VDecl->setInvalidDecl();
13507 // Check for self-references within variable initializers.
13512 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13513 VDecl->getType()->isReferenceType())
13520 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13521 VDecl->setType(DclT);
13523 if (!VDecl->isInvalidDecl()) {
13524 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13526 if (VDecl->hasAttr<BlocksAttr>())
13535 // -Wrepeated-use-of-weak is made flow-sensitive.
13537 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13538 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13540 Init->getBeginLoc()))
13541 FSI->markSafeWeakUse(Init);
13544 // The initialization is usually a full-expression.
13548 // full-expression. For instance, in:
13556 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13557 /*DiscardedValue*/ false, VDecl->isConstexpr());
13559 VDecl->setInvalidDecl();
13565 VDecl->setInit(Init);
13567 if (VDecl->isLocalVarDecl()) {
13569 if (VDecl->isInvalidDecl()) {
13572 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13574 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13583 } else if (VDecl->getStorageClass() == SC_Static) {
13590 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13596 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13597 if (VDecl->hasLocalStorage())
13598 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13599 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13600 VDecl->getLexicalDeclContext()->isRecord()) {
13601 // This is an in-class initialization for a static data member, e.g.,
13608 // A member-declarator can contain a constant-initializer only
13613 // If a non-volatile non-inline const static data member is of integral
13615 // specify a brace-or-equal-initializer in which every initializer-clause
13616 // that is an assignment-expression is a constant expression. A static
13619 // brace-or-equal-initializer in which every initializer-clause that is
13620 // an assignment-expression is a constant expression.
13623 if (DclT->isDependentType()) {
13628 } else if (VDecl->isConstexpr()) {
13632 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13633 << Init->getSourceRange();
13634 VDecl->setInvalidDecl();
13637 } else if (DclT->isIntegralOrEnumerationType()) {
13641 // In C++11, a non-constexpr const static data member with an
13642 // in-class initializer cannot be volatile.
13643 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13644 else if (Init->isValueDependent())
13646 else if (Init->isIntegerConstantExpr(Context, &Loc))
13648 else if (Init->getType()->isScopedEnumeralType() &&
13649 Init->isCXX11ConstantExpr(Context))
13650 ; // Ok, it is a scoped-enum constant expression.
13651 else if (Init->isEvaluatable(Context)) {
13653 // but report this as a use of an extension for -pedantic.
13655 << Init->getSourceRange();
13660 << Init->getSourceRange();
13661 VDecl->setInvalidDecl();
13664 // We allow foldable floating-point constants as an extension.
13665 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13669 Diag(VDecl->getLocation(),
13671 << DclT << Init->getSourceRange();
13672 Diag(VDecl->getBeginLoc(),
13674 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13676 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13677 << DclT << Init->getSourceRange();
13679 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13680 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13681 << Init->getSourceRange();
13682 VDecl->setInvalidDecl();
13687 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13688 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13689 << DclT << Init->getSourceRange()
13690 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13691 VDecl->setConstexpr(true);
13694 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13695 << DclT << Init->getSourceRange();
13696 VDecl->setInvalidDecl();
13698 } else if (VDecl->isFileVarDecl()) {
13706 if (VDecl->getStorageClass() == SC_Extern &&
13707 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13708 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13709 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13710 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13711 Diag(VDecl->getLocation(), diag::warn_extern_init);
13717 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13718 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13719 VDecl->setStorageClass(SC_Extern);
13723 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13724 !VDecl->isConstexpr())
13728 QualType InitType = Init->getType();
13732 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13734 // We will represent direct-initialization similarly to copy-initialization:
13735 // int x(1); -as-> int x = 1;
13736 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13749 assert(DirectInit && "Call-style initializer must be direct init.");
13750 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13753 // This must be list-initialization. No other way is direct-initialization.
13754 VDecl->setInitStyle(VarDecl::ListInit);
13759 VDecl->isFileVarDecl())
13765 // Our main concern here is re-establishing invariants like "a
13767 if (!D || D->isInvalidDecl()) return;
13774 for (auto *BD : DD->bindings())
13775 BD->setInvalidDecl();
13778 if (VD->getType()->isUndeducedType()) {
13779 D->setInvalidDecl();
13783 QualType Ty = VD->getType();
13784 if (Ty->isDependentType()) return;
13787 if (RequireCompleteType(VD->getLocation(),
13790 VD->setInvalidDecl();
13794 // Require a non-abstract type.
13795 if (RequireNonAbstractType(VD->getLocation(), Ty,
13798 VD->setInvalidDecl();
13812 QualType Type = Var->getType();
13816 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13817 Var->setInvalidDecl();
13821 if (Type->isUndeducedType() &&
13827 // a brace-or-equal-initializer.
13831 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13832 !Var->isThisDeclarationADemotedDefinition()) {
13833 if (Var->isStaticDataMember()) {
13834 // C++1z removes the relevant rule; the in-class declaration is always
13838 Diag(Var->getLocation(),
13841 Var->setInvalidDecl();
13845 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13846 Var->setInvalidDecl();
13851 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13853 if (!Var->isInvalidDecl() &&
13854 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13855 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13857 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13858 for (auto *Ctor : RD->ctors()) {
13859 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13860 Ctor->getMethodQualifiers().getAddressSpace() ==
13867 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13868 Var->setInvalidDecl();
13873 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13874 if (Var->getStorageClass() == SC_Extern) {
13875 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13877 Var->setInvalidDecl();
13880 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13882 Var->setInvalidDecl();
13885 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13886 if (!RD->hasTrivialDefaultConstructor()) {
13887 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13888 Var->setInvalidDecl();
13896 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13897 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13898 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13899 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13905 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13908 // We have an out-of-line definition of a static data member
13909 // that has an in-class initializer, so we type-check this like
13920 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13921 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13922 RequireCompleteType(Var->getLocation(), Type,
13924 Var->setInvalidDecl();
13927 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13928 RequireNonAbstractType(Var->getLocation(), Type,
13931 Var->setInvalidDecl();
13932 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13933 Var->getStorageClass() == SC_PrivateExtern) {
13934 Diag(Var->getLocation(), diag::warn_private_extern);
13935 Diag(Var->getLocation(), diag::note_private_extern);
13939 !Var->isInvalidDecl())
13947 // storage-class specifier or with the storage-class specifier "static",
13950 if (!Var->isInvalidDecl()) {
13954 Var->getLocation(), ArrayT->getElementType(),
13956 Var->setInvalidDecl();
13957 } else if (Var->getStorageClass() == SC_Static) {
13967 if (Var->isFirstDecl())
13968 RequireCompleteType(Var->getLocation(), Type,
13974 if (!Var->isInvalidDecl())
13981 if (Type->isIncompleteArrayType()) {
13982 if (Var->isConstexpr())
13983 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13986 Diag(Var->getLocation(),
13988 Var->setInvalidDecl();
13994 if (Type->isReferenceType()) {
13995 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13996 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14000 // Do not attempt to type-check the default initializer for a
14002 if (Type->isDependentType())
14005 if (Var->isInvalidDecl())
14008 if (!Var->hasAttr<AliasAttr>()) {
14009 if (RequireCompleteType(Var->getLocation(),
14012 Var->setInvalidDecl();
14020 if (RequireNonAbstractType(Var->getLocation(), Type,
14023 Var->setInvalidDecl();
14029 // storage duration", not a "local variable".
14033 // ill-formed unless the variable has scalar type, class type with a
14034 // trivial default constructor and a trivial destructor, a cv-qualified
14037 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14039 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14040 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14044 if (!CXXRecord->isPOD())
14048 // In OpenCL, we can't initialize objects in the __local address space,
14051 Var->getType().getAddressSpace() == LangAS::opencl_local)
14055 // object is of (possibly cv-qualified) non-POD class type (or
14056 // array thereof), the object shall be default-initialized; if
14057 // the object is of const-qualified type, the underlying class
14058 // type shall have a user-declared default
14060 // a non- static object, the object and its subobjects, if
14062 // or any of its subobjects are of const-qualified type, the
14063 // program is ill-formed.
14066 // default-initialized; [...].
14069 = InitializationKind::CreateDefault(Var->getLocation());
14075 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14077 Var->setInitStyle(VarDecl::CallInit);
14079 // If default-init fails, attach a recovery-expr initializer to track
14082 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14084 Var->setInit(RecoveryExpr.get());
14098 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14099 D->setInvalidDecl();
14103 VD->setCXXForRangeDecl(true);
14105 // for-range-declaration cannot be given a storage class specifier.
14106 int Error = -1;
14107 switch (VD->getStorageClass()) {
14127 // for-range-declaration cannot be given a storage class specifier con't.
14128 switch (VD->getTSCSpec()) {
14138 if (Error != -1) {
14139 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14141 D->setInvalidDecl();
14149 // A range-based for statement of the form
14150 // for ( for-range-identifier : for-range-initializer ) statement
14152 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14167 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14175 if (var->isInvalidDecl()) return;
14180 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14182 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14183 !var->hasInit()) {
14184 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14186 var->setInvalidDecl();
14191 // In Objective-C, don't allow jumps past the implicit initialization of a
14192 // local retaining variable.
14194 var->hasLocalStorage()) {
14195 switch (var->getType().getObjCLifetime()) {
14208 if (var->hasLocalStorage() &&
14209 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14212 // Warn about externally-visible variables being defined without a
14217 if (var->isThisDeclarationADefinition() &&
14218 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14219 var->isExternallyVisible() && var->hasLinkage() &&
14220 !var->isInline() && !var->getDescribedVarTemplate() &&
14221 var->getStorageClass() != SC_Register &&
14223 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14225 var->getLocation())) {
14227 VarDecl *prev = var->getPreviousDecl();
14228 while (prev && prev->isThisDeclarationADefinition())
14229 prev = prev->getPreviousDecl();
14232 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14233 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14243 CacheHasConstInit = var->getInit()->isConstantInitializer(
14244 Context, var->getType()->isReferenceType(), &CacheCulprit);
14248 if (var->getTLSKind() == VarDecl::TLS_Static) {
14249 if (var->getType().isDestructedType()) {
14252 // have a non-trivial destructor.
14253 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14255 Diag(var->getLocation(), diag::note_use_thread_local);
14256 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14262 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14263 << CacheCulprit->getSourceRange();
14265 Diag(var->getLocation(), diag::note_use_thread_local);
14271 if (!var->getType()->isStructureType() && var->hasInit() &&
14272 isa<InitListExpr>(var->getInit())) {
14273 const auto *ILE = cast<InitListExpr>(var->getInit());
14274 unsigned NumInits = ILE->getNumInits();
14277 const auto *Init = ILE->getInit(I);
14280 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14284 unsigned NumConcat = SL->getNumConcatenated();
14288 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14291 const auto *Init = ILE->getInit(J);
14294 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14295 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14303 for (unsigned i = 0; i < NumConcat - 1; ++i)
14305 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14307 Diag(SL->getStrTokenLoc(1),
14310 Diag(SL->getBeginLoc(),
14320 QualType type = var->getType();
14322 if (var->hasAttr<BlocksAttr>())
14323 getCurFunction()->addByrefBlockVar(var);
14325 Expr *Init = var->getInit();
14326 bool GlobalStorage = var->hasGlobalStorage();
14327 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14331 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14332 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14336 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14337 !type->isDependentType() && Init && !Init->isValueDependent() &&
14338 (GlobalStorage || var->isConstexpr() ||
14339 var->mightBeUsableInConstantExpressions(Context))) {
14348 // in [expr.const]p2-6.
14350 // -Wglobal-constructors.
14356 (void)var->checkForConstantInitialization(Notes);
14359 Notes.emplace_back(CacheCulprit->getExprLoc(),
14361 Notes.back().second << CacheCulprit->getSourceRange();
14365 HasConstInit = var->checkForConstantInitialization(Notes);
14370 } else if (var->isConstexpr()) {
14371 SourceLocation DiagLoc = var->getLocation();
14380 << var << Init->getSourceRange();
14383 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14384 auto *Attr = var->getAttr<ConstInitAttr>();
14385 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14386 << Init->getSourceRange();
14387 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14388 << Attr->getRange() << Attr->isConstinit();
14393 var->getLocation())) {
14395 // warn about globals with a non-trivial destructor because we already
14397 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14398 if (!(RD && !RD->hasTrivialDestructor())) {
14403 Diag(var->getLocation(), diag::warn_global_constructor)
14404 << Init->getSourceRange();
14410 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14418 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14422 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14424 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14425 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14427 UnifySection(SA->getName(), SectionFlags, var);
14428 } else if (Stack->CurrentValue) {
14431 var->getType().isConstQualified()) {
14435 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14441 auto SectionName = Stack->CurrentValue->getString();
14442 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14443 Stack->CurrentPragmaLocation,
14446 var->dropAttr<SectionAttr>();
14452 if (CurInitSeg && var->getInit())
14453 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14467 if (!type->isDependentType())
14468 if (const RecordType *recordType = baseType->getAs<RecordType>())
14482 assert(VD->isStaticLocal());
14484 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14488 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14489 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14490 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14498 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14499 NewAttr->setInherited(true);
14500 VD->addAttr(NewAttr);
14501 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14503 NewAttr->setInherited(true);
14504 VD->addAttr(NewAttr);
14508 if (!FD->hasAttr<DLLExportAttr>())
14509 FD->addAttr(NewAttr);
14511 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14513 NewAttr->setInherited(true);
14514 VD->addAttr(NewAttr);
14519 assert(VD->getTLSKind());
14527 if (!VD->hasDependentAlignment()) {
14530 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14547 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14548 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14550 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14554 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14558 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14562 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14568 for (auto *BD : DD->bindings()) {
14569 FinalizeDeclaration(BD);
14575 if (VD->isStaticLocal())
14578 if (VD->getTLSKind())
14581 // Perform check for initializers of device-side global variables.
14584 // variables whether they are local or not. CUDA also allows
14592 // Imported static data members cannot be defined out-of-line.
14594 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14595 VD->isThisDeclarationADefinition()) {
14599 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14602 Context->getDescribedClassTemplate();
14604 Diag(VD->getLocation(),
14608 Diag(IA->getLocation(), diag::note_attribute);
14610 VD->setInvalidDecl();
14614 // dllimport/dllexport variables cannot be thread local, their TLS index
14616 if (DLLAttr && VD->getTLSKind()) {
14617 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14619 assert(VD->isStaticLocal());
14620 // But if this is a static local in a dlimport/dllexport function, the
14624 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14626 VD->setInvalidDecl();
14630 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14631 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14632 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14634 VD->dropAttr<UsedAttr>();
14637 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14638 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14639 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14641 VD->dropAttr<RetainAttr>();
14645 const DeclContext *DC = VD->getDeclContext();
14648 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14652 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14657 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14658 !VD->getType()->isIntegralOrEnumerationType())
14661 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14662 const Expr *MagicValueExpr = VD->getInit();
14667 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14668 Diag(I->getRange().getBegin(),
14670 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14673 if (MagicValueInt->getActiveBits() > 64) {
14674 Diag(I->getRange().getBegin(),
14676 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14679 uint64_t MagicValue = MagicValueInt->getZExtValue();
14680 RegisterTypeTagForDatatype(I->getArgumentKind(),
14682 I->getMatchingCType(),
14683 I->getLayoutCompatible(),
14684 I->getMustBeNull());
14690 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14712 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14713 VD->hasGlobalStorage())
14715 // For declarators, there are some additional syntactic-ish checks we need
14730 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14732 << FirstDeclaratorInGroup->getSourceRange()
14733 << DD->getSourceRange();
14741 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14743 << FirstNonDeducedAutoInGroup->getType()
14744 ->hasAutoForTrailingReturnType()
14745 << FirstDeclaratorInGroup->getSourceRange()
14746 << DD->getSourceRange();
14758 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14771 // deduction, the program is ill-formed.
14777 if (!D || D->isInvalidDecl())
14779 DeducedType *DT = D->getType()->getContainedDeducedType();
14780 if (!DT || DT->getDeducedType().isNull())
14783 Deduced = DT->getDeducedType();
14785 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14787 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14789 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14790 << DeducedDecl->getDeclName() << DT->getDeducedType()
14791 << D->getDeclName();
14792 if (DeducedDecl->hasInit())
14793 Dia << DeducedDecl->getInit()->getSourceRange();
14794 if (D->getInit())
14795 Dia << D->getInit()->getSourceRange();
14796 D->setInvalidDecl();
14818 Group[0]->getLocation()) &&
14820 Group[0]->getLocation()))
14855 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14885 "explicit parameter in non-cplusplus mode");
14888 << P->getSourceRange();
14892 if (P->isParameterPack()) {
14893 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14894 << P->getSourceRange();
14897 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14899 LSI->ExplicitObjectParameter = P;
14944 QualType parmDeclType = TInfo->getType();
14954 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14960 if (PrevDecl && S->isDeclScope(PrevDecl)) {
14962 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14979 New->setInvalidDecl();
14983 assert(S->isFunctionPrototypeScope());
14984 assert(S->getFunctionPrototypeDepth() >= 1);
14985 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14986 S->getNextFunctionPrototypeIndex());
14989 S->AddDecl(New);
14996 Diag(New->getLocation(), diag::err_module_private_local)
15000 if (New->hasAttr<BlocksAttr>()) {
15001 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15019 Param->setImplicit();
15024 // Don't diagnose unused-parameter errors in template instantiations; we
15030 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15031 !Parameter->hasAttr<UnusedAttr>() &&
15032 !Parameter->getIdentifier()->isPlaceholder()) {
15033 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15034 << Parameter->getDeclName();
15044 // Warn if the return value is pass-by-value and larger than the specified
15046 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15049 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15052 // Warn if any parameter is pass-by-value and larger than the specified
15055 QualType T = Parameter->getType();
15056 if (T->isDependentType() || !T.isPODType(Context))
15060 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15072 T->isObjCLifetimeType()) {
15077 // - if it's const, use __unsafe_unretained
15078 // - otherwise, it's an error
15079 if (T->isArrayType()) {
15087 << TSInfo->getTypeLoc().getSourceRange();
15091 lifetime = T->getObjCARCImplicitLifetime();
15103 if (New->isParameterPack())
15105 LSI->LocalPacks.push_back(New);
15107 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15108 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15109 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15114 if (T->isObjCObjectType()) {
15116 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15121 New->setType(T);
15125 // duration shall not be qualified by an address-space qualifier."
15127 // an address space.
15130 // to be qualified with an address space.
15132 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15134 // lives in a different address space.
15135 !(T->isFunctionPointerType() &&
15138 New->setInvalidDecl();
15141 // PPC MMA non-pointer types are not allowed as function argument types.
15143 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15144 New->setInvalidDecl();
15166 --i;
15171 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15203 Scope *ParentScope = FnBodyScope->getParent();
15206 // we define a non-templated function definition, we will create a declaration
15234 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15235 Prev = Prev->getPreviousDecl()) {
15238 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15242 return Prev->getType()->isFunctionProtoType();
15251 if (FD->isInvalidDecl())
15255 if (!FD->isGlobal())
15263 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15264 if (IdentifierInfo *II = FD->getIdentifier())
15265 if (II->isStr("main") || II->isStr("efi_main"))
15268 if (FD->isMSVCRTEntryPoint())
15272 if (FD->isInlined())
15276 if (FD->getDescribedFunctionTemplate())
15280 if (FD->isFunctionTemplateSpecialization())
15284 if (FD->hasAttr<OpenCLKernelAttr>())
15288 if (FD->isDeleted())
15291 // Don't warn on implicitly local functions (such as having local-typed
15293 if (!FD->isExternallyVisible())
15309 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15312 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15313 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15314 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15318 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15319 cast<Decl>(FD->getLexicalDeclContext())))
15328 // Don't emit an error when this is redefinition of a typo-corrected
15336 (Definition->getFormalLinkage() == Linkage::Internal ||
15337 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15338 Definition->getNumTemplateParameterLists())) {
15339 SkipBody->ShouldSkip = true;
15340 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15341 if (auto *TD = Definition->getDescribedFunctionTemplate())
15347 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15348 Definition->getStorageClass() == SC_Extern)
15349 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15352 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15354 Diag(Definition->getLocation(), diag::note_previous_definition);
15355 FD->setInvalidDecl();
15359 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15362 LSI->CallOperator = CallOperator;
15363 LSI->Lambda = LambdaClass;
15364 LSI->ReturnType = CallOperator->getReturnType();
15368 LSI->AfterParameterList = false;
15369 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15372 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15374 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15376 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15377 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15379 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15380 LSI->Mutable = !CallOperator->isConst();
15381 if (CallOperator->isExplicitObjectMemberFunction())
15382 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15386 auto I = LambdaClass->field_begin();
15387 for (const auto &C : LambdaClass->captures()) {
15390 if (VD->isInitCapture())
15391 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15393 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15397 I->getType(), /*Invalid*/false);
15400 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15403 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15404 I->getType());
15425 FD = FunTmpl->getTemplatedDecl();
15434 // potentially evaluated and either: its innermost enclosing non-block scope
15437 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15447 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15449 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15452 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15453 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15454 FD->dropAttr<AliasAttr>();
15455 FD->setInvalidDecl();
15457 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15458 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15459 FD->dropAttr<IFuncAttr>();
15460 FD->setInvalidDecl();
15462 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15464 !Attr->isDefaultVersion()) {
15466 // defined with non-default target_version attribute
15468 SkipBody->ShouldSkip = true;
15474 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15475 Ctor->isDefaultConstructor() &&
15485 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15486 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15490 if (SkipBody && SkipBody->ShouldSkip)
15497 FD->setWillHaveBody();
15511 if (FD->getTemplateSpecializationInfo()
15512 ->isExplicitInstantiationOrSpecialization()) {
15513 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15514 FD->setInvalidDecl();
15528 if (unsigned BuiltinID = FD->getBuiltinID()) {
15531 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15532 FD->setInvalidDecl();
15539 // shall not be a (possibly cv-qualified) class type that is incomplete
15541 QualType ResultType = FD->getReturnType();
15542 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15543 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15544 (RequireCompleteType(FD->getLocation(), ResultType,
15546 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15549 FD->setInvalidDecl();
15556 CheckParmsForFunctionDef(FD->parameters(),
15559 // Add non-parameter declarations already in the function to the current
15562 for (Decl *NPD : FD->decls()) {
15570 if (NonParmDecl->getDeclName())
15576 for (auto *EI : ED->enumerators())
15583 for (auto *Param : FD->parameters()) {
15584 Param->setOwningFunction(FD);
15587 if (Param->getIdentifier() && FnBodyScope) {
15600 !FD->isInvalidDecl() && !FD->isInlined() &&
15602 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15603 !FD->isTemplateInstantiation()) {
15604 assert(FD->isThisDeclarationADefinition());
15605 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15606 FD->setInvalidDecl();
15610 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15611 ResolveExceptionSpec(D->getLocation(), FPT);
15613 // dllimport cannot be applied to non-inline function definitions.
15614 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15615 !FD->isTemplateInstantiation()) {
15616 assert(!FD->hasAttr<DLLExportAttr>());
15617 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15618 FD->setInvalidDecl();
15629 if (getCurLexicalContext()->isObjCContainer() &&
15630 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15631 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15632 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15638 if (!FD || FD->isInvalidDecl())
15641 FD = TD->getTemplatedDecl();
15642 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15652 ReturnStmt **Returns = Scope->Returns.data();
15654 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15655 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15656 if (!NRVOCandidate->isNRVOVariable())
15657 Returns[I]->setNRVOCandidate(nullptr);
15670 // If the placeholder introduces a non-deduced trailing return type,
15673 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15677 return Ty.isNull() || !Ty->isUndeducedType();
15692 if (const FunctionDecl *FD = D->getAsFunction()) {
15693 if (FD->isConstexpr())
15698 if (FD->getReturnType()->getContainedDeducedType())
15707 if (FunctionDecl *FD = Decl->getAsFunction())
15708 FD->setHasSkippedBody();
15710 MD->setHasSkippedBody();
15736 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15737 if (EscapeInfo.count(BD))
15738 return EscapeInfo[BD];
15741 const BlockDecl *CurBD = BD;
15744 R = !CurBD->doesNotEscape();
15747 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15750 return EscapeInfo[BD] = R;
15759 << FixItHint::CreateInsertion(P.first, "self->");
15763 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15764 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15772 return FD->isStatic() &&
15777 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15778 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15783 if (!FD->hasAttr<CoroWrapperAttr>())
15784 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15790 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15792 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15793 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15799 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15800 if (FSI->isCoroutine())
15813 // the declaration as deleted, and if the deleted-function-body contains
15821 if (!FD->isDeletedAsWritten())
15822 FD->setBody(Body);
15823 FD->setWillHaveBody(false);
15827 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15828 FD->getReturnType()->isUndeducedType()) {
15831 // possibly cv-qualified or constrained, but not ref-qualified.
15832 if (!FD->getReturnType()->getAs<AutoType>()) {
15833 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15834 << FD->getReturnType();
15835 FD->setInvalidDecl();
15840 FD, dcl->getLocation(), Dummy,
15841 FD->getReturnType()->getAs<AutoType>()))
15842 FD->setInvalidDecl();
15849 if (LSI->HasImplicitReturnType) {
15853 // [...] if there are no return statements in the compound-statement
15856 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15859 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15860 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15861 Proto->getExtProtoInfo()));
15867 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15871 // defined at class scope, warn about this non-standard construct.
15872 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
15873 !FD->isOutOfLine())
15874 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15876 if (!FD->isInvalidDecl()) {
15879 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15880 !FD->hasAttr<NakedAttr>())
15881 DiagnoseUnusedParameters(FD->parameters());
15882 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15883 FD->getReturnType(), FD);
15887 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15890 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15895 if (FD->getReturnType()->isRecordType() &&
15896 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15900 // GNU warning -Wmissing-prototypes:
15907 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15911 // but that could be a zero-parameter prototype
15912 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15913 TypeLoc TL = TI->getTypeLoc();
15915 Diag(PossiblePrototype->getLocation(),
15917 << (FD->getNumParams() != 0)
15918 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15939 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15949 if ((FD->getReturnType()->isAnyPointerType() &&
15950 FD->getReturnType()->getPointeeType().isConstQualified()) ||
15951 FD->getReturnType().isConstQualified()) {
15954 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15957 return FD->getBeginLoc();
15959 return FD->getTypeSpecStartLoc();
15961 Diag(FD->getTypeSpecStartLoc(),
15964 << (FD->getStorageClass() == SC_None
15988 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15989 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15990 !PossiblePrototype->isImplicit()))) {
16004 // -Wstrict-prototypes is enabled. If we already warned about it being
16011 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16014 // If we have a possible prototype for the function which is a user-
16017 // note because it's the same behavior-changing problem as with the
16020 Diag(PossiblePrototype->getLocation(),
16027 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16029 if (!CmpndBody->body_empty())
16030 Diag(CmpndBody->body_front()->getBeginLoc(),
16035 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16036 MD->isVirtual() &&
16037 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16038 MD == KeyFunction->getCanonicalDecl()) {
16039 // Update the key-function state if necessary for this ABI.
16040 if (FD->isInlined() &&
16044 // If the newly-chosen key function is already defined, then we
16046 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16048 if (KeyFunction && KeyFunction->isDefined(Definition))
16049 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16052 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16061 MD->setBody(Body);
16062 if (!MD->isInvalidDecl()) {
16063 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16064 MD->getReturnType(), MD);
16069 if (FSI->ObjCShouldCallSuper) {
16070 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16071 << MD->getSelector().getAsString();
16072 FSI->ObjCShouldCallSuper = false;
16074 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16077 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16082 auto IFace = MD->getClassInterface();
16085 auto SuperD = IFace->getSuperClass();
16088 return SuperD->getIdentifier() ==
16089 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16093 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16094 Diag(MD->getLocation(),
16096 Diag(InitMethod->getLocation(),
16099 FSI->ObjCWarnForNoDesignatedInitChain = false;
16101 if (FSI->ObjCWarnForNoInitDelegation) {
16103 if (!MD->isUnavailable())
16104 Diag(MD->getLocation(),
16106 FSI->ObjCWarnForNoInitDelegation = false;
16117 if (Body && FSI->HasPotentialAvailabilityViolations)
16120 assert(!FSI->ObjCShouldCallSuper &&
16124 // Verify and clean out per-function state.
16125 if (Body && (!FD || !FD->isDefaulted())) {
16126 // C++ constructors that have function-try-blocks can't have return
16133 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16137 if (!Destructor->getParent()->isDependentType())
16140 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16141 Destructor->getParent());
16153 // Since the body is valid, issue any analysis-based warnings that are
16159 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16160 !FD->isInvalidDecl() &&
16162 FD->setInvalidDecl();
16164 if (FD && FD->hasAttr<NakedAttr>()) {
16165 for (const Stmt *S : Body->children()) {
16166 // Allow local register variables without initializer as they don't
16170 for (const auto *Decl : DS->decls()) {
16173 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16182 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16183 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16184 FD->setInvalidDecl();
16196 "Leftover expressions for odr-use checking");
16222 if (FD && !FD->isDeleted())
16223 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16234 D = TD->getTemplatedDecl();
16239 if (Method->isStatic())
16255 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16256 BlockScope = BlockScope->getParent();
16263 while (!ContextScope->getEntity() ||
16264 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16265 !ContextScope->getEntity()->isTranslationUnit()))
16266 ContextScope = ContextScope->getParent();
16267 ContextRAII SavedContext(*this, ContextScope->getEntity());
16270 // function, see whether there was a locally-scoped declaration of
16272 // (non-visible) declaration, and complain about it.
16276 // that later (non-call) uses can see it.
16284 cast<FunctionDecl>(ExternCPrev)->getType(),
16288 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16297 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16308 // consumers use typo-correction callbacks to enhance the main diagnostic.
16322 Diagnose = !D->isImplicit();
16368 FD->setImplicit();
16377 if (FD->isInvalidDecl())
16380 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16381 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16386 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16390 // An allocation function that has a non-throwing exception specification
16395 // However, -fcheck-new invalidates this possible assumption, so don't add
16397 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16399 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16408 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16412 // storage. If it is successful, it returns the address of the start of a
16415 if (!FD->hasAttr<AllocSizeAttr>()) {
16416 FD->addAttr(AllocSizeAttr::CreateImplicit(
16418 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16423 // call shall represent the address of storage that is aligned as follows:
16427 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16428 FD->addAttr(AllocAlignAttr::CreateImplicit(
16429 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16435 // call shall represent the address of storage that is aligned as follows:
16438 // new-extended alignment ([basic.align]) and is no larger than the
16441 // have new-extended alignment and is of the requested size.
16445 if (FD->isInvalidDecl())
16448 // If this is a built-in function, map its builtin attributes to
16450 if (unsigned BuiltinID = FD->getBuiltinID()) {
16451 // Handle printf-formatting attributes.
16455 if (!FD->hasAttr<FormatAttr>()) {
16457 unsigned int NumParams = FD->getNumParams();
16459 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16461 FD->addAttr(FormatAttr::CreateImplicit(Context,
16465 FD->getLocation()));
16470 if (!FD->hasAttr<FormatAttr>())
16471 FD->addAttr(FormatAttr::CreateImplicit(Context,
16475 FD->getLocation()));
16480 if (!FD->hasAttr<CallbackAttr>() &&
16482 FD->addAttr(CallbackAttr::CreateImplicit(
16483 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16494 if (!FD->hasAttr<ConstAttr>() &&
16499 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16506 !FD->hasAttr<ConstAttr>()) {
16514 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16522 !FD->hasAttr<ReturnsTwiceAttr>())
16523 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16524 FD->getLocation()));
16525 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16526 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16527 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16528 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16529 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16530 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16532 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16538 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16540 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16547 if (!FD->hasAttr<AllocAlignAttr>())
16548 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16549 FD->getLocation()));
16558 FD->addAttr(AllocSizeAttr::CreateImplicit(
16559 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16564 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16565 ParamIdx(), FD->getLocation()));
16568 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16569 ParamIdx(), FD->getLocation()));
16585 if (ParmVarDecl *P = FD->getParamDecl(0u);
16586 !P->hasAttr<LifetimeBoundAttr>())
16587 P->addAttr(
16588 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16601 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16602 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16603 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16604 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16607 IdentifierInfo *Name = FD->getIdentifier();
16610 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16611 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16612 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16614 // Okay: this could be a libc/libm/Objective-C function we know
16619 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16621 // target-specific builtins, perhaps?
16622 if (!FD->hasAttr<FormatAttr>())
16623 FD->addAttr(FormatAttr::CreateImplicit(Context,
16625 Name->isStr("vasprintf") ? 0 : 3,
16626 FD->getLocation()));
16629 if (Name->isStr("__CFStringMakeConstantString")) {
16631 // but builds that use -fno-constant-cfstrings don't go through that.
16632 if (!FD->hasAttr<FormatArgAttr>())
16633 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16634 FD->getLocation()));
16655 NewTD->setInvalidDecl();
16660 if (CurContext->isFunctionOrMethod())
16661 Diag(NewTD->getLocation(), diag::err_module_private_local)
16667 NewTD->setModulePrivate();
16672 // enum), the first typedef-name declared by the declaration
16695 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16696 QualType T = TI->getType();
16698 if (T->isDependentType())
16703 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16704 if (BT->isInteger())
16708 << T << T->isBitIntType();
16714 if (IsScoped != Prev->isScoped()) {
16716 << Prev->isScoped();
16717 Diag(Prev->getLocation(), diag::note_previous_declaration);
16721 if (IsFixed && Prev->isFixed()) {
16722 if (!EnumUnderlyingTy->isDependentType() &&
16723 !Prev->getIntegerType()->isDependentType() &&
16725 Prev->getIntegerType())) {
16728 << EnumUnderlyingTy << Prev->getIntegerType();
16729 Diag(Prev->getLocation(), diag::note_previous_declaration)
16730 << Prev->getIntegerTypeRange();
16733 } else if (IsFixed != Prev->isFixed()) {
16735 << Prev->isFixed();
16736 Diag(Prev->getLocation(), diag::note_previous_declaration);
16760 /// Determine if tag kind is a class-key compatible with
16800 // The class-key or enum keyword present in the
16801 // elaborated-type-specifier shall agree in kind with the
16802 // declaration to which the name in the elaborated-type-specifier
16804 // elaborated-type-specifier that declares a class-name or
16807 // elaborated-type-specifier, the enum keyword shall be used to
16808 // refer to an enumeration (7.2), the union class-key shall be
16810 // struct class-key shall be used to refer to a class (clause 9)
16811 // declared using the class or struct class-key.
16812 TagTypeKind OldTag = Previous->getTagKind();
16818 // Non-class tags can't be mismatched at this point.
16822 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16835 return IsIgnoredLoc(Tag->getLocation());
16838 Previous = Previous->getPreviousDecl();
16841 OldTag = Previous->getTagKind();
16846 isTemplate = Record->getDescribedClassTemplate();
16850 // In a template instantiation, do not offer fix-its for tag mismatches
16861 // On definitions, check all previous tags and issue a fix-it for each
16863 if (Previous->getDefinition()) {
16864 // Don't suggest fix-its for redefinitions.
16869 for (const TagDecl *I : Previous->redecls()) {
16870 if (I->getTagKind() != NewTag) {
16879 << getRedeclDiagFromTagKind(I->getTagKind());
16881 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16883 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16891 // there is a non-ignored definition), or otherwise the kind of the prior
16892 // (non-ignored) declaration.
16893 const TagDecl *PrevDef = Previous->getDefinition();
16897 if (Redecl->getTagKind() != NewTag) {
16901 Diag(Redecl->getLocation(), diag::note_previous_use);
16903 // If there is a previous definition, suggest a fix-it.
16906 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16908 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16930 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16931 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16935 if (!Namespace || Namespace->isAnonymousNamespace())
16937 IdentifierInfo *II = Namespace->getIdentifier();
16949 if (DC->isTranslationUnit())
16953 OS << II->getName() << "::";
16960 /// using-declaration).
16963 OldDC = OldDC->getRedeclContext();
16964 NewDC = NewDC->getRedeclContext();
16966 if (OldDC->Equals(NewDC))
16972 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17004 // for non-C++ cases.
17013 // If an elaborated-type-specifier is the sole constituent of a
17014 // declaration, the declaration is ill-formed unless it is an explicit
17018 // If the enum-head-name of an opaque-enum-declaration contains a
17019 // nested-name-specifier, the declaration shall be an explicit
17036 if (TemplateParams->size() > 0) {
17047 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17052 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17065 // If an elaborated-type-specifier appears with the friend specifier as
17066 // an entire member-declaration, the member-declaration shall have one
17068 // friend class-key nested-name-specifier(opt) identifier ;
17069 // friend class-key simple-template-id ;
17070 // friend class-key nested-name-specifier template(opt)
17071 // simple-template-id ;
17073 // Since enum is not a class-key, so declarations like "friend enum E;"
17074 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17095 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17096 // integral type; any cv-qualification is ignored.
17105 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17112 // the underlying type unless the user enables -fms-compatibility. This
17128 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17131 auto createTagFromNewDecl = [&]() -> TagDecl * {
17148 ED->setIntegerTypeSourceInfo(TI);
17150 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17151 QualType EnumTy = ED->getIntegerType();
17152 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17172 (!SkipBody || !SkipBody->ShouldSkip)) {
17177 New->setLexicalDeclContext(CurContext);
17183 // We have a nested-name tag ('struct foo::bar').
17212 // Look-up name inside 'foo::'.
17220 // nested-name-specifier refers to the current instantiation,
17223 // this as a dependent elaborated-type-specifier.
17224 // But this only makes any sense for reference-like lookups.
17242 // -- every member of class T that is itself a type
17261 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17262 SearchDC->getRedeclContext()))
17270 // a template-id and the declaration is a function or an
17271 // elaborated-type-specifier, the lookup to determine whether
17282 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17287 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17288 if (DC->isFileContext() &&
17289 !EnclosingNS->Encloses(ND->getDeclContext())) {
17317 SearchDC = SearchDC->getParent();
17323 SearchDC = SearchDC->getParent();
17329 SearchDC = SearchDC->getParent();
17333 Previous.getFoundDecl()->isTemplateParameter()) {
17341 DC->Equals(getStdNamespace())) {
17342 if (Name->isStr("bad_alloc")) {
17351 } else if (Name->isStr("align_val_t")) {
17370 // -- for an elaborated-type-specifier of the form
17372 // class-key identifier
17374 // if the elaborated-type-specifier is used in the
17375 // decl-specifier-seq or parameter-declaration-clause of a
17377 // declared as a class-name in the namespace that contains
17380 // non-class, non-function-prototype scope that contains the
17406 // If a friend declaration in a non-local class first declares a
17409 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17410 : SearchDC->getEnclosingNamespaceContext();
17417 // type declared by an elaborated-type-specifier. In C that is not correct
17431 if (Previous.empty() && SkipBody && SkipBody->Previous)
17432 Previous.addDecl(SkipBody->Previous);
17442 // This is also okay for elaborated-type-specifiers, which is
17445 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17448 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17449 TagDecl *Tag = TT->getDecl();
17450 if (Tag->getDeclName() == Name &&
17451 Tag->getDeclContext()->getRedeclContext()
17452 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17471 *this, OldTag->getDeclContext(), SearchDC))) {
17473 Diag(Shadow->getTargetDecl()->getLocation(),
17475 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17496 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17502 PrevTagDecl->getKindName());
17505 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17508 Kind = PrevTagDecl->getTagKind();
17518 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17525 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17539 // A member shall not be declared twice in the member-specification,
17542 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17543 S->isDeclScope(PrevDecl)) {
17545 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17556 (PrevTagDecl->getFriendObjectKind() ==
17558 PrevDecl->getOwningModule() != getCurrentModule()) &&
17567 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17568 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17580 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17588 RD->getTemplateSpecializationKind() !=
17592 ED->getTemplateSpecializationKind() !=
17596 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17611 SkipBody->CheckSameAsPrevious = true;
17612 SkipBody->New = createTagFromNewDecl();
17613 SkipBody->Previous = Def;
17616 SkipBody->ShouldSkip = true;
17617 SkipBody->Previous = Def;
17625 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17641 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17642 if (TD->isBeingDefined()) {
17644 Diag(PrevTagDecl->getLocation(),
17660 SearchDC = PrevTagDecl->getDeclContext();
17675 // is non-NULL, it's a definition of the tag declared by
17682 // Use a better diagnostic if an elaborated-type-specifier
17684 // (non-redeclaration) lookup.
17690 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17702 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17711 << Name << Kind << TND->getUnderlyingType();
17712 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17754 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17760 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17761 // C++0x: 7.2p2: opaque-enum-declaration.
17764 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17767 Diag(Def->getLocation(), diag::note_previous_definition);
17781 ED->setIntegerTypeSourceInfo(TI);
17783 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17784 QualType EnumTy = ED->getIntegerType();
17785 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17788 assert(ED->isComplete() && "enum with type should be complete");
17800 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17810 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17811 << (OOK == OOK_Macro) << New->getSourceRange();
17814 // A type-specifier-seq shall not define a class or enumeration [...].
17818 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17824 DC->getDeclKind() == Decl::Enum) {
17825 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17834 // nested-name-specifier against the current context.
17841 New->setQualifierInfo(SS.getWithLocInContext(Context));
17843 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17860 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17868 Diag(New->getLocation(), diag::err_module_private_specialization)
17871 // __module_private__ does not apply to local classes. However, we only
17874 else if (!SearchDC->isFunctionOrMethod())
17875 New->setModulePrivate();
17887 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17902 New->setInvalidDecl();
17906 New->setLexicalDeclContext(CurContext);
17913 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17916 if (!Invalid && SearchDC->isRecord())
17922 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
17923 New->startDefinition();
17933 New->setAccess(PrevDecl->getAccess());
17935 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17936 DC->makeDeclVisibleInContext(New);
17944 CurContext->addDecl(New);
17948 if (IdentifierInfo *II = New->getIdentifier())
17949 if (!New->isInvalidDecl() &&
17950 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17951 II->isStr("FILE"))
17966 if (isMemberSpecialization && !New->isInvalidDecl())
17973 if (New->isBeingDefined())
17975 RD->completeDefinition();
17977 } else if (SkipBody && SkipBody->ShouldSkip) {
17978 return SkipBody->Previous;
18015 FieldCollector->StartClass();
18017 if (!Record->getIdentifier())
18021 Record->markAbstract();
18024 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18030 // [...] The class-name is also inserted into the scope of the
18031 // class itself; this is known as the injected-class-name. For
18032 // purposes of access checking, the injected-class-name is treated
18035 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18036 Record->getLocation(), Record->getIdentifier(),
18040 InjectedClassName->setImplicit();
18041 InjectedClassName->setAccess(AS_public);
18042 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18043 InjectedClassName->setDescribedClassTemplate(Template);
18045 assert(InjectedClassName->isInjectedClassName() &&
18046 "Broken injected-class-name");
18053 Tag->setBraceRange(BraceRange);
18056 if (Tag->isBeingDefined()) {
18057 assert(Tag->isInvalidDecl() && "We should already have completed it");
18059 RD->completeDefinition();
18063 FieldCollector->FinishClass();
18064 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18065 auto *Def = RD->getDefinition();
18068 for (auto *Method : Def->methods()) {
18069 if (!Method->getIdentifier())
18071 if (Method->getName() == "__init")
18074 if (NumInitMethods > 1 || !Def->hasInitMethod())
18075 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18084 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18085 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18091 if (getCurLexicalContext()->isObjCContainer() &&
18092 Tag->getDeclContext()->isFileContext())
18093 Tag->setTopLevelDeclInObjCContainer();
18096 if (!Tag->isInvalidDecl())
18111 if (llvm::any_of(RD->fields(),
18112 [](const FieldDecl *FD) { return FD->isBitField(); }))
18120 Tag->setInvalidDecl();
18123 if (Tag->isBeingDefined()) {
18125 RD->completeDefinition();
18141 if (BitWidth->containsErrors())
18144 // C99 6.7.2.1p4 - verify the field type.
18145 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18146 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18153 << FieldName << FieldTy << BitWidth->getSourceRange();
18155 << FieldTy << BitWidth->getSourceRange();
18160 // If the bit-width is type- or value-dependent, don't try to check
18162 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18171 // Zero-width bitfield is ok for anonymous field.
18174 << FieldName << BitWidth->getSourceRange();
18184 // The size of the bit-field must not exceed our maximum permitted object
18191 if (!FieldTy->isDependentType()) {
18196 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18214 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18249 QualType T = TInfo->getType();
18293 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18310 if (NewFD->isInvalidDecl())
18311 Record->setInvalidDecl();
18314 NewFD->setModulePrivate();
18316 if (NewFD->isInvalidDecl() && PrevDecl) {
18322 Record->addDecl(NewFD);
18337 if (D) InvalidDecl = D->isInvalidType();
18339 // If we receive a broken type, recover by assuming 'int' and
18341 if (T.isNull() || T->containsErrors()) {
18347 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18351 Record->setInvalidDecl();
18355 EltTy->isIncompleteType(&Def);
18356 if (Def && Def->isInvalidDecl()) {
18357 Record->setInvalidDecl();
18363 // TR 18037 does not allow fields to be declared with address space
18364 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18365 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18367 Record->setInvalidDecl();
18372 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18374 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18375 T->isBlockPointerType()) {
18377 Record->setInvalidDecl();
18389 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18398 if (!InvalidDecl && T->isVariablyModifiedType()) {
18412 // If this is declared as a bit-field, check the bit-field.
18415 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18425 if (T->isReferenceType())
18433 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18434 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18445 // brace-or-equal-initializer.
18452 NewFD->setInvalidDecl();
18455 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18457 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18458 NewFD->setInvalidDecl();
18462 if (Record->isUnion()) {
18463 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18464 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18465 if (RDecl->getDefinition()) {
18466 // C++ [class.union]p1: An object of a class with a non-trivial
18467 // constructor, a non-trivial copy constructor, a non-trivial
18468 // destructor, or a non-trivial copy assignment operator
18472 NewFD->setInvalidDecl();
18477 // the program is ill-formed, except when compiling with MSVC extensions
18479 if (EltTy->isReferenceType()) {
18480 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18483 << NewFD->getDeclName() << EltTy;
18485 NewFD->setInvalidDecl();
18496 if (NewFD->hasAttrs())
18500 // In auto-retain/release, infer strong retension for fields of
18503 NewFD->setInvalidDecl();
18508 // PPC MMA non-pointer types are not allowed as field types.
18510 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18511 NewFD->setInvalidDecl();
18513 NewFD->setAccess(AS);
18521 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18524 QualType EltTy = Context.getBaseElementType(FD->getType());
18525 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18526 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18527 if (RDecl->getDefinition()) {
18533 // We're required to check for any non-trivial constructors. Since the
18535 // user-declared constructors, we just need to check that there is a
18538 if (RDecl->hasNonTrivialCopyConstructor())
18540 else if (!RDecl->hasTrivialDefaultConstructor())
18542 else if (RDecl->hasNonTrivialCopyAssignment())
18544 else if (RDecl->hasNonTrivialDestructor())
18549 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18550 // Objective-C++ ARC: it is an error to have a non-trivial field of
18551 // a union. However, system headers in Objective-C programs
18552 // occasionally have Objective-C lifetime objects within unions,
18555 SourceLocation Loc = FD->getLocation();
18557 if (!FD->hasAttr<UnavailableAttr>())
18558 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18565 FD->getLocation(),
18569 << FD->getParent()->isUnion() << FD->getDeclName()
18585 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18588 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18593 if (!CD->IsClassExtension())
18623 if (!Record->hasUserDeclaredDestructor()) {
18627 SourceLocation Loc = Record->getLocation();
18630 for (auto *Decl : Record->decls()) {
18632 if (DD->isInvalidDecl())
18634 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18636 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18650 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18665 // OpenCL have got their own thing going with destructors. It's slightly broken,
18670 Record->setInvalidDecl();
18677 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18683 /// - they are both default constructors,
18684 /// - they are both copy or move constructors with the same first parameter
18686 /// - they are both copy or move assignment operators with the same first
18687 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18692 // We don't want to compare templates to non-templates: See
18693 // https://github.com/llvm/llvm-project/issues/59206
18695 return bool(M1->getDescribedFunctionTemplate()) ==
18696 bool(M2->getDescribedFunctionTemplate());
18699 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18700 M2->getNonObjectParameter(0)->getType()))
18702 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18703 M2->getFunctionObjectParameterReferenceType()))
18711 /// - the function is not deleted,
18712 /// - the associated constraints, if any, are satisfied, and
18713 /// - no special member function of the same kind whose associated constraints
18721 const Expr *Constraints = Method->getTrailingRequiresClause();
18738 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18741 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18747 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18754 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18774 Method->setIneligibleOrNotSelected(false);
18775 Record->addedEligibleSpecialMemberFunction(Method,
18789 for (auto *Decl : Record->decls()) {
18794 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18799 if (CD->isInvalidDecl())
18801 if (CD->isDefaultConstructor())
18803 else if (CD->isCopyConstructor())
18805 else if (CD->isMoveConstructor())
18807 } else if (MD->isCopyAssignmentOperator()) {
18809 } else if (MD->isMoveAssignmentOperator()) {
18832 // If this is an Objective-C @implementation or category and we have
18837 switch (DC->getKind()) {
18840 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18844 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18856 for (const auto *I : Record->decls()) {
18858 if (IFD->getDeclName())
18871 const Type *FDTy = FD->getType().getTypePtr();
18873 if (!FD->isAnonymousStructOrUnion()) {
18880 if (FD->isInvalidDecl()) {
18881 EnclosingDecl->setInvalidDecl();
18896 if (FDTy->isFunctionType()) {
18898 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18899 << FD->getDeclName();
18900 FD->setInvalidDecl();
18901 EnclosingDecl->setInvalidDecl();
18903 } else if (FDTy->isIncompleteArrayType() &&
18911 if (!Record->isUnion() && !IsLastField) {
18912 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18913 << FD->getDeclName() << FD->getType()
18914 << llvm::to_underlying(Record->getTagKind());
18915 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18916 FD->setInvalidDecl();
18917 EnclosingDecl->setInvalidDecl();
18919 } else if (Record->isUnion())
18929 Diag(FD->getLocation(), DiagID)
18930 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18936 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18937 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18938 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18940 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18941 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18943 // If the element type has a non-trivial destructor, we would not
18948 QualType BaseElem = Context.getBaseElementType(FD->getType());
18949 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18950 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18951 << FD->getDeclName() << FD->getType();
18952 FD->setInvalidDecl();
18953 EnclosingDecl->setInvalidDecl();
18957 Record->setHasFlexibleArrayMember(true);
18963 } else if (!FDTy->isDependentType() &&
18965 FD->getLocation(), FD->getType(),
18968 FD->setInvalidDecl();
18969 EnclosingDecl->setInvalidDecl();
18971 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18972 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18975 Record->setHasFlexibleArrayMember(true);
18976 if (!Record->isUnion()) {
18981 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18982 << FD->getDeclName() << FD->getType();
18986 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18987 << FD->getDeclName();
18992 RequireNonAbstractType(FD->getLocation(), FD->getType(),
18996 FD->setInvalidDecl();
18998 if (Record && FDTTy->getDecl()->hasObjectMember())
18999 Record->setHasObjectMember(true);
19000 if (Record && FDTTy->getDecl()->hasVolatileMember())
19001 Record->setHasVolatileMember(true);
19002 } else if (FDTy->isObjCObjectType()) {
19003 /// A field cannot be an Objective-c object
19004 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19005 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19006 QualType T = Context.getObjCObjectPointerType(FD->getType());
19007 FD->setType(T);
19008 } else if (Record && Record->isUnion() &&
19009 FD->getType().hasNonTrivialObjCLifetime() &&
19010 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19011 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19012 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19013 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19015 // headers that have non-trivial ObjC ownership qualifications are marked
19020 FD->addAttr(UnavailableAttr::CreateImplicit(
19022 FD->getLocation()));
19025 !Record->hasObjectMember()) {
19026 if (FD->getType()->isObjCObjectPointerType() ||
19027 FD->getType().isObjCGCStrong())
19028 Record->setHasObjectMember(true);
19029 else if (Context.getAsArrayType(FD->getType())) {
19030 QualType BaseType = Context.getBaseElementType(FD->getType());
19031 if (BaseType->isRecordType() &&
19032 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19033 Record->setHasObjectMember(true);
19034 else if (BaseType->isObjCObjectPointerType() ||
19036 Record->setHasObjectMember(true);
19042 QualType FT = FD->getType();
19044 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19046 Record->isUnion())
19047 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19051 Record->setNonTrivialToPrimitiveCopy(true);
19052 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19053 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19056 Record->setNonTrivialToPrimitiveDestroy(true);
19057 Record->setParamDestroyedInCallee(true);
19058 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19059 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19062 if (const auto *RT = FT->getAs<RecordType>()) {
19063 if (RT->getDecl()->getArgPassingRestrictions() ==
19065 Record->setArgPassingRestrictions(
19068 Record->setArgPassingRestrictions(
19072 if (Record && FD->getType().isVolatileQualified())
19073 Record->setHasVolatileMember(true);
19075 if (FD->getIdentifier())
19083 Scope *Parent = S->getParent();
19084 if (Parent && Parent->isTypeAliasScope() &&
19085 Parent->isTemplateParamScope())
19086 Record->setInvalidDecl();
19090 if (!CXXRecord->isInvalidDecl()) {
19091 // Set access bits correctly on the directly-declared conversions.
19093 I = CXXRecord->conversion_begin(),
19094 E = CXXRecord->conversion_end(); I != E; ++I)
19095 I.setAccess((*I)->getAccess());
19098 // Add any implicitly-declared members to this class.
19101 if (!CXXRecord->isDependentType()) {
19102 if (!CXXRecord->isInvalidDecl()) {
19106 if (CXXRecord->getNumVBases()) {
19108 CXXRecord->getFinalOverriders(FinalOverriders);
19113 for (OverridingMethods::iterator SO = M->second.begin(),
19114 SOEnd = M->second.end();
19116 assert(SO->second.size() > 0 &&
19118 if (SO->second.size() == 1)
19124 // program is ill-formed.
19125 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19126 << (const NamedDecl *)M->first << Record;
19127 Diag(M->first->getLocation(),
19130 OM = SO->second.begin(),
19131 OMEnd = SO->second.end();
19133 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19134 << (const NamedDecl *)M->first << OM->Method->getParent();
19136 Record->setInvalidDecl();
19139 CXXRecord->completeDefinition(&FinalOverriders);
19149 Record->completeDefinition();
19159 // Clang. This happens when a non-forward declared / defined type is
19170 return !TD->isCompleteDefinition();
19173 QualType FieldType = FD->getType().getDesugaredType(Context);
19175 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19176 return PointeeType.getDesugaredType(Context)->isFunctionType();
19184 (Record->hasAttr<RandomizeLayoutAttr>() ||
19185 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19186 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19187 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19188 !Record->isRandomized()) {
19192 Record->reorderDecls(NewDeclOrdering);
19197 auto *Dtor = CXXRecord->getDestructor();
19198 if (Dtor && Dtor->isImplicit() &&
19200 CXXRecord->setImplicitDestructorIsDeleted();
19201 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19205 if (Record->hasAttrs()) {
19208 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19210 IA->getRange(), IA->getBestCase(),
19211 IA->getInheritanceModel());
19224 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19225 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19226 CXXRecord->isCLike();
19232 for (RecordDecl::field_iterator I = Record->field_begin(),
19233 E = Record->field_end();
19236 if (I->isUnnamedBitField()) {
19237 if (!I->isZeroLengthBitField(Context))
19241 QualType FieldType = I->getType();
19242 if (FieldType->isIncompleteType() ||
19255 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19263 << Record->isUnion();
19270 ID->setEndOfDefinitionLoc(RBrac);
19273 ClsFields[i]->setLexicalDeclContext(ID);
19274 ID->addDecl(ClsFields[i]);
19278 if (ID->getSuperClass())
19279 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19282 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19286 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19289 IMPDecl->setIvarLBraceLoc(LBrac);
19290 IMPDecl->setIvarRBraceLoc(RBrac);
19296 // CDecl->setLocEnd(RBrac);
19299 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19303 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19304 Diag(ClsFields[i]->getLocation(),
19306 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19309 for (const auto *Ext : IDecl->known_extensions()) {
19311 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19312 Diag(ClsFields[i]->getLocation(),
19314 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19319 ClsFields[i]->setLexicalDeclContext(CDecl);
19320 CDecl->addDecl(ClsFields[i]);
19322 CDecl->setIvarLBraceLoc(LBrac);
19323 CDecl->setIvarRBraceLoc(RBrac);
19334 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19339 if (T->isSignedIntegerOrEnumerationType())
19340 --BitWidth;
19351 assert((T->isIntegralType(Context) ||
19352 T->isEnumeralType()) && "Integral type required!");
19363 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19388 if (Enum->isDependentType() || Val->isTypeDependent() ||
19389 Val->containsErrors())
19394 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19396 // constant-expression in the enumerator-definition shall be a converted
19398 EltTy = Enum->getIntegerType();
19406 } else if (!Val->isValueDependent() &&
19412 if (Enum->isComplete()) {
19413 EltTy = Enum->getIntegerType();
19415 // In Obj-C and Microsoft mode, require the enumeration value to be
19417 // we perform a non-narrowing conversion as part of converted constant
19431 EltTy->isBooleanType() ? CK_IntegralToBoolean
19438 // - If an initializer is specified for an enumerator, the
19440 EltTy = Val->getType();
19450 << toString(EnumVal, 10) << Val->getSourceRange()
19452 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19456 EltTy = Val->getType();
19463 if (Enum->isDependentType())
19469 // - If no initializer is specified for the first enumerator, the
19474 if (Enum->isFixed()) {
19475 EltTy = Enum->getIntegerType();
19482 EnumVal = LastEnumConst->getInitVal();
19484 EltTy = LastEnumConst->getType();
19487 if (EnumVal < LastEnumConst->getInitVal()) {
19492 // - Otherwise the type of the initializing value is the same as
19497 // exists, the program is ill-formed.
19499 if (T.isNull() || Enum->isFixed()) {
19502 EnumVal = LastEnumConst->getInitVal();
19505 if (Enum->isFixed())
19506 // When the underlying type is fixed, this is ill-formed.
19520 EnumVal = LastEnumConst->getInitVal();
19521 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19533 !EltTy->isDependentType() &&
19542 if (!EltTy->isDependentType()) {
19546 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19568 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19570 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19598 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19608 // - every enumerator of every member of class T that is an unscoped
19610 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19611 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19620 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19645 New->setAccess(TheEnumDecl->getAccess());
19657 // Element2 = Element1 - 1
19660 Expr *InitExpr = ECD->getInitExpr();
19663 InitExpr = InitExpr->IgnoreImpCasts();
19666 if (!BO->isAdditiveOp())
19668 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19671 if (IL->getValue() != 1)
19674 InitExpr = BO->getLHS();
19682 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19686 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19698 if (!Enum->getIdentifier())
19702 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19705 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19718 llvm::APSInt Val = D->getInitVal();
19731 // this constant. Skip this enum since it may be ill-formed.
19737 if (ECD->getInitExpr())
19758 DeclOrVector& Entry = Iter->second;
19766 Vec->push_back(D);
19767 Vec->push_back(ECD);
19780 if (*Vec->begin() == ECD)
19783 Vec->push_back(ECD);
19788 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19791 auto *FirstECD = Vec->front();
19792 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19793 << FirstECD << toString(FirstECD->getInitVal(), 10)
19794 << FirstECD->getSourceRange();
19799 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19800 << ECD << toString(ECD->getInitVal(), 10)
19801 << ECD->getSourceRange();
19807 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19808 assert(ED->isCompleteDefinition() && "expected enum definition");
19811 llvm::APInt &FlagBits = R.first->second;
19814 for (auto *E : ED->enumerators()) {
19815 const auto &EVal = E->getInitVal();
19816 // Only single-bit enumerators introduce new flag values.
19843 if (Enum->isDependentType()) {
19849 ECD->setType(EnumType);
19852 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19873 const llvm::APSInt &InitVal = ECD->getInitVal();
19889 // If the enumerator-list is empty, the values of the enumeration are as if
19909 bool Packed = Enum->hasAttr<PackedAttr>();
19910 // -fshort-enums is the equivalent to specifying the packed attribute on all
19917 if (Enum->isComplete()) {
19918 BestType = Enum->getIntegerType();
19949 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19981 // This can happen with bit-precise integer types, but those are not
19984 // a 128-bit integer, we should consider doing the same.
19985 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20007 llvm::APSInt InitVal = ECD->getInitVal();
20015 !Enum->isFixed() &&
20020 } else if (ECD->getType() == BestType) {
20024 // enum-specifier, each enumerator has the type of its
20026 ECD->setType(EnumType);
20031 NewSign = BestType->isSignedIntegerOrEnumerationType();
20037 ECD->setInitVal(Context, InitVal);
20040 if (ECD->getInitExpr() &&
20041 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20042 ECD->setInitExpr(ImplicitCastExpr::Create(
20043 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20047 // enum-specifier, each enumerator has the type of its
20049 ECD->setType(EnumType);
20051 ECD->setType(NewTy);
20054 Enum->completeDefinition(BestType, BestPromotionType,
20059 if (Enum->isClosedFlag()) {
20064 llvm::APSInt InitVal = ECD->getInitVal();
20067 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20073 if (Enum->hasAttrs())
20085 CurContext->addDecl(New);
20091 CurContext->addDecl(New);
20099 D->setStmt(Statement);
20115 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20123 PrevDecl->addAttr(Attr);
20125 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20138 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20154 if (!PrevDecl->hasAttr<AliasAttr>())
20164 assert(FD && "Expected non-null FunctionDecl");
20168 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20172 if (FD->isDependentContext())
20177 // We have to check the GVA linkage of the function's *definition* -- if we
20180 const FunctionDecl *Def = FD->getDefinition();
20190 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20212 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20224 // (Technically, we do emit a host-side stub for global functions, but this
20237 // Otherwise, the function is known-emitted if it's in our set of
20238 // known-emitted functions.
20243 // Host-side references to a __global__ function refer to the stub, so the
20249 // known-emitted.